ronantakizawa/codereview-bench huggingface dataset:
Repository: tauri-apps/tauri
File: packages/api/src/menu/base.ts (TypeScript)

Code before:
          | MenuItemOptions
          | SubmenuOptions
          | IconMenuItemOptions
          | PredefinedMenuItemOptions
          | CheckMenuItemOptions
      ):
        | [number, string]
        | SubmenuOptions
        | PredefinedMenuItemOptions
        | MenuItemOptions
        | IconMenuItemOptions
        | CheckMenuItemOptions {
        if ('rid' in i) {
          return [i.rid, i.kind]
        }

        if ('item' in i && typeof i.item === 'object' && i.item.About?.icon) {
          i.item.About.icon = transformImage(i.item.About.icon)
        }

        if ('icon' in i && i.icon) {
          i.icon = transformImage(i.icon)
        }

        if ('items' in i && i.items) {
          // @ts-expect-error the `perpareItem` return doesn't exactly match
          // this is fine, because the difference is in `[number, string]` variant
          i.items = i.items.map(prepareItem)
        }

        return injectChannel(i)
      }

      opts.items = (opts.items as []).map(prepareItem)
    }
  }

  return invoke('plugin:menu|new', {
    kind,
    options: opts,
    handler
  })
}

export class MenuItemBase extends Resource {
  /** @ignore */
  readonly #id: string
  /** @ignore */
  readonly #kind: ItemKind

  /** The id of this item. */

Review comment (suggestion):
```suggestion
          // @ts-expect-error the `prepareItem` return doesn't exactly match
```

Code after:
          | MenuItemOptions
          | SubmenuOptions
          | IconMenuItemOptions
          | PredefinedMenuItemOptions
          | CheckMenuItemOptions
      ):
        | [number, string]
        | SubmenuOptions
        | PredefinedMenuItemOptions
        | MenuItemOptions
        | IconMenuItemOptions
        | CheckMenuItemOptions {
        if ('rid' in i) {
          return [i.rid, i.kind]
        }

        if ('item' in i && typeof i.item === 'object' && i.item.About?.icon) {
          i.item.About.icon = transformImage(i.item.About.icon)
        }

        if ('icon' in i && i.icon) {
          i.icon = transformImage(i.icon)
        }

        if ('items' in i && i.items) {
          // @ts-expect-error the `prepareItem` return doesn't exactly match
          // this is fine, because the difference is in `[number, string]` variant
          i.items = i.items.map(prepareItem)
        }

        return injectChannel(i)
      }

      opts.items = (opts.items as []).map(prepareItem)
    }
  }

  return invoke('plugin:menu|new', {
    kind,
    options: opts,
    handler
  })
}

export class MenuItemBase extends Resource {
  /** @ignore */
  readonly #id: string
  /** @ignore */
  readonly #kind: ItemKind

  /** The id of this item. */
Repository: tauri-apps/tauri
File: crates/tauri-runtime-wry/src/lib.rs (Rust)

Code before:
  if let Some(proxy_url) = webview_attributes.proxy_url {
    let config = parse_proxy_url(&proxy_url)?;

    webview_builder = webview_builder.with_proxy_config(config);
  }

  #[cfg(windows)]
  {
    if let Some(additional_browser_args) = webview_attributes.additional_browser_args {
      webview_builder = webview_builder.with_additional_browser_args(&additional_browser_args);
    }

    webview_builder = webview_builder.with_theme(match window.theme() {
      TaoTheme::Dark => wry::Theme::Dark,
      TaoTheme::Light => wry::Theme::Light,
      _ => wry::Theme::Light,
    });
  }

  #[cfg(windows)]
  {
    webview_builder = webview_builder
      .with_browser_extensions_enabled(webview_attributes.browser_extensions_enabled);
  }

  #[cfg(any(windows, target_os = "linux"))]
  {
    if let Some(path) = &webview_attributes.extensions_path {
      webview_builder = webview_builder.with_extension_path(path);
    }
  }

  webview_builder = webview_builder.with_ipc_handler(create_ipc_handler(
    kind,
    window_id.clone(),
    id,
    context.clone(),
    label.clone(),
    ipc_handler,
  ));

  for script in webview_attributes.initialization_scripts {
    webview_builder = webview_builder.with_initialization_script(&script);
  }

