ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: tooling/cli/src/signer/generate.rs (Rust)

Code before:
    options.password.replace("".into());
  }
  let keypair = generate_key(options.password).expect("Failed to generate key");

  if let Some(output_path) = options.write_keys {
    let (secret_path, public_path) =
      save_keypair(options.force, output_path, &keypair.sk, &keypair.pk)
        .expect("Unable to write keypair");

    println!(
        "\nYour keypair was generated successfully\nPrivate: {} (Keep it secret!)\nPublic: {}\n---------------------------",
        display_path(secret_path),
        display_path(public_path)
        )
  } else {
    println!(
      "\nYour secret key was generated successfully - Keep it secret!\n{}\n\n",
      keypair.sk
    );
    println!(
          "Your public key was generated successfully:\n{}\n\nAdd the public key in your tauri.conf.json\n---------------------------\n",
          keypair.pk
        );
  }

  println!("\nEnvironment variables used to sign:\n`TAURI_SIGNINING_PRIVATE_KEY`  Path or String of your private key\n`TAURI_SIGNINING_PRIVATE_KEY_PASSWORD`  Your private key password (optional)\n\nATTENTION: If you lose your private key OR password, you'll not be able to sign your update package and updates will not work.\n---------------------------\n");

  Ok(())
}


Review comment (suggestion):
```suggestion
  println!("\nEnvironment variables used to sign:\n`TAURI_SIGNING_PRIVATE_KEY`  Path or String of your private key\n`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`  Your private key password (optional)\n\nATTENTION: If you lose your private key OR password, you'll not be able to sign your update package and updates will not work.\n---------------------------\n");
```

Code after:
    options.password.replace("".into());
  }
  let keypair = generate_key(options.password).expect("Failed to generate key");

  if let Some(output_path) = options.write_keys {
    let (secret_path, public_path) =
      save_keypair(options.force, output_path, &keypair.sk, &keypair.pk)
        .expect("Unable to write keypair");

    println!(
        "\nYour keypair was generated successfully\nPrivate: {} (Keep it secret!)\nPublic: {}\n---------------------------",
        display_path(secret_path),
        display_path(public_path)
        )
  } else {
    println!(
      "\nYour secret key was generated successfully - Keep it secret!\n{}\n\n",
      keypair.sk
    );
    println!(
          "Your public key was generated successfully:\n{}\n\nAdd the public key in your tauri.conf.json\n---------------------------\n",
          keypair.pk
        );
  }

  println!("\nEnvironment variables used to sign:\n`TAURI_SIGNING_PRIVATE_KEY`  Path or String of your private key\n`TAURI_SIGNING_PRIVATE_KEY_PASSWORD`  Your private key password (optional)\n\nATTENTION: If you lose your private key OR password, you'll not be able to sign your update package and updates will not work.\n---------------------------\n");

  Ok(())
}
Repository: tauri-apps/tauri
File: tooling/cli/src/completions.rs (Rust)

Code before:
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::Result;
use anyhow::Context;
use clap::{Command, Parser};
use clap_complete::{generate, Shell};
use log::info;

use std::{fs::write, path::PathBuf};

const PKG_MANAGERS: &[&str] = &["cargo", "pnpm", "npm", "yarn"];

#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate Tauri CLI shell completions for Bash, Zsh, PowerShell and Fish")]
pub struct Options {
  /// Shell to generate a completion script for.
  #[clap(short, long, verbatim_doc_comment)]
  shell: Shell,
  /// Output file for the shell completions. By default the completions are printed to stdout.
  #[clap(short, long)]
  output: Option<PathBuf>,
}

fn completions_for(shell: Shell, manager: &'static str, cmd: Command) -> Vec<u8> {
  let tauri = cmd.name("tauri");
  let mut command = if manager == "npm" {
    Command::new(manager)
      .bin_name(manager)
      .subcommand(Command::new("run").subcommand(tauri))
  } else {
    Command::new(manager).bin_name(manager).subcommand(tauri)
  };

  let mut buf = Vec::new();
  generate(shell, &mut command, manager, &mut buf);
  buf
}

