<commit_before>import * as path from 'path';
import * as fs from 'fs';
import * as FormData from 'form-data';
import fetch from 'node-fetch';

import {
  ImageResource,
  SourceImage,
  ImageUploadResponse,
  ResourcesConfig,
  KnownPlatform
} from '../definitions';
import {
  fsReadDir,
  fsMkdirp,
  fsReadJsonFile,
  ERROR_FILE_NOT_FOUND,
  ERROR_FILE_INVALID_JSON,
  getFileChecksum,
  writeStreamToFile,
  copyDirectory
} from '@ionic/cli-utils';

import {
  writeConfigXml,
  parseConfigXmlToJson,
  addPlatformImagesToConfigJson,
  addSplashScreenPreferencesToConfigJson
} from './utils/configXmlUtils';

const SUPPORTED_SOURCE_EXTENSIONS = ['.psd', '.ai', '.png'];
const UPLOAD_URL = 'http://res.ionic.io/api/v1/upload';
const TRANSFORM_URL = 'http://res.ionic.io/api/v1/transform';
const DEFAULT_RESOURCES_DIR = path.resolve(__dirname, '..', '..', 'default-resources');

/**
 * Take the JSON structure for resources.json and turn it into a flat array
 * that contains only images and turns all struture info into attributes of the image
 * items.
 */
export function flattenResourceJsonStructure (jsonStructure: any): ImageResource[] {
  return flatten(Object.keys(jsonStructure).map(platform => (
    Object.keys(jsonStructure[platform]).map(resType => (
      jsonStructure[platform][resType]['images'].map((imgInfo: any) => (
        {
          platform,
          resType,
          name: imgInfo.name,
          width: imgInfo.width,
          height: imgInfo.height,
          density: imgInfo.density,
          nodeName: jsonStructure[platform][resType]['nodeName'],
          nodeAttributes: jsonStructure[platform][resType]['nodeAttributes']
        }
      ))
    )))
  ));
}

/**
 * Create the destination directories for the provided image resources.
 */
export async function createImgDestinationDirectories (imgResources: ImageResource[]): Promise<void[]> {
  const buildDirPromises: Promise<void>[] = imgResources
    .map(img => path.dirname(img.dest))
    .filter((dir, index, dirNames) => dirNames.indexOf(dir) === index)
    .map(dir => fsMkdirp(dir));

  return Promise.all(buildDirPromises);
}

/**
 * Read the resources config and return the Json.
 */
export async function getResourceConfigJson(): Promise<ResourcesConfig> {
  let resourceJsonStructure;
  const filePath = path.join(__dirname, '..', '..', 'resources.json');
  try {
    resourceJsonStructure = await fsReadJsonFile(filePath);
  } catch (e) {
    if (e === ERROR_FILE_NOT_FOUND) {
      throw new Error(`${filePath} not found`);
    } else if (e === ERROR_FILE_INVALID_JSON) {
      throw new Error(`${filePath} is not valid JSON.`);
    }
    throw e;
  }
  return <ResourcesConfig>resourceJsonStructure;
}

/**
 * Find all source images within the resources directory
 */
export async function getSourceImages (buildPlatforms: string[], resourceTypes: string[], resourceDir: string): Promise<SourceImage[]> {
  const srcDirList = buildPlatforms
    .map((platform: string) => (
      {
        platform,
        path: path.join(resourceDir, platform)
      }
    ))
    .concat({
      platform: 'global',<commit_msg>chore(): changed resource config file path to a const.<commit_after>import * as path from 'path';
import * as fs from 'fs';
import * as FormData from 'form-data';
import fetch from 'node-fetch';

import {
  ImageResource,
  SourceImage,
  ImageUploadResponse,
  ResourcesConfig,
  KnownPlatform
} from '../definitions';
import {
  fsReadDir,
  fsMkdirp,
  fsReadJsonFile,
  ERROR_FILE_NOT_FOUND,
  ERROR_FILE_INVALID_JSON,
  getFileChecksum,
  writeStreamToFile,
  copyDirectory
} from '@ionic/cli-utils';

import {
  writeConfigXml,
  parseConfigXmlToJson,
  addPlatformImagesToConfigJson,
  addSplashScreenPreferencesToConfigJson
} from './utils/configXmlUtils';

const SUPPORTED_SOURCE_EXTENSIONS = ['.psd', '.ai', '.png'];
const UPLOAD_URL = 'http://res.ionic.io/api/v1/upload';
const TRANSFORM_URL = 'http://res.ionic.io/api/v1/transform';
const RESOURCES_CONFIG_FILE = path.join(__dirname, '..', '..', 'resources.json');
const DEFAULT_RESOURCES_DIR = path.resolve(__dirname, '..', '..', 'default-resources');

/**
 * Take the JSON structure for resources.json and turn it into a flat array
 * that contains only images and turns all struture info into attributes of the image
 * items.
 */
export function flattenResourceJsonStructure (jsonStructure: any): ImageResource[] {
  return flatten(Object.keys(jsonStructure).map(platform => (
    Object.keys(jsonStructure[platform]).map(resType => (
      jsonStructure[platform][resType]['images'].map((imgInfo: any) => (
        {
          platform,
          resType,
          name: imgInfo.name,
          width: imgInfo.width,
          height: imgInfo.height,
          density: imgInfo.density,
          nodeName: jsonStructure[platform][resType]['nodeName'],
          nodeAttributes: jsonStructure[platform][resType]['nodeAttributes']
        }
      ))
    )))
  ));
}

/**
 * Create the destination directories for the provided image resources.
 */
export async function createImgDestinationDirectories (imgResources: ImageResource[]): Promise<void[]> {
  const buildDirPromises: Promise<void>[] = imgResources
    .map(img => path.dirname(img.dest))
    .filter((dir, index, dirNames) => dirNames.indexOf(dir) === index)
    .map(dir => fsMkdirp(dir));

  return Promise.all(buildDirPromises);
}

/**
 * Read the resources config and return the Json.
 */
export async function getResourceConfigJson(): Promise<ResourcesConfig> {
  let resourceJsonStructure;
  const filePath = RESOURCES_CONFIG_FILE;
  try {
    resourceJsonStructure = await fsReadJsonFile(filePath);
  } catch (e) {
    if (e === ERROR_FILE_NOT_FOUND) {
      throw new Error(`${filePath} not found`);
    } else if (e === ERROR_FILE_INVALID_JSON) {
      throw new Error(`${filePath} is not valid JSON.`);
    }
    throw e;
  }
  return <ResourcesConfig>resourceJsonStructure;
}

/**
 * Find all source images within the resources directory
 */
export async function getSourceImages (buildPlatforms: string[], resourceTypes: string[], resourceDir: string): Promise<SourceImage[]> {
  const srcDirList = buildPlatforms
    .map((platform: string) => (
      {
        platform,
        path: path.join(resourceDir, platform)
      }
    ))
    .concat({
      platform: 'global',
{'fraction_non_alphanumeric': 0.12756551941900854, 'fraction_numerical': 0.0006315124723713293, 'mean_word_length': 3.858128834355828, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2552041', 'n_tokens_mistral': 1883, 'n_tokens_neox': 1866, 'n_words': 456}