utils.js 1.91 KB
Newer Older
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
const { existsSync, readFileSync, readdirSync, statSync, lstatSync } = require('fs');
const { join } = require('path');

const chunk = (array, chunkSize) => {
  const size = Math.ceil(array.length / chunkSize);
  const result = [];
  while (array.length) {
    result.push(array.splice(0, size));
  }
  return result;
};

const readDir = (dir, filesList = []) => {
  const files = readdirSync(dir);
  for (let file of files) {
    const filePath = join(dir, file);
    if (lstatSync(filePath).isSymbolicLink()) {
      continue;
    }
    if (existsSync(filePath)) {
      if (statSync(filePath).isDirectory()) {
        filesList = readDir(filePath, filesList);
      }
      else {
        if (file.endsWith('.java') || file.endsWith('.xml') || file.endsWith('.kt')) {
          filesList.push(filePath);
        }
      }
    }
  }
  return filesList;
};

const loadCSVFile = () => {
  const csvFilePath = join(__dirname, '..', 'mapping', 'androidx-class-mapping.csv');
  const lines = readFileSync(csvFilePath, { encoding: 'utf8' }).split(/\r?\n/);

  // Remove redundant "Support Library class,Android X class" from array
  lines.shift();

  // last element will always be an empty line so removing it from the array
  if (lines[lines.length - 1] === "") {
    lines.pop();
  }

  // Some mappings are substrings of other mappings, transform longest mappings first
  lines.sort(function(a, b){
    return b.length - a.length;
  });

  return lines;
};

const getClassesMapping = () => {
  const csv = loadCSVFile();
  const result = [];
  for (let line of csv) {
    const oldValue = line.split(',')[0];
    const newValue = line.split(',')[1];
    result.push([oldValue, newValue]);
  }

  // renderscript must be added to the canonical androidx-class-mapping.csv - it is not upstream
  result.push(['android.support.v8.renderscript', 'android.renderscript']);

  return result;
};

module.exports = {
  getClassesMapping,
  readDir,
  chunk
};