fn get_completions(shell: Shell, cmd: Command) -> Result<String> {

Review comment (suggestion):
```suggestion
#[clap(about = "Generate Tauri CLI shell completions for Bash, Zsh, PowerShell or Fish")]
```

Code after:
// Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::Result;
use anyhow::Context;
use clap::{Command, Parser};
use clap_complete::{generate, Shell};
use log::info;

use std::{fs::write, path::PathBuf};

const PKG_MANAGERS: &[&str] = &["cargo", "pnpm", "npm", "yarn"];

#[derive(Debug, Clone, Parser)]
#[clap(about = "Generate Tauri CLI shell completions for Bash, Zsh, PowerShell or Fish")]
pub struct Options {
  /// Shell to generate a completion script for.
  #[clap(short, long, verbatim_doc_comment)]
  shell: Shell,
  /// Output file for the shell completions. By default the completions are printed to stdout.
  #[clap(short, long)]
  output: Option<PathBuf>,
}

fn completions_for(shell: Shell, manager: &'static str, cmd: Command) -> Vec<u8> {
  let tauri = cmd.name("tauri");
  let mut command = if manager == "npm" {
    Command::new(manager)
      .bin_name(manager)
      .subcommand(Command::new("run").subcommand(tauri))
  } else {
    Command::new(manager).bin_name(manager).subcommand(tauri)
  };

  let mut buf = Vec::new();
  generate(shell, &mut command, manager, &mut buf);
  buf
}

fn get_completions(shell: Shell, cmd: Command) -> Result<String> {
Repository: tauri-apps/tauri
File: tooling/cli/src/init.rs (Rust)

Code before:
    resolve_tauri_path, template,
  },
  VersionMetadata,
};
use std::{
  collections::BTreeMap,
  env::current_dir,
  fmt::Display,
  fs::{read_to_string, remove_dir_all},
  path::PathBuf,
  str::FromStr,
};

use crate::Result;
use anyhow::Context;
use clap::Parser;
use dialoguer::Input;
use handlebars::{to_json, Handlebars};
use include_dir::{include_dir, Dir};
use log::warn;

const TEMPLATE_DIR: Dir<'_> = include_dir!("templates/app");
const TAURI_CONF_TEMPLATE: &str = include_str!("../templates/tauri.conf.json");

#[derive(Debug, Parser)]
#[clap(about = "Initialize a tauri project in an existing directory")]
pub struct Options {
  /// Skip prompting for values
  #[clap(long)]
  ci: bool,
  /// Force init to overwrite the src-tauri folder
  #[clap(short, long)]
  force: bool,
  /// Enables logging
  #[clap(short, long)]
  log: bool,
  /// Set target directory for init
  #[clap(short, long)]
  #[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
  directory: String,
  /// Path of the Tauri project to use (relative to the cwd)
  #[clap(short, long)]
  tauri_path: Option<PathBuf>,
  /// Name of your Tauri application
  #[clap(short = 'A', long)]
  app_name: Option<String>,
  /// Window title of your Tauri application
  #[clap(short = 'W', long)]
  window_title: Option<String>,
  /// Web assets location, relative to <project-dir>/src-tauri
  #[clap(short = 'D', long)]

Review comment (suggestion):
```suggestion
#[clap(about = "Initialize a Tauri project in an existing directory")]
```

Code after:
    resolve_tauri_path, template,
  },
  VersionMetadata,
};
use std::{
  collections::BTreeMap,
  env::current_dir,
  fmt::Display,
  fs::{read_to_string, remove_dir_all},
  path::PathBuf,
  str::FromStr,
};

use crate::Result;
use anyhow::Context;
use clap::Parser;
use dialoguer::Input;
use handlebars::{to_json, Handlebars};
use include_dir::{include_dir, Dir};
use log::warn;

const TEMPLATE_DIR: Dir<'_> = include_dir!("templates/app");
const TAURI_CONF_TEMPLATE: &str = include_str!("../templates/tauri.conf.json");

