code.gitea.io/gitea@v1.21.7/build/generate-svg.js (about)

     1  #!/usr/bin/env node
     2  import fastGlob from 'fast-glob';
     3  import {optimize} from 'svgo';
     4  import {parse} from 'node:path';
     5  import {readFile, writeFile, mkdir} from 'node:fs/promises';
     6  import {fileURLToPath} from 'node:url';
     7  
     8  const glob = (pattern) => fastGlob.sync(pattern, {
     9    cwd: fileURLToPath(new URL('..', import.meta.url)),
    10    absolute: true,
    11  });
    12  
    13  function exit(err) {
    14    if (err) console.error(err);
    15    process.exit(err ? 1 : 0);
    16  }
    17  
    18  async function processFile(file, {prefix, fullName} = {}) {
    19    let name;
    20    if (fullName) {
    21      name = fullName;
    22    } else {
    23      name = parse(file).name;
    24      if (prefix) name = `${prefix}-${name}`;
    25      if (prefix === 'octicon') name = name.replace(/-[0-9]+$/, ''); // chop of '-16' on octicons
    26    }
    27  
    28    // Set the `xmlns` attribute so that the files are displayable in standalone documents
    29    // The svg backend module will strip the attribute during startup for inline display
    30    const {data} = optimize(await readFile(file, 'utf8'), {
    31      plugins: [
    32        {name: 'preset-default'},
    33        {name: 'removeDimensions'},
    34        {name: 'prefixIds', params: {prefix: () => name}},
    35        {name: 'addClassesToSVGElement', params: {classNames: ['svg', name]}},
    36        {
    37          name: 'addAttributesToSVGElement', params: {
    38            attributes: [
    39              {'xmlns': 'http://www.w3.org/2000/svg'},
    40              {'width': '16'}, {'height': '16'}, {'aria-hidden': 'true'},
    41            ]
    42          }
    43        },
    44      ],
    45    });
    46  
    47    await writeFile(fileURLToPath(new URL(`../public/assets/img/svg/${name}.svg`, import.meta.url)), data);
    48  }
    49  
    50  function processFiles(pattern, opts) {
    51    return glob(pattern).map((file) => processFile(file, opts));
    52  }
    53  
    54  async function main() {
    55    try {
    56      await mkdir(fileURLToPath(new URL('../public/assets/img/svg', import.meta.url)), {recursive: true});
    57    } catch {}
    58  
    59    await Promise.all([
    60      ...processFiles('node_modules/@primer/octicons/build/svg/*-16.svg', {prefix: 'octicon'}),
    61      ...processFiles('web_src/svg/*.svg'),
    62      ...processFiles('public/assets/img/gitea.svg', {fullName: 'gitea-gitea'}),
    63    ]);
    64  }
    65  
    66  main().then(exit).catch(exit);