  for (scheme, protocol) in uri_scheme_protocols {
    // on Linux the custom protocols are associated with the web context
    // and you cannot register a scheme more than once
    #[cfg(any(
      target_os = "linux",
      target_os = "dragonfly",

Review comment (suggestion):
```suggestion
  #[cfg(any(
    windows,
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
  ))]
```

Code after:
  if let Some(proxy_url) = webview_attributes.proxy_url {
    let config = parse_proxy_url(&proxy_url)?;

    webview_builder = webview_builder.with_proxy_config(config);
  }

  #[cfg(windows)]
  {
    if let Some(additional_browser_args) = webview_attributes.additional_browser_args {
      webview_builder = webview_builder.with_additional_browser_args(&additional_browser_args);
    }

    webview_builder = webview_builder.with_theme(match window.theme() {
      TaoTheme::Dark => wry::Theme::Dark,
      TaoTheme::Light => wry::Theme::Light,
      _ => wry::Theme::Light,
    });
  }

  #[cfg(windows)]
  {
    webview_builder = webview_builder
      .with_browser_extensions_enabled(webview_attributes.browser_extensions_enabled);
  }

  #[cfg(any(
    windows,
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "netbsd",
    target_os = "openbsd"
  ))]
  {
    if let Some(path) = &webview_attributes.extensions_path {
      webview_builder = webview_builder.with_extension_path(path);
    }
  }

  webview_builder = webview_builder.with_ipc_handler(create_ipc_handler(
    kind,
    window_id.clone(),
    id,
    context.clone(),
    label.clone(),
    ipc_handler,
  ));

  for script in webview_attributes.initialization_scripts {
    webview_builder = webview_builder.with_initialization_script(&script);
  }
Repository: tauri-apps/tauri
File: packages/api/src/index.ts (TypeScript)

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

/**
 * The Tauri API allows you to interface with the backend layer.
 *
 * This module exposes all other modules as an object where the key is the module name, and the value is the module exports.
 * @example
 * ```typescript
 * import { event, window, path } from '@tauri-apps/api'
 * ```
 *
 * ### Vanilla JS API
 *
 * The above import syntax is for TypeScript. If you're using vanilla JavaScript, use `window.__TAURI__` instead. It requires `app.withGlobalTauri` configuration option enabled.
 *
 * @example
 * ```js
 * const { event, window: tauriWindow, path } = window.__TAURI__;
 * ```
 *
 * @module
 */

import * as app from './app'
import * as core from './core'
import * as dpi from './dpi'
import * as event from './event'
import * as image from './image'
import * as menu from './menu'
import * as mocks from './mocks'
import * as path from './path'
import * as tray from './tray'
import * as webview from './webview'
import * as webviewWindow from './webviewWindow'
import * as window from './window'