#[derive(Debug, Parser)]
#[clap(about = "Initialize a Tauri project in an existing directory")]
pub struct Options {
  /// Skip prompting for values
  #[clap(long)]
  ci: bool,
  /// Force init to overwrite the src-tauri folder
  #[clap(short, long)]
  force: bool,
  /// Enables logging
  #[clap(short, long)]
  log: bool,
  /// Set target directory for init
  #[clap(short, long)]
  #[clap(default_value_t = current_dir().expect("failed to read cwd").display().to_string())]
  directory: String,
  /// Path of the Tauri project to use (relative to the cwd)
  #[clap(short, long)]
  tauri_path: Option<PathBuf>,
  /// Name of your Tauri application
  #[clap(short = 'A', long)]
  app_name: Option<String>,
  /// Window title of your Tauri application
  #[clap(short = 'W', long)]
  window_title: Option<String>,
  /// Web assets location, relative to <project-dir>/src-tauri
  #[clap(short = 'D', long)]
Repository: tauri-apps/tauri
File: tooling/api/src/mocks.ts (TypeScript)

Code before:

/**
 * Mock `convertFileSrc` function
 *
 *
 * @example
 * ```js
 * import { mockConvertFileSrc } from "@tauri-apps/api/mocks";
 * import { convertFileSrc } from "@tauri-apps/api/tauri";
 *
 * mockConvertFileSrc("windows")
 *
 * const url = convertFileSrc("C:\\Users\\user\\file.txt")
 * ```
 *
 * @param osName The operating system to mock, can be one of linux, macos, or windows
 * @param windowsProtocolScheme The scheme to use on Windows, can be either `http` or `https` and defaults to `https`
 *
 * @since 1.6.0
 */
export function mockConvertFileSrc(
  osName: string,
  windowsProtocolScheme = 'https'
): void {
  window.__TAURI__.convertFileSrc = function (filePath, protocol = 'asset') {
    const path = encodeURIComponent(filePath)
    return osName === 'windows'
      ? `${windowsProtocolScheme}://${protocol}.localhost/${path}`
      : `${protocol}://localhost/${path}`
  }
}

/**
 * Clears mocked functions/data injected by the other functions in this module.
 * When using a test runner that doesn't provide a fresh window object for each test, calling this function will reset tauri specific properties.
 *
 * # Example
 *
 * ```js
 * import { mockWindows, clearMocks } from "@tauri-apps/api/mocks"
 *
 * afterEach(() => {
 *    clearMocks()
 * })
 *
 * test("mocked windows", () => {
 *    mockWindows("main", "second", "third");
 *
 *    expect(window).toHaveProperty("__TAURI_METADATA__")
 * })
 *

Review comment (suggestion):
```suggestion
  window.__TAURI__ = window.__TAURI__ ?? {};
  window.__TAURI__.convertFileSrc = function (filePath, protocol = 'asset') {
```

Code after:

/**
 * Mock `convertFileSrc` function
 *
 *
 * @example
 * ```js
 * import { mockConvertFileSrc } from "@tauri-apps/api/mocks";
 * import { convertFileSrc } from "@tauri-apps/api/tauri";
 *
 * mockConvertFileSrc("windows")
 *
 * const url = convertFileSrc("C:\\Users\\user\\file.txt")
 * ```
 *
 * @param osName The operating system to mock, can be one of linux, macos, or windows
 * @param windowsProtocolScheme The scheme to use on Windows, can be either `http` or `https` and defaults to `https`
 *
 * @since 1.6.0
 */
export function mockConvertFileSrc(
  osName: string,
  windowsProtocolScheme = 'https'
): void {
  window.__TAURI__ = window.__TAURI__ ?? {}
  window.__TAURI__.convertFileSrc = function (filePath, protocol = 'asset') {
    const path = encodeURIComponent(filePath)
    return osName === 'windows'
      ? `${windowsProtocolScheme}://${protocol}.localhost/${path}`
      : `${protocol}://localhost/${path}`
  }
}

/**
 * Clears mocked functions/data injected by the other functions in this module.
 * When using a test runner that doesn't provide a fresh window object for each test, calling this function will reset tauri specific properties.
 *
 * # Example
 *
 * ```js
 * import { mockWindows, clearMocks } from "@tauri-apps/api/mocks"
 *
 * afterEach(() => {
 *    clearMocks()
 * })
 *
 * test("mocked windows", () => {
 *    mockWindows("main", "second", "third");
 *
 *    expect(window).toHaveProperty("__TAURI_METADATA__")
 * })
Repository: tauri-apps/tauri
File: tooling/cli/src/plugin.rs (Rust)

Code before:
}

#[derive(Subcommand)]
enum Commands {
  New(new::Options),
  Init(init::Options),
  Android(android::Cli),
  Ios(ios::Cli),
}

pub fn command(cli: Cli) -> Result<()> {
  match cli.command {
    Commands::New(options) => new::command(options)?,
    Commands::Init(options) => init::command(options)?,
    Commands::Android(cli) => android::command(cli)?,
    Commands::Ios(cli) => ios::command(cli)?,
  }

  Ok(())
}

fn infer_plugin_name<P: AsRef<Path>>(directory: P) -> Result<String> {
  let dir = directory.as_ref();
  let carg_toml_path = dir.join("Cargo.toml");
  let name = if carg_toml_path.exists() {
    let contents = std::fs::read(carg_toml_path)?;
    let cargo_toml: toml::Value = toml::from_slice(&contents)?;
    cargo_toml
      .get("package")
      .and_then(|v| v.get("name"))
      .map(|v| v.as_str().unwrap_or_default())
      .unwrap_or_default()
      .to_string()
  } else {
    dir
      .file_name()
      .unwrap_or_default()
      .to_string_lossy()
      .to_string()
  };
  Ok(
    name
      .strip_prefix("tauri-plugin-")
      .unwrap_or(&name)
      .to_string(),
  )
}


Review comment (suggestion):
```suggestion
  let cargo_toml_path = dir.join("Cargo.toml");
  let name = if cargo_toml_path.exists() {
    let contents = std::fs::read(cargo_toml_path)?;
```

Code after:
}

#[derive(Subcommand)]
enum Commands {
  New(new::Options),
  Init(init::Options),
  Android(android::Cli),
  Ios(ios::Cli),
}

pub fn command(cli: Cli) -> Result<()> {
  match cli.command {
    Commands::New(options) => new::command(options)?,
    Commands::Init(options) => init::command(options)?,
    Commands::Android(cli) => android::command(cli)?,
    Commands::Ios(cli) => ios::command(cli)?,
  }

  Ok(())
}

fn infer_plugin_name<P: AsRef<Path>>(directory: P) -> Result<String> {
  let dir = directory.as_ref();
  let cargo_toml_path = dir.join("Cargo.toml");
  let name = if cargo_toml_path.exists() {
    let contents = std::fs::read(cargo_toml_path)?;
    let cargo_toml: toml::Value = toml::from_slice(&contents)?;
    cargo_toml
      .get("package")
      .and_then(|v| v.get("name"))
      .map(|v| v.as_str().unwrap_or_default())
      .unwrap_or_default()
      .to_string()
  } else {
    dir
      .file_name()
      .unwrap_or_default()
      .to_string_lossy()
      .to_string()
  };
  Ok(
    name
      .strip_prefix("tauri-plugin-")
      .unwrap_or(&name)
      .to_string(),
  )
}
Repository: tauri-apps/tauri
File: tooling/cli/templates/plugin/__example-api/tauri-app/vite.config.js (JavaScript)

Code before:
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { internalIpV4 } from 'internal-ip'

// https://vitejs.dev/config/
export default defineConfig(async ({
  command,
  mode
}) => {
  const host =
    process.env.TAURI_ENV_PLATFORM === 'android' ||
    process.env.TAURI_ENV_PLATFORM === 'ios' ?
    await internalIpV4() :
    'localhost'
  return {

    plugins: [svelte()],

    // Vite optons tailored for Tauri development and only applied in `tauri dev` or `tauri build`
    // prevent vite from obscuring rust errors
    clearScreen: false,
    // tauri expects a fixed port, fail if that port is not available
    server: {
      host: '0.0.0.0',
      port: 1420,
      strictPort: true,
      hmr: {
        protocol: 'ws',
        host,
        port: 1420
      },
    },
    // to make use of `TAURI_ENV_DEBUG` and other env variables
    // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
    envPrefix: ["VITE_", "TAURI_ENV_"],
    build: {
      // Tauri supports es2021
      target: ["es2021", "chrome100", "safari13"],
      // don't minify for debug builds

Review comment (suggestion):
```suggestion
  const mobile = !!/android|ios/.exec(process.env.TAURI_ENV_PLATFORM);
```

Code after:
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { internalIpV4Sync } from 'internal-ip'

const mobile = !!/android|ios/.exec(process.env.TAURI_ENV_PLATFORM);

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte()],

  // Vite optons tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  // prevent vite from obscuring rust errors
  clearScreen: false,
  // tauri expects a fixed port, fail if that port is not available
  server: {
    host: mobile ? "0.0.0.0" : false,
    port: 1420,
    strictPort: true,
    hmr: mobile ? {
      protocol: 'ws',
      host: internalIpV4Sync(),
      port: 1421
    } : undefined,
  },
})
Repository: tauri-apps/tauri
File: tooling/cli/templates/plugin/__example-api/tauri-app/vite.config.js (JavaScript)

Code before:
export default defineConfig(async ({
  command,
  mode
}) => {
  const host =
    process.env.TAURI_ENV_PLATFORM === 'android' ||
    process.env.TAURI_ENV_PLATFORM === 'ios' ?
    await internalIpV4() :
    'localhost'
  return {

    plugins: [svelte()],

    // Vite optons tailored for Tauri development and only applied in `tauri dev` or `tauri build`
    // prevent vite from obscuring rust errors
    clearScreen: false,
    // tauri expects a fixed port, fail if that port is not available
    server: {
      host: '0.0.0.0',
      port: 1420,
      strictPort: true,
      hmr: {
        protocol: 'ws',
        host,
        port: 1420
      },
    },
    // to make use of `TAURI_ENV_DEBUG` and other env variables
    // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
    envPrefix: ["VITE_", "TAURI_ENV_"],
    build: {
      // Tauri supports es2021
      target: ["es2021", "chrome100", "safari13"],
      // don't minify for debug builds
      minify: !process.env.TAURI_ENV_DEBUG ? "esbuild" : false,
      // produce sourcemaps for debug builds
      sourcemap: !!process.env.TAURI_ENV_DEBUG,
    },
  }
});


Review comment (suggestion):
```suggestion
    server: {
    port: 1420,
    strictPort: true,
    host: mobile ? "0.0.0.0" : false,
    hmr: mobile
      ? {
          protocol: "ws",
          host: await internalIpV4(),
          port: 1421,
        }
      : undefined,
  },	
```

Code after:
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { internalIpV4Sync } from 'internal-ip'

const mobile = !!/android|ios/.exec(process.env.TAURI_ENV_PLATFORM);

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svelte()],

  // Vite optons tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  // prevent vite from obscuring rust errors
  clearScreen: false,
  // tauri expects a fixed port, fail if that port is not available
  server: {
    host: mobile ? "0.0.0.0" : false,
    port: 1420,
    strictPort: true,
    hmr: mobile ? {
      protocol: 'ws',
      host: internalIpV4Sync(),
      port: 1421
    } : undefined,
  },
})
Repository: tauri-apps/tauri
File: core/tauri/src/test/mod.rs (Rust)

Code before:
pub use mock_runtime::*;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value as JsonValue;

use std::{
  borrow::Cow,
  collections::HashMap,
  fmt::Debug,
  hash::{Hash, Hasher},
  sync::{
    mpsc::{channel, Sender},
    Arc, Mutex,
  },
};

use crate::hooks::window_invoke_responder;
#[cfg(shell_scope)]
use crate::ShellScopeConfig;
use crate::{api::ipc::CallbackFn, App, Builder, Context, InvokePayload, Manager, Pattern, Window};
use tauri_utils::{
  assets::{AssetKey, Assets, CspHash},
  config::{CliConfig, Config, PatternKind, TauriConfig},
};

/// Hash structure f
#[derive(Eq, PartialEq)]
pub struct IpcKey {
  /// callback
  pub callback: CallbackFn,
  /// error callback
  pub error: CallbackFn,
}

impl Hash for IpcKey {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.callback.0.hash(state);
    self.error.0.hash(state);
  }
}

/// Structure to retrieve result of a Tauri command
pub struct Ipc(Mutex<HashMap<IpcKey, Sender<std::result::Result<JsonValue, JsonValue>>>>);

impl Ipc {
  /// Insert an `Ipc` which will be used by the Tauri backend to send back the result of a Tauri
  /// command
  pub fn insert_ipc(&self, key: IpcKey, tx: Sender<std::result::Result<JsonValue, JsonValue>>) {
    self.0.lock().unwrap().insert(key, tx);
  }


Review comment (suggestion):
```suggestion
/// A key for an [`Ipc`] call.
```

Code after:
pub use mock_runtime::*;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value as JsonValue;

use std::{
  borrow::Cow,
  collections::HashMap,
  fmt::Debug,
  hash::{Hash, Hasher},
  sync::{
    mpsc::{channel, Sender},
    Arc, Mutex,
  },
};

use crate::hooks::window_invoke_responder;
#[cfg(shell_scope)]
use crate::ShellScopeConfig;
use crate::{api::ipc::CallbackFn, App, Builder, Context, InvokePayload, Manager, Pattern, Window};
use tauri_utils::{
  assets::{AssetKey, Assets, CspHash},
  config::{CliConfig, Config, PatternKind, TauriConfig},
};

/// A key for an [`Ipc`] call.
#[derive(Eq, PartialEq)]
struct IpcKey {
  /// callback
  callback: CallbackFn,
  /// error callback
  error: CallbackFn,
}

impl Hash for IpcKey {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.callback.0.hash(state);
    self.error.0.hash(state);
  }
}

/// Structure to retrieve result of a Tauri command
struct Ipc(Mutex<HashMap<IpcKey, Sender<std::result::Result<JsonValue, JsonValue>>>>);

/// An empty [`Assets`] implementation.
pub struct NoopAsset {
  csp_hashes: Vec<CspHash<'static>>,
}

impl Assets for NoopAsset {
  fn get(&self, key: &AssetKey) -> Option<Cow<'_, [u8]>> {