<commit_before>// TODO: Rename to cli/test/helpers/scenarios.js

const Promise = require('bluebird')
const fs = require('fs-extra')
const glob = require('glob')
const _ = require('lodash')
const path = require('path')

const metadata = require('../../src/metadata')

const { cozy } = require('./cozy')

const debug = process.env.DEBUG ? console.log : () => {}

const disabledExtension = '.DISABLED'

const scenarioByPath = module.exports.scenarioByPath = scenarioPath => {
  // $FlowFixMe
  const scenario = require(scenarioPath)
  scenario.name = path.basename(path.dirname(scenarioPath), disabledExtension)
  scenario.path = scenarioPath
  scenario.disabled = scenarioPath.endsWith(disabledExtension) && 'scenario disabled'

  if (process.platform === 'win32' && scenario.expected && scenario.expected.prepCalls) {
    for (let prepCall of scenario.expected.prepCalls) {
      if (prepCall.src) {
        prepCall.src = prepCall.src.split('/').join('\\').toUpperCase()
        // @TODO why is src in maj
      }
      if (prepCall.path) prepCall.path = prepCall.path.split('/').join('\\')
      if (prepCall.dst) prepCall.dst = prepCall.dst.split('/').join('\\')
    }
  }

  return scenario
}

// TODO: Refactor to function
module.exports.scenarios =
  glob.sync(path.join(__dirname, '../scenarios/**/scenario.js*'), {})
    .map(scenarioByPath)

