All files / packages/icons/.claude/skills/icons-release/scripts prepare-release.js

0% Statements 0/118
0% Branches 0/60
0% Functions 0/7
0% Lines 0/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
#!/usr/bin/env node
'use strict'
 
/**
 * prepare-release
 *
 * Builds a self-contained, per-release working set under .workflow/<release>/
 * from the read-only gdrive download (master CSV + exported SVG folders).
 *
 * It does NOT consume the download directly downstream: it filters the CSV to
 * the target build's eligible icons, copies only those SVGs into the working
 * set, and reports every dropped row with a reason.
 *
 * Usage:
 *   node .claude/skills/icons-release/scripts/prepare-release.js \
 *     --release R264 --csv <master.csv> --assets <gdrive-assets-folder>
 *
 * Output: a single JSON object on stdout (see succeed() payload below).
 */
 
const fs = require('fs')
const path = require('path')
 
const { log, succeed, failWith, run } = require('./lib/output')
const { parseArgs } = require('./lib/args')
const { parseCsv, toCsv } = require('./lib/csv')
const { resolveColumns } = require('./lib/columns')
const { classifyRow } = require('./lib/classify')
const { parseSynonyms } = require('./lib/synonyms')
const { indexAssetFolders, findSvgFile, resolveAssetsDir } = require('./lib/assets')
const { normalizeDimensions } = require('./lib/dimensions')
const { findRepoIconPath } = require('./lib/repo')
 
const STEP = 'prepare-release'
const WORKFLOW_ROOT = '.workflow'
 
function parseRelease(input) {
  const match = String(input || '').match(/(\d+)/)
  if (!match) {
    failWith(STEP, 'invalidRelease', `Could not read a build number from --release "${input}"`)
  }
  const targetBuild = Number(match[1])
  return { release: `R${targetBuild}`, targetBuild }
}
 