export {
  app,
  core,

Review comment (suggestion):
I think it would be more accurate to say JavaScript with bundler, what do you think about
```suggestion
 * The above import syntax is for JavaScript/TypeScript with a bundler. If you're using vanilla JavaScript, you can use the global `window.__TAURI__` object instead. It requires `app.withGlobalTauri` configuration option enabled.
```


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

/**
 * The Tauri API allows you to interface with the backend layer.
 *
 * This module exposes all other modules as an object where the key is the module name, and the value is the module exports.
 * @example
 * ```typescript
 * import { event, window, path } from '@tauri-apps/api'
 * ```
 *
 * ### Vanilla JS API
 *
 * The above import syntax is for JavaScript/TypeScript with a bundler. If you're using vanilla JavaScript, you can use the global `window.__TAURI__` object instead. It requires `app.withGlobalTauri` configuration option enabled.
 *
 * @example
 * ```js
 * const { event, window: tauriWindow, path } = window.__TAURI__;
 * ```
 *
 * @module
 */

import * as app from './app'
import * as core from './core'
import * as dpi from './dpi'
import * as event from './event'
import * as image from './image'
import * as menu from './menu'
import * as mocks from './mocks'
import * as path from './path'
import * as tray from './tray'
import * as webview from './webview'
import * as webviewWindow from './webviewWindow'
import * as window from './window'

export {
  app,
  core,
Repository: tauri-apps/tauri
File: crates/tauri-cli/src/info/env_system.rs (Rust)

Code before:
  pkg_conf_version("librsvg-2.0")
}

#[cfg(target_os = "macos")]
fn is_xcode_command_line_tools_installed() -> bool {
  Command::new("xcode-select")
    .arg("-p")
    .output()
    .map(|o| o.status.success())
    .unwrap_or(false)
}
fn de_and_session() -> String {
  #[cfg(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  ))]
  return {
    let de = std::env::var("DESKTOP_SESSION");
    let session = std::env::var("XDG_SESSION_TYPE");
    format!(
      " ({} on {})",
      de.as_str().unwrap_or("Unknown DE"),
      session.as_str().unwrap_or("Unknown Session")
    )
  };

  #[cfg(not(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  )))]
  String::new()
}

pub fn items() -> Vec<SectionItem> {
  vec![
    SectionItem::new().action(|| {
      let os_info = os_info::get();
      format!(
        "OS: {} {} {} ({:?}){}",
        os_info.os_type(),
        os_info.version(),
        os_info.architecture().unwrap_or("Unknown Architecture"),
        os_info.bitness(),
        de_and_session(),
      ).into()

Review comment (suggestion):
```suggestion
      de.as_deref().unwrap_or("Unknown DE"),
      session.as_deref().unwrap_or("Unknown Session")
```

Code after:
  pkg_conf_version("librsvg-2.0")
}

#[cfg(target_os = "macos")]
fn is_xcode_command_line_tools_installed() -> bool {
  Command::new("xcode-select")
    .arg("-p")
    .output()
    .map(|o| o.status.success())
    .unwrap_or(false)
}
fn de_and_session() -> String {
  #[cfg(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  ))]
  return {
    let de = std::env::var("DESKTOP_SESSION");
    let session = std::env::var("XDG_SESSION_TYPE");
    format!(
      " ({} on {})",
      de.as_deref().unwrap_or("Unknown DE"),
      session.as_deref().unwrap_or("Unknown Session")
    )
  };

  #[cfg(not(any(
    target_os = "linux",
    target_os = "dragonfly",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd"
  )))]
  String::new()
}

pub fn items() -> Vec<SectionItem> {
  vec![
    SectionItem::new().action(|| {
      let os_info = os_info::get();
      format!(
        "OS: {} {} {} ({:?}){}",
        os_info.os_type(),
        os_info.version(),
        os_info.architecture().unwrap_or("Unknown Architecture"),
        os_info.bitness(),
        de_and_session(),
      ).into()
Repository: tauri-apps/tauri
File: packages/api/src/window.ts (TypeScript)

Code before:
    })
  }

  /**
   * Starts resize-dragging the window.
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().startResizeDragging();
   * ```
   *
   * @return A promise indicating the success or failure of the operation.
   */
  async startResizeDragging(direction: ResizeDirection): Promise<void> {
    return invoke('plugin:window|start_resize_dragging', {
      label: this.label,
      value: direction
    })
  }

  /**
   * Sets the badge count. It is app wide and not specific to this window.
   *
   * #### Platform-specific
   *
   * - **Windows**: Use `setOverlayIcon` instead.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeCount(5);
   * ```
   *
   * @param count The badge count. Set undefined to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeCount(count?: number): Promise<void> {
    return invoke('plugin:window|set_badge_count', {
      label: this.label,
      value: count
    })
  }

  /**
   * Sets the badge cont **macOS only**.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeLabel("Hello");
   * ```

Review comment (suggestion):
```suggestion
   * - **Windows**: Unsupported. Use @{linkcode Window.setOverlayIcon} instead.
```

Code after:
    })
  }

  /**
   * Starts resize-dragging the window.
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().startResizeDragging();
   * ```
   *
   * @return A promise indicating the success or failure of the operation.
   */
  async startResizeDragging(direction: ResizeDirection): Promise<void> {
    return invoke('plugin:window|start_resize_dragging', {
      label: this.label,
      value: direction
    })
  }

  /**
   * Sets the badge count. It is app wide and not specific to this window.
   *
   * #### Platform-specific
   *
   * - **Windows**: Unsupported. Use @{linkcode Window.setOverlayIcon} instead.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeCount(5);
   * ```
   *
   * @param count The badge count. Use `undefined` to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeCount(count?: number): Promise<void> {
    return invoke('plugin:window|set_badge_count', {
      label: this.label,
      value: count
    })
  }

  /**
   * Sets the badge cont **macOS only**.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeLabel("Hello");
   * ```
Repository: tauri-apps/tauri
File: packages/api/src/window.ts (TypeScript)

Code before:
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeCount(5);
   * ```
   *
   * @param count The badge count. Set undefined to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeCount(count?: number): Promise<void> {
    return invoke('plugin:window|set_badge_count', {
      label: this.label,
      value: count
    })
  }

  /**
   * Sets the badge cont **macOS only**.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeLabel("Hello");
   * ```
   *
   * @param label The badge label. Set undefined to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeLabel(label?: string): Promise<void> {
    return invoke('plugin:window|set_badge_label', {
      label: this.label,
      value: label
    })
  }

  /**
   * Sets the overlay icon. **Windows only**
   * The overlay icon can be set for every window.
   *
   *
   * Note that you may need the `image-ico` or `image-png` Cargo features to use this API.
   * To enable it, change your Cargo.toml file:
   *
   * ```toml
   * [dependencies]
   * tauri = { version = "...", features = ["...", "image-png"] }
   * ```
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';

Review comment (suggestion):
```suggestion
   * @param label The badge label. Use `undefined` to remove the badge.
```

Code after:
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeCount(5);
   * ```
   *
   * @param count The badge count. Use `undefined` to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeCount(count?: number): Promise<void> {
    return invoke('plugin:window|set_badge_count', {
      label: this.label,
      value: count
    })
  }

  /**
   * Sets the badge cont **macOS only**.
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
   * await getCurrentWindow().setBadgeLabel("Hello");
   * ```
   *
   * @param label The badge label. Use `undefined` to remove the badge.
   * @return A promise indicating the success or failure of the operation.
   */
  async setBadgeLabel(label?: string): Promise<void> {
    return invoke('plugin:window|set_badge_label', {
      label: this.label,
      value: label
    })
  }

  /**
   * Sets the overlay icon. **Windows only**
   * The overlay icon can be set for every window.
   *
   *
   * Note that you may need the `image-ico` or `image-png` Cargo features to use this API.
   * To enable it, change your Cargo.toml file:
   *
   * ```toml
   * [dependencies]
   * tauri = { version = "...", features = ["...", "image-png"] }
   * ```
   *
   * @example
   * ```typescript
   * import { getCurrentWindow } from '@tauri-apps/api/window';
Repository: tauri-apps/tauri
File: crates/tauri-bundler/src/bundle/windows/nsis/mod.rs (Rust)

Code before:
    NSIS_TAURI_UTILS_URL,
    NSIS_TAURI_UTILS_SHA1,
    HashAlgorithm::Sha1,
  )?;

  let target_folder = nsis_plugins.join("x86-unicode");
  fs::create_dir_all(&target_folder)?;
  fs::write(target_folder.join("nsis_tauri_utils.dll"), data)?;

  Ok(())
}

fn try_add_numeric_build_number(version_str: &str) -> anyhow::Result<String> {
  let version = semver::Version::parse(version_str).context("invalid app version")?;
  if !version.build.is_empty() {
    let build = version.build.parse::<u64>();
    if build.is_ok() {
      return Ok(format!(
        "{}.{}.{}.{}",
        version.major, version.minor, version.patch, version.build
      ));
    }
  }

  log::warn!(
    "Unable to parse version build metadata. Numeric value expected, received: {}",
    version.build
  );

  Ok(format!(
    "{}.{}.{}.0",
    version.major, version.minor, version.patch,
  ))
}

fn build_nsis_app_installer(
  settings: &Settings,
  _nsis_toolset_path: &Path,
  tauri_tools_path: &Path,
  updater: bool,
) -> crate::Result<Vec<PathBuf>> {
  let arch = match settings.binary_arch() {
    Arch::X86_64 => "x64",
    Arch::X86 => "x86",
    Arch::AArch64 => "arm64",
    target => {
      return Err(crate::Error::ArchError(format!(
        "unsupported architecture: {:?}",
        target
      )))
    }

Review comment (suggestion):
```suggestion
    "Unable to parse version build metadata. Numeric value expected, received: `{}`. This will be replaced with `0` in `VIProductVersion` because Windows requires this field to be numeric.",
```

Code after:
    NSIS_TAURI_UTILS_URL,
    NSIS_TAURI_UTILS_SHA1,
    HashAlgorithm::Sha1,
  )?;

  let target_folder = nsis_plugins.join("x86-unicode");
  fs::create_dir_all(&target_folder)?;
  fs::write(target_folder.join("nsis_tauri_utils.dll"), data)?;

  Ok(())
}

fn try_add_numeric_build_number(version_str: &str) -> anyhow::Result<String> {
  let version = semver::Version::parse(version_str).context("invalid app version")?;
  if !version.build.is_empty() {
    let build = version.build.parse::<u64>();
    if build.is_ok() {
      return Ok(format!(
        "{}.{}.{}.{}",
        version.major, version.minor, version.patch, version.build
      ));
    } else {
      log::warn!(
        "Unable to parse version build metadata. Numeric value expected, received: `{}`. This will be replaced with `0` in `VIProductVersion` because Windows requires this field to be numeric.",
        version.build
      );
    }
  }

  Ok(format!(
    "{}.{}.{}.0",
    version.major, version.minor, version.patch,
  ))
}

fn build_nsis_app_installer(
  settings: &Settings,
  _nsis_toolset_path: &Path,
  tauri_tools_path: &Path,
  updater: bool,
) -> crate::Result<Vec<PathBuf>> {
  let arch = match settings.binary_arch() {
    Arch::X86_64 => "x64",
    Arch::X86 => "x86",
    Arch::AArch64 => "arm64",
    target => {
      return Err(crate::Error::ArchError(format!(
        "unsupported architecture: {:?}",
        target
      )))
    }
Repository: tauri-apps/tauri
File: crates/tauri/src/event/mod.rs (Rust)

Code before:
pub struct EmitArgs {
  /// Raw event name.
  pub event_name: String,
  /// Serialized event name.
  pub event: String,
  /// Serialized payload.
  pub payload: String,
}

impl EmitArgs {
  pub fn new<S: Serialize>(event: &str, payload: S) -> crate::Result<Self> {
    #[cfg(feature = "tracing")]
    let _span = tracing::debug_span!("window::emit::serialize").entered();
    Ok(EmitArgs {
      event_name: event.into(),
      event: serde_json::to_string(event)?,
      payload: serde_json::to_string(&payload)?,
    })
  }

  pub fn new_json(event: &str, payload: String) -> crate::Result<Self> {
    #[cfg(feature = "tracing")]
    let _span = tracing::debug_span!("window::emit::json").entered();
    Ok(EmitArgs {
      event_name: event.into(),
      event: serde_json::to_string(event)?,
      payload,
    })
  }
}

/// An event that was emitted.
#[derive(Debug, Clone)]
pub struct Event {
  id: EventId,
  data: String,
}

impl Event {
  fn new(id: EventId, data: String) -> Self {
    Self { id, data }
  }

  /// The [`EventId`] of the handler that was triggered.
  pub fn id(&self) -> EventId {
    self.id
  }

  /// The event payload.
  pub fn payload(&self) -> &str {
    &self.data

Review comment (refactor):
let's remove this serde call as well, it is unnecessary, also do the same for `EmitArgs::new`.

Don't forget to update `emit_js_script` function later down in this file to add wrapping single quotes around event name. 

Code after:
    let _span = tracing::debug_span!("window::emit::serialize").entered();
    Ok(EmitArgs {
      event: event.into_owned(),
      payload: serde_json::to_string(payload)?,
    })
  }

  pub fn new_str(event: EventName<&str>, payload: String) -> crate::Result<Self> {
    #[cfg(feature = "tracing")]
    let _span = tracing::debug_span!("window::emit::json").entered();
    Ok(EmitArgs {
      event: event.into_owned(),
      payload,
    })
  }
}

/// An event that was emitted.
#[derive(Debug, Clone)]
pub struct Event {
  id: EventId,
  data: String,
}

impl Event {
  fn new(id: EventId, data: String) -> Self {
    Self { id, data }
  }

  /// The [`EventId`] of the handler that was triggered.
  pub fn id(&self) -> EventId {
    self.id
  }

  /// The event payload.
  pub fn payload(&self) -> &str {
    &self.data
  }
}

pub fn listen_js_script(
  listeners_object_name: &str,
  serialized_target: &str,
  event: EventName<&str>,
  event_id: EventId,
  handler: &str,
) -> String {
  format!(
    "(function () {{
      if (window['{listeners_object_name}'] === void 0) {{
        Object.defineProperty(window, '{listeners_object_name}', {{ value: Object.create(null) }});