module.exports.loadFSEventFiles = (scenario) => {
  const eventFiles = glob.sync(path.join(path.dirname(scenario.path), 'local', '*.json*'))
  const disabledEventsFile = (name) => {
    if (process.platform === 'win32' && name.indexOf('win32') === -1) {
      return 'darwin/linux test'
    } else if (name.endsWith(disabledExtension)) {
      return 'disabled case'
    }
  }
  return eventFiles
    .map(f => {
      const name = path.basename(f)
      const disabled = scenario.disabled || disabledEventsFile(name)
      const events = fs.readJsonSync(f).map(e => {
        if (e.stats) {
          e.stats.mtime = new Date(e.stats.mtime)
          e.stats.ctime = new Date(e.stats.ctime)
        }
        if (name.indexOf('win32') !== -1 && process.platform !== 'win32') {
          e.path = e.path.replace(/\\/g, '/')
        }
        if (name.indexOf('win32') === -1 && process.platform === 'win32') {
          e.path = e.path.replace(/\//g, '\\')
        }
        return e
      })

      return {name, events, disabled}
    })
}

module.exports.loadRemoteChangesFiles = (scenario) => {
  const pattern = path.join(path.dirname(scenario.path), 'remote', '*.json*')

  return glob.sync(pattern).map(f => {
    const name = path.basename(f)
    const disabled = scenario.disabled || f.endsWith(disabledExtension)
    const changes = fs.readJsonSync(f)
    return {name, disabled, changes}
  })
}

module.exports.init = async (scenario, pouch, abspath, relpathFix) => {
  debug('init')
  const remoteDocsToTrash = []
  for (let {path: relpath, ino, trashed} of scenario.init) {
    debug(relpath)
    const isOutside = relpath.startsWith('../outside')
    let remoteParent
    if (!isOutside) {
      debug('retrieve remote parent...')
      const remoteParentPath = path.posix.join('/', path.posix.dirname(relpath))
      remoteParent = await cozy.files.statByPath(remoteParentPath)
    }
    const lastModifiedDate = new Date('2011-04-11T10:20:30Z')
    if (relpath.endsWith('/')) {
      relpath = _.trimEnd(relpath, '/') // XXX: Check in metadata.id?
      relpath = relpathFix(relpath)

      if (!trashed) {
        debug('create local dir...')
        await fs.ensureDir(abspath(relpath))
      }

      const doc = {
        _id: metadata.id(relpath),
        docType: 'folder',
        updated_at: lastModifiedDate,
        path: relpath,
        ino,
        tags: [],
        sides: {local: 1, remote: 1}
      }

      if (!isOutside) {
        debug('create remote dir...', trashed ? '(trashed)' : '')
        const remoteDir = await cozy.files.createDirectory({
          name: path.basename(relpath),
          dirID: remoteParent._id,
          lastModifiedDate
        })
        doc.remote = _.pick(remoteDir, ['_id', '_rev'])
        if (trashed) remoteDocsToTrash.push(remoteDir)
        else {
          debug('create dir metadata...')
          await pouch.put(doc)
        }
      }
    } else {
      relpath = relpathFix(relpath)
      const content = 'foo'
      const md5sum = 'rL0Y20zC+Fzt72VPzMSk2A=='

      if (!trashed) {
        debug('create local file...')
        await fs.outputFile(abspath(relpath), content)
      }<commit_msg>test/helpers/scenarios: Allow creating initial metadata with real inode number<commit_after>// TODO: Rename to cli/test/helpers/scenarios.js

const Promise = require('bluebird')
const fs = require('fs-extra')
const glob = require('glob')
const _ = require('lodash')
const path = require('path')

const metadata = require('../../src/metadata')

const { cozy } = require('./cozy')

const debug = process.env.DEBUG ? console.log : () => {}

const disabledExtension = '.DISABLED'

const scenarioByPath = module.exports.scenarioByPath = scenarioPath => {
  // $FlowFixMe
  const scenario = require(scenarioPath)
  scenario.name = path.basename(path.dirname(scenarioPath), disabledExtension)
  scenario.path = scenarioPath
  scenario.disabled = scenarioPath.endsWith(disabledExtension) && 'scenario disabled'

  if (process.platform === 'win32' && scenario.expected && scenario.expected.prepCalls) {
    for (let prepCall of scenario.expected.prepCalls) {
      if (prepCall.src) {
        prepCall.src = prepCall.src.split('/').join('\\').toUpperCase()
        // @TODO why is src in maj
      }
      if (prepCall.path) prepCall.path = prepCall.path.split('/').join('\\')
      if (prepCall.dst) prepCall.dst = prepCall.dst.split('/').join('\\')
    }
  }

  return scenario
}

// TODO: Refactor to function
module.exports.scenarios =
  glob.sync(path.join(__dirname, '../scenarios/**/scenario.js*'), {})
    .map(scenarioByPath)

module.exports.loadFSEventFiles = (scenario) => {
  const eventFiles = glob.sync(path.join(path.dirname(scenario.path), 'local', '*.json*'))
  const disabledEventsFile = (name) => {
    if (process.platform === 'win32' && name.indexOf('win32') === -1) {
      return 'darwin/linux test'
    } else if (name.endsWith(disabledExtension)) {
      return 'disabled case'
    }
  }
  return eventFiles
    .map(f => {
      const name = path.basename(f)
      const disabled = scenario.disabled || disabledEventsFile(name)
      const events = fs.readJsonSync(f).map(e => {
        if (e.stats) {
          e.stats.mtime = new Date(e.stats.mtime)
          e.stats.ctime = new Date(e.stats.ctime)
        }
        if (name.indexOf('win32') !== -1 && process.platform !== 'win32') {
          e.path = e.path.replace(/\\/g, '/')
        }
        if (name.indexOf('win32') === -1 && process.platform === 'win32') {
          e.path = e.path.replace(/\//g, '\\')
        }
        return e
      })

      return {name, events, disabled}
    })
}

module.exports.loadRemoteChangesFiles = (scenario) => {
  const pattern = path.join(path.dirname(scenario.path), 'remote', '*.json*')

  return glob.sync(pattern).map(f => {
    const name = path.basename(f)
    const disabled = scenario.disabled || f.endsWith(disabledExtension)
    const changes = fs.readJsonSync(f)
    return {name, disabled, changes}
  })
}

module.exports.init = async (scenario, pouch, abspath, relpathFix, trueino) => {
  debug('init')
  const remoteDocsToTrash = []
  for (let {path: relpath, ino, trashed} of scenario.init) {
    debug(relpath)
    const isOutside = relpath.startsWith('../outside')
    let remoteParent
    if (!isOutside) {
      debug('retrieve remote parent...')
      const remoteParentPath = path.posix.join('/', path.posix.dirname(relpath))
      remoteParent = await cozy.files.statByPath(remoteParentPath)
    }
    const lastModifiedDate = new Date('2011-04-11T10:20:30Z')
    if (relpath.endsWith('/')) {
      relpath = _.trimEnd(relpath, '/') // XXX: Check in metadata.id?
      relpath = relpathFix(relpath)

      if (!trashed) {
        debug('create local dir...')
        await fs.ensureDir(abspath(relpath))
        if (trueino) ino = (await fs.stat(abspath(relpath))).ino
      }

      const doc = {
        _id: metadata.id(relpath),
        docType: 'folder',
        updated_at: lastModifiedDate,
        path: relpath,
        ino,
        tags: [],
        sides: {local: 1, remote: 1}
      }

      if (!isOutside) {
        debug('create remote dir...', trashed ? '(trashed)' : '')
        const remoteDir = await cozy.files.createDirectory({
          name: path.basename(relpath),
          dirID: remoteParent._id,
          lastModifiedDate
        })
        doc.remote = _.pick(remoteDir, ['_id', '_rev'])
        if (trashed) remoteDocsToTrash.push(remoteDir)
        else {
          debug('create dir metadata...')
          await pouch.put(doc)
        }
      }
    } else {
      relpath = relpathFix(relpath)
      const content = 'foo'
      const md5sum = 'rL0Y20zC+Fzt72VPzMSk2A=='

      if (!trashed) {
        debug('create local file...')
        await fs.outputFile(abspath(relpath), content)
        if (trueino) ino = (await fs.stat(abspath(relpath))).ino
      }
{'fraction_non_alphanumeric': 0.15737137916126243, 'fraction_numerical': 0.00864677907479464, 'mean_word_length': 2.7160642570281124, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 21, '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': '7293703', 'n_tokens_mistral': 3021, 'n_tokens_neox': 2954, 'n_words': 607}