function main() {
  const args = parseArgs(process.argv.slice(2))
 
  if (!args.release) failWith(STEP, 'missingArg', '--release is required (e.g. --release R264)')
  if (!args.csv) failWith(STEP, 'missingArg', '--csv <master csv path> is required')
  if (!args.assets) failWith(STEP, 'missingArg', '--assets <gdrive assets folder> is required')
 
  const { release, targetBuild } = parseRelease(args.release)
  const repoRoot = args['repo-root'] || '.'
 
  if (!fs.existsSync(args.csv)) {
    failWith(STEP, 'csvNotFound', `CSV not found: ${args.csv}`)
  }
  if (!fs.existsSync(args.assets)) {
    failWith(STEP, 'assetsNotFound', `Assets folder not found: ${args.assets}`)
  }
 
  // --- parse + resolve columns -------------------------------------------
  const rawRows = parseCsv(fs.readFileSync(args.csv, 'utf8'))
  if (rawRows.length < 2) {
    failWith(STEP, 'emptyCsv', 'CSV has no data rows')
  }
  const header = rawRows[0]
  const dataRows = rawRows.slice(1)
 
  let columns
  try {
    columns = resolveColumns(header)
  } catch (err) {
    failWith(STEP, 'missingColumns', err.message)
  }
 
  const cell = (row, field) =>
    columns[field] === undefined ? '' : (row[columns[field]] || '').trim()
 
  // --- prepare working dirs ----------------------------------------------
  const location = path.join(WORKFLOW_ROOT, release)
  const assetsOut = path.join(location, 'assets')
  if (fs.existsSync(location)) {
    fs.rmSync(location, { recursive: true, force: true })
  }
  fs.mkdirSync(assetsOut, { recursive: true })
 
  // --- materialize source assets (unzip if needed) + locate type folders --
  let assetsDir
  try {
    assetsDir = resolveAssetsDir(args.assets, path.join(location, 'download'))
  } catch (err) {
    failWith(STEP, err.code === 'UNSUPPORTED_ASSETS' ? 'unsupportedAssets' : 'unzipFailed', err.message)
  }
  const assetFolders = indexAssetFolders(assetsDir)
  log(`Asset folders detected: ${JSON.stringify(assetFolders)}`)
  if (Object.keys(assetFolders).length === 0) {
    failWith(STEP, 'noAssetFolders', `No Exported <type> Icons folders found under ${assetsDir}`)
  }
 
  // --- classify + materialize --------------------------------------------
  const eligible = []
  const ineligible = []
  const duplicates = []
  const normalized = []
  let matchedBuild = 0
 
  // Copy an exported SVG into the working set under <type> and apply the gated
  // width/height normalization (recorded in `normalized`). Safe unit fixes are
  // applied; geometry-scale mismatches are left to fail validation loudly.
  // Returns { ok:true } or { ok:false, reason, detail }.
  const materialize = (name, type) => {
    const sourceFolder = assetFolders[type]
    const sourceFile = findSvgFile(sourceFolder, name)
    if (!sourceFile) {
      return {
        ok: false,
        reason: 'assetFileMissing',
        detail: sourceFolder
          ? `No "${name}.svg" (case-insensitive) in ${sourceFolder}`
          : `No source folder for type "${type}"`
      }
    }
    const destDir = path.join(assetsOut, type)
    fs.mkdirSync(destDir, { recursive: true })
    const destFile = path.join(destDir, `${name}.svg`)
    fs.copyFileSync(path.join(sourceFolder, sourceFile), destFile)
    const norm = normalizeDimensions(fs.readFileSync(destFile, 'utf8'), type)
    if (norm.changed) {
      fs.writeFileSync(destFile, norm.content)
      normalized.push({
        icon_name: name,
        icon_type: type,
        from: norm.from,
        to: norm.to,
        note: 'width/height attributes normalized to canonical px (viewBox unchanged)'
      })
    }
    return { ok: true }
  }
 
  const pushEligible = (name, type, record, extra) =>
    eligible.push({
      icon_name: name,
      icon_type: type,
      color: record.color,
      synonyms: record.synonyms,
      has_ltr_rtl: 'no',
      converted: false,
      source: '',
      ...extra
    })
 
  // Skip any icon whose name already exists in the target repo set — report it
  // as a duplicate rather than overwriting a shipped icon.
  const pushDuplicate = (name, type, extra) => {
    duplicates.push({
      icon_name: name,
      icon_type: type,
      reason: 'duplicate',
      detail: `"${name}" already exists in ${type} — skipped as duplicate.`,
      ...extra
    })
  }
 
  for (const row of dataRows) {
    const name = cell(row, 'name')
    if (!name) continue
 
    const rowBuild = Number((cell(row, 'targetBuild').match(/\d+/) || [])[0])
    if (rowBuild !== targetBuild) continue
    matchedBuild++
 
    const record = {
      icon_name: name,
      designStatus: cell(row, 'designStatus'),
      iconType: cell(row, 'iconType'),
      assetSubmitted: cell(row, 'assetSubmitted'),
      color: cell(row, 'color'),
      synonyms: parseSynonyms(cell(row, 'synonyms'))
    }
 
    const result = classifyRow(record)
 
    if (result.bucket === 'ineligible') {
      ineligible.push({ icon_name: name, reason: result.reason, detail: result.detail })
      continue
    }
 
    // --- convert existing == COPY source-set -> target-set ----------------
    // Additive: the asset is added to the target set; the source copy is left
    // in place for backward compatibility (no deletion, no alias needed).
    if (result.bucket === 'convert') {
      const targetType = result.type
      const sourceType = result.source || null
 
      if (findRepoIconPath(repoRoot, targetType, name)) {
        pushDuplicate(name, targetType, { source_type: sourceType })
        continue
      }
 
      const m = materialize(name, targetType)
      if (!m.ok) {
        ineligible.push({ icon_name: name, reason: m.reason, detail: m.detail })
        continue
      }
      pushEligible(name, targetType, record, {
        converted: true,
        source: sourceType || ''
      })
      continue
    }
 
    // --- normal eligible --------------------------------------------------
    if (findRepoIconPath(repoRoot, result.type, name)) {
      pushDuplicate(name, result.type)
      continue
    }
    const m = materialize(name, result.type)
    if (!m.ok) {
      ineligible.push({ icon_name: name, reason: m.reason, detail: m.detail })
      continue
    }
    pushEligible(name, result.type, record)
  }
 
  // --- write target-icons csv (eligible only) ----------------------------
  const targetIconsCsv = path.join(location, `${release}-icons.csv`)
  const csvHeaders = ['icon_name', 'icon_type', 'color', 'synonyms', 'has_ltr_rtl', 'converted', 'source']
  const csvRecords = eligible.map(e => ({
    icon_name: e.icon_name,
    icon_type: e.icon_type,
    color: e.color,
    synonyms: e.synonyms.join('|'),
    has_ltr_rtl: e.has_ltr_rtl,
    converted: e.converted ? 'yes' : 'no',
    source: e.source || ''
  }))
  fs.writeFileSync(targetIconsCsv, toCsv(csvHeaders, csvRecords))
 
  const data = {
    release,
    targetBuild,
    location,
    targetIconsCsv,
    totalRowsInCsv: dataRows.length,
    matchedBuild,
    eligibleCount: eligible.length,
    eligible,
    ineligible,
    duplicates,
    normalized,
    reconciliation: {
      matchedBuild,
      eligible: eligible.length,
      ineligible: ineligible.length,
      duplicates: duplicates.length,
      balanced:
        matchedBuild === eligible.length + ineligible.length + duplicates.length
    }
  }
 
  // persist the output so steps can be re-read without re-running
  fs.writeFileSync(
    path.join(location, 'prepare-release.json'),
    JSON.stringify({ success: true, step: STEP, data }, null, 2) + '\n'
  )
 
  succeed(STEP, data)
}
 
run(STEP, main)