ronantakizawa/codereview-bench huggingface dataset:
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/candidate.ts (TypeScript)

Code before:
      yield ['@', input.slice(1)]
    }
    return
  }

  // Determine the root and value by testing permutations of the incoming input.
  //
  // In case of a candidate like `bg-red-500`, this looks like:
  //
  // `bg-red-500` -> No match
  // `bg-red`     -> No match
  // `bg`         -> Match
  do {
    let maybeRoot = input.slice(0, idx)

    if (exists(maybeRoot)) {
      let root: Root = [maybeRoot, input.slice(idx + 1)]

      // If the leftover value is an empty string, it means that the value is an
      // invalid named value, e.g.: `bg-`. This makes the candidate invalid and we
      // can skip any further parsing.
      if (root[1] === '') break

      yield root
    }

    idx = input.lastIndexOf('-', idx - 1)
  } while (idx > 0)

  // Try '@' variant after permutations. This allows things like `@max` of `@max-foo-bar`
  // to match before looking for `@`.
  if (input[0] === '@' && exists('@')) {
    yield ['@', input.slice(1)]
  }
}


Review comment (suggestion):
I've been thinking of restructuring this somehow so that there's only one special-case for `@`. Let me know what you think about this (I pushed onto your PR). Tests seem to pass so it should be fine? 🤞 

Code after:
  //
  // `bg-red-500` -> No match
  // `bg-red`     -> No match
  // `bg`         -> Match
  while (idx > 0) {
    let maybeRoot = input.slice(0, idx)

    if (exists(maybeRoot)) {
      let root: Root = [maybeRoot, input.slice(idx + 1)]

      // If the leftover value is an empty string, it means that the value is an
      // invalid named value, e.g.: `bg-`. This makes the candidate invalid and we
      // can skip any further parsing.
      if (root[1] === '') break

      yield root
    }

    idx = input.lastIndexOf('-', idx - 1)
  }

  // Try '@' variant after permutations. This allows things like `@max` of `@max-foo-bar`
  // to match before looking for `@`.
  if (input[0] === '@' && exists('@')) {
    yield ['@', input.slice(1)]
  }
}
Repository: tailwindlabs/tailwindcss
File: packages/tailwindcss/src/compat/apply-config-to-theme.ts (TypeScript)

Code before:

  return theme
}

export function themeableValues(config: ResolvedConfig['theme']): [string[], unknown][] {
  let toAdd: [string[], unknown][] = []

  walk(config as any, [], (value, path) => {
    if (isValidThemePrimitive(value)) {
      toAdd.push([path, value])

      return WalkAction.Skip
    }

    if (isValidThemeTuple(value)) {
      toAdd.push([path, value[0]])

      for (let key of Reflect.ownKeys(value[1]) as string[]) {
        toAdd.push([[...path, `-${key}`], value[1][key]])
      }

      return WalkAction.Skip
    }

    if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
      if (path[0] === 'fontSize') {
        toAdd.push([path, value[0]])
        toAdd.push([[...path, '-line-height'], value[1]])
      } else {
        toAdd.push([path, value.join(', ')])
      }

      return WalkAction.Skip
    }
  })

  return toAdd
}

const IS_VALID_KEY = /^[a-zA-Z0-9-_%/\.]+$/

export function keyPathToCssProperty(path: string[]) {
  // The legacy container component config should not be included in the Theme
  if (path[0] === 'container') return null

  path = structuredClone(path)

  if (path[0] === 'animation') path[0] = 'animate'
  if (path[0] === 'aspectRatio') path[0] = 'aspect'
  if (path[0] === 'borderRadius') path[0] = 'radius'
  if (path[0] === 'boxShadow') path[0] = 'shadow'

Review comment (suggestion):
```suggestion
      if (path[0] === 'fontSize' && value.length === 2) {
```

I'd probably want to make sure this _only_ works for tuples. 

Code after:

  return theme
}

export function themeableValues(config: ResolvedConfig['theme']): [string[], unknown][] {
  let toAdd: [string[], unknown][] = []

  walk(config as any, [], (value, path) => {
    if (isValidThemePrimitive(value)) {
      toAdd.push([path, value])

      return WalkAction.Skip
    }

    if (isValidThemeTuple(value)) {
      toAdd.push([path, value[0]])

      for (let key of Reflect.ownKeys(value[1]) as string[]) {
        toAdd.push([[...path, `-${key}`], value[1][key]])
      }

      return WalkAction.Skip
    }

    if (Array.isArray(value) && value.every((v) => typeof v === 'string')) {
      if (path[0] === 'fontSize') {
        toAdd.push([path, value[0]])

        if (value.length >= 2) {
          toAdd.push([[...path, '-line-height'], value[1]])
        }
      } else {
        toAdd.push([path, value.join(', ')])
      }

      return WalkAction.Skip
    }
  })

  return toAdd
}

const IS_VALID_KEY = /^[a-zA-Z0-9-_%/\.]+$/

export function keyPathToCssProperty(path: string[]) {
  // The legacy container component config should not be included in the Theme
  if (path[0] === 'container') return null

  path = structuredClone(path)

  if (path[0] === 'animation') path[0] = 'animate'
Repository: tailwindlabs/tailwindcss
File: integrations/oxide/postinstall.test.ts (TypeScript)

Code before:
    let packageJson = JSON.parse(await fs.read('node_modules/@tailwindcss/oxide/package.json'))
    packageJson.version = version
    await fs.write(
      'node_modules/@tailwindcss/oxide/package.json',
      JSON.stringify(packageJson, null, 2),
    )

    let opts = {
      // Ensure that we don't include any node paths from the test runner
      env: { NODE_PATH: '' },
    }

    expect(await exec('node test.js', opts)).toMatch(/FAILURE/)

    // Now run the post-install script
    await exec('node node_modules/@tailwindcss/oxide/scripts/install.js', opts)

    expect(await exec('node test.js', opts)).toMatch(/SUCCESS/)
  },
)

async function removePlatformSpecificExtensions(directory: string) {
  const entries = await fs.readdir(directory, { withFileTypes: true })

  for (const entry of entries) {
    const fullPath = path.join(directory, entry.name)

    if (entry.name.startsWith('oxide-')) {
      if (entry.isSymbolicLink()) {
        await fs.unlink(fullPath)
      } else if (entry.isFile()) {
        await fs.unlink(fullPath)
      } else if (entry.isDirectory()) {
        await fs.rm(fullPath, { recursive: true, force: true })
      }
    } else if (entry.isDirectory()) {
      await removePlatformSpecificExtensions(fullPath)
    }
  }
}


Review comment (suggestion):
```suggestion
  let entries = await fs.readdir(directory, { withFileTypes: true })

  for (let entry of entries) {
    let fullPath = path.join(directory, entry.name)
```

Code after:
    let packageJson = JSON.parse(await fs.read('node_modules/@tailwindcss/oxide/package.json'))
    packageJson.version = version
    await fs.write(
      'node_modules/@tailwindcss/oxide/package.json',
      JSON.stringify(packageJson, null, 2),
    )

    let opts = {
      // Ensure that we don't include any node paths from the test runner
      env: { NODE_PATH: '' },
    }

    expect(await exec('node test.js', opts)).toMatch(/FAILURE/)

    // Now run the post-install script
    await exec('node node_modules/@tailwindcss/oxide/scripts/install.js', opts)

    expect(await exec('node test.js', opts)).toMatch(/SUCCESS/)
  },
)

async function removePlatformSpecificExtensions(directory: string) {
  let entries = await fs.readdir(directory, { withFileTypes: true })

  for (let entry of entries) {
    let fullPath = path.join(directory, entry.name)

    if (entry.name.startsWith('oxide-')) {
      if (entry.isSymbolicLink()) {
        await fs.unlink(fullPath)
      } else if (entry.isFile()) {
        await fs.unlink(fullPath)
      } else if (entry.isDirectory()) {
        await fs.rm(fullPath, { recursive: true, force: true })
      }
    } else if (entry.isDirectory()) {
      await removePlatformSpecificExtensions(fullPath)
    }
  }
}
Repository: tailwindlabs/tailwindcss
File: crates/node/scripts/install.js (JavaScript)

Code before:

            await extractTarball(
              response,
              path.join(__dirname, '..', 'node_modules', ...packageName.split('/')),
            )
            console.log(`Successfully downloaded and installed ${packageName}`)
          } catch (error) {
            console.error('Error during extraction:', error)
            resolve()
          } finally {
            resolve()
          }
        }
      })
      .on('error', (err) => {
        console.error('Download error:', err)
        resolve()
      })
  })
}

async function main() {
  // Don't run this script in the package source
  if (fs.existsSync(path.join(__dirname, '..', 'build.rs'))) {
    return
  }

  const packageName = getPlatformPackageName()
  if (!packageName) return
  if (isPackageAvailable(packageName)) return

  await downloadAndExtractBinary(packageName)
}

main()


Review comment (bug):
I think we should wrap this in a try/catch. Some people run stuff from Docker in the `/` path, so `../build.rs` will very likely crash.

Also let's hope nobody has a `build.rs` file in the parent directory 😅 

```suggestion
  // Don't run this script in the package source
  try {
    if (fs.existsSync(path.join(__dirname, '..', 'build.rs'))) {
      return
    }
  } catch {
    return
  }
```

Code after:
            await extractTarball(
              response,
              path.join(__dirname, '..', 'node_modules', ...packageName.split('/')),
            )
            console.log(`Successfully downloaded and installed ${packageName}`)
          } catch (error) {
            console.error('Error during extraction:', error)
            resolve()
          } finally {
            resolve()
          }
        }
      })
      .on('error', (err) => {
        console.error('Download error:', err)
        resolve()
      })
  })
}

async function main() {
  // Don't run this script in the package source
  try {
    if (fs.existsSync(path.join(__dirname, '..', 'build.rs'))) {
      return
    }

    let packageName = getPlatformPackageName()
    if (!packageName) return
    if (isPackageAvailable(packageName)) return

    await downloadAndExtractBinary(packageName)
  } catch (error) {
    console.error(error)
    return
  }
}

main()
Repository: tailwindlabs/tailwindcss
File: crates/node/scripts/install.js (JavaScript)

Code before:
              response,
              path.join(__dirname, '..', 'node_modules', ...packageName.split('/')),
            )
            console.log(`Successfully downloaded and installed ${packageName}`)
          } catch (error) {
            console.error('Error during extraction:', error)
            resolve()
          } finally {
            resolve()
          }
        }
      })
      .on('error', (err) => {
        console.error('Download error:', err)
        resolve()
      })
  })
}

async function main() {
  // Don't run this script in the package source
  if (fs.existsSync(path.join(__dirname, '..', 'build.rs'))) {
    return
  }

  const packageName = getPlatformPackageName()
  if (!packageName) return
  if (isPackageAvailable(packageName)) return

  await downloadAndExtractBinary(packageName)
}

main()


Review comment (suggestion):
```suggestion
  let packageName = getPlatformPackageName()
```

Code after:
              path.join(__dirname, '..', 'node_modules', ...packageName.split('/')),
            )
            console.log(`Successfully downloaded and installed ${packageName}`)
          } catch (error) {
            console.error('Error during extraction:', error)
            resolve()
          } finally {
            resolve()
          }
        }
      })
      .on('error', (err) => {
        console.error('Download error:', err)
        resolve()
      })
  })
}

async function main() {
  // Don't run this script in the package source
  try {
    if (fs.existsSync(path.join(__dirname, '..', 'build.rs'))) {
      return
    }

    let packageName = getPlatformPackageName()
    if (!packageName) return
    if (isPackageAvailable(packageName)) return

    await downloadAndExtractBinary(packageName)
  } catch (error) {
    console.error(error)
    return
  }
}

main()
Repository: tailwindlabs/tailwindcss
File: crates/node/scripts/install.js (JavaScript)

Code before:
#!/usr/bin/env node

/**
 * @tailwindcss/oxide postinstall script
 *
 * This script ensures that the correct binary for the current platform and
 * architecture is downloaded and available.
 */

const fs = require('fs')
const path = require('path')
const https = require('https')
const { extract } = require('tar')
const packageJson = require('../package.json')
const detectLibc = require('detect-libc')

const version = packageJson.version

function getPlatformPackageName() {
  const platform = process.platform
  const arch = process.arch

  let libc = ''
  if (platform === 'linux') {
    libc = detectLibc.isNonGlibcLinuxSync() ? 'musl' : 'gnu'
  }

  // Map to our package naming conventions
  switch (platform) {
    case 'darwin':
      return arch === 'arm64' ? '@tailwindcss/oxide-darwin-arm64' : '@tailwindcss/oxide-darwin-x64'
    case 'win32':
      if (arch === 'arm64') return '@tailwindcss/oxide-win32-arm64-msvc'
      if (arch === 'ia32') return '@tailwindcss/oxide-win32-ia32-msvc'
      return '@tailwindcss/oxide-win32-x64-msvc'
    case 'linux':
      if (arch === 'x64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-x64-musl'
          : '@tailwindcss/oxide-linux-x64-gnu'
      } else if (arch === 'arm64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-arm64-musl'
          : '@tailwindcss/oxide-linux-arm64-gnu'
      } else if (arch === 'arm') {
        return '@tailwindcss/oxide-linux-arm-gnueabihf'

Review comment (suggestion):
```suggestion
  let platform = process.platform
  let arch = process.arch
```

Code after:
#!/usr/bin/env node

/**
 * @tailwindcss/oxide postinstall script
 *
 * This script ensures that the correct binary for the current platform and
 * architecture is downloaded and available.
 */

const fs = require('fs')
const path = require('path')
const https = require('https')
const { extract } = require('tar')
const packageJson = require('../package.json')
const detectLibc = require('detect-libc')

const version = packageJson.version

function getPlatformPackageName() {
  let platform = process.platform
  let arch = process.arch

  let libc = ''
  if (platform === 'linux') {
    libc = detectLibc.isNonGlibcLinuxSync() ? 'musl' : 'gnu'
  }

  // Map to our package naming conventions
  switch (platform) {
    case 'darwin':
      return arch === 'arm64' ? '@tailwindcss/oxide-darwin-arm64' : '@tailwindcss/oxide-darwin-x64'
    case 'win32':
      if (arch === 'arm64') return '@tailwindcss/oxide-win32-arm64-msvc'
      if (arch === 'ia32') return '@tailwindcss/oxide-win32-ia32-msvc'
      return '@tailwindcss/oxide-win32-x64-msvc'
    case 'linux':
      if (arch === 'x64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-x64-musl'
          : '@tailwindcss/oxide-linux-x64-gnu'
      } else if (arch === 'arm64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-arm64-musl'
          : '@tailwindcss/oxide-linux-arm64-gnu'
      } else if (arch === 'arm') {
        return '@tailwindcss/oxide-linux-arm-gnueabihf'
Repository: tailwindlabs/tailwindcss
File: crates/node/scripts/install.js (JavaScript)

Code before:
#!/usr/bin/env node

/**
 * @tailwindcss/oxide postinstall script
 *
 * This script ensures that the correct binary for the current platform and
 * architecture is downloaded and available.
 */

const fs = require('fs')
const path = require('path')
const https = require('https')
const { extract } = require('tar')
const packageJson = require('../package.json')
const detectLibc = require('detect-libc')

const version = packageJson.version

function getPlatformPackageName() {
  const platform = process.platform
  const arch = process.arch

  let libc = ''
  if (platform === 'linux') {
    libc = detectLibc.isNonGlibcLinuxSync() ? 'musl' : 'gnu'
  }

  // Map to our package naming conventions
  switch (platform) {
    case 'darwin':
      return arch === 'arm64' ? '@tailwindcss/oxide-darwin-arm64' : '@tailwindcss/oxide-darwin-x64'
    case 'win32':
      if (arch === 'arm64') return '@tailwindcss/oxide-win32-arm64-msvc'
      if (arch === 'ia32') return '@tailwindcss/oxide-win32-ia32-msvc'
      return '@tailwindcss/oxide-win32-x64-msvc'
    case 'linux':
      if (arch === 'x64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-x64-musl'
          : '@tailwindcss/oxide-linux-x64-gnu'
      } else if (arch === 'arm64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-arm64-musl'
          : '@tailwindcss/oxide-linux-arm64-gnu'

Review comment (suggestion):
I wonder if we can somehow re-use this logic from what NAPI generated for us. Since that is generated and using require already it might not be as easy.

Just have to make sure that _if_ we make changes, that we keep this in sync

Code after:
#!/usr/bin/env node

/**
 * @tailwindcss/oxide postinstall script
 *
 * This script ensures that the correct binary for the current platform and
 * architecture is downloaded and available.
 */

const fs = require('fs')
const path = require('path')
const https = require('https')
const { extract } = require('tar')
const packageJson = require('../package.json')
const detectLibc = require('detect-libc')

const version = packageJson.version

function getPlatformPackageName() {
  let platform = process.platform
  let arch = process.arch

  let libc = ''
  if (platform === 'linux') {
    libc = detectLibc.isNonGlibcLinuxSync() ? 'musl' : 'gnu'
  }

  // Map to our package naming conventions
  switch (platform) {
    case 'darwin':
      return arch === 'arm64' ? '@tailwindcss/oxide-darwin-arm64' : '@tailwindcss/oxide-darwin-x64'
    case 'win32':
      if (arch === 'arm64') return '@tailwindcss/oxide-win32-arm64-msvc'
      if (arch === 'ia32') return '@tailwindcss/oxide-win32-ia32-msvc'
      return '@tailwindcss/oxide-win32-x64-msvc'
    case 'linux':
      if (arch === 'x64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-x64-musl'
          : '@tailwindcss/oxide-linux-x64-gnu'
      } else if (arch === 'arm64') {
        return libc === 'musl'
          ? '@tailwindcss/oxide-linux-arm64-musl'
          : '@tailwindcss/oxide-linux-arm64-gnu'
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-upgrade/src/codemods/template/migrate-camelcase-in-named-value.ts (TypeScript)

Code before:
import type { Config } from '../../../../tailwindcss/src/compat/plugin-api'
import type { DesignSystem } from '../../../../tailwindcss/src/design-system'
import * as version from '../../utils/version'

// Converts named values to use kebab-case. This is necessary because the
// upgrade tool also renames the theme values to kebab-case, so `text-superRed`
// will have it's theme value renamed to `--color-super-red` and thus the
// utility will be renamed to `text-super-red`.
export function migrateCamelcaseInNamedValue(
  designSystem: DesignSystem,
  _userConfig: Config | null,
  rawCandidate: string,
): string {
  if (!version.isMajor(3)) return rawCandidate

  for (let candidate of designSystem.parseCandidate(rawCandidate)) {
    if (candidate.kind !== 'functional') continue
    let clone = structuredClone(candidate)
    let didChange = false

    if (
      candidate.value &&
      clone.value &&
      candidate.value.kind === 'named' &&
      clone.value.kind === 'named' &&
      candidate.value.value.match(/[A-Z]/)
    ) {
      clone.value.value = camelToKebab(candidate.value.value)
      didChange = true
    }

    if (

Review comment (suggestion):
```suggestion
// will have its theme value renamed to `--color-super-red` and thus the
```

Code after:
import type { Config } from '../../../../tailwindcss/src/compat/plugin-api'
import type { DesignSystem } from '../../../../tailwindcss/src/design-system'
import * as version from '../../utils/version'

// Converts named values to use kebab-case. This is necessary because the
// upgrade tool also renames the theme values to kebab-case, so `text-superRed`
// will have its theme value renamed to `--color-super-red` and thus the utility
// will be renamed to `text-super-red`.
export function migrateCamelcaseInNamedValue(
  designSystem: DesignSystem,
  _userConfig: Config | null,
  rawCandidate: string,
): string {
  if (!version.isMajor(3)) return rawCandidate

  for (let candidate of designSystem.parseCandidate(rawCandidate)) {
    if (candidate.kind !== 'functional') continue
    let clone = structuredClone(candidate)
    let didChange = false

    if (
      candidate.value &&
      clone.value &&
      candidate.value.kind === 'named' &&
      clone.value.kind === 'named' &&
      candidate.value.value.match(/[A-Z]/)
    ) {
      clone.value.value = camelToKebab(candidate.value.value)
      didChange = true
    }

    if (
Repository: tailwindlabs/tailwindcss
File: packages/@tailwindcss-upgrade/src/codemods/template/is-safe-migration.ts (TypeScript)

Code before:
  // Heuristic: Disallow Next.js Image `placeholder` prop
  if (NEXT_PLACEHOLDER_PROP.test(currentLineBeforeCandidate)) {
    return false
  }

  return true
}

// Assumptions:
// - All `<style` tags appear before the next `</style>` tag
// - All `<style` tags are closed with `</style>`
// - No nested `<style>` tags
const styleBlockRanges = new DefaultMap((source: string) => {
  let ranges: number[] = []
  let offset = 0

  while (true) {
    let startTag = source.indexOf('<style', offset)
    if (startTag === -1) return ranges

    // Ensure the style looks like:
    // - `<style>`   (closed)
    // - `<style …>` (with attributes)
    if (!source[startTag + 6].match(/[>\s]/)) return ranges

    offset = startTag + 1

    let endTag = source.indexOf('</style>', offset)
    if (endTag === -1) return ranges
    offset = endTag + 1

    ranges.push(startTag, endTag)
  }
})


Review comment (suggestion):
This will stop scanning as soon as it sees a tag that starts with `<style` but isn't `<style>`. e.g. `<styleless>`. How about this?

```suggestion
    offset = startTag + 1

    // Ensure the style looks like:
    // - `<style>`   (closed)
    // - `<style …>` (with attributes)
    if (!source[startTag + 6].match(/[>\s]/)) continue
```


Code after:
  // Heuristic: Disallow Next.js Image `placeholder` prop
  if (NEXT_PLACEHOLDER_PROP.test(currentLineBeforeCandidate)) {
    return false
  }

  return true
}

// Assumptions:
// - All `<style` tags appear before the next `</style>` tag
// - All `<style` tags are closed with `</style>`
// - No nested `<style>` tags
const styleBlockRanges = new DefaultMap((source: string) => {
  let ranges: number[] = []
  let offset = 0

  while (true) {
    let startTag = source.indexOf('<style', offset)
    if (startTag === -1) return ranges

    offset = startTag + 1

    // Ensure the style looks like:
    // - `<style>`   (closed)
    // - `<style …>` (with attributes)
    if (!source[startTag + 6].match(/[>\s]/)) continue

    let endTag = source.indexOf('</style>', offset)
    if (endTag === -1) return ranges
    offset = endTag + 1

    ranges.push(startTag, endTag)
  }
})