/**
 * @module core/utils/fs
 */

const Promise = require('bluebird')
const childProcess = require('child_process')
const { shell } = require('electron')

const logger = require('./logger')

Promise.promisifyAll(childProcess)

const log = logger({
  component: 'Fs'
})

/** Hide a directory on Windows.
 *
 * Errors are logged, not thrown.
 */
async function hideOnWindows(path /*: string */) /*: Promise<void> */ {
  if (process.platform !== 'win32') return
  try {
    await childProcess.execAsync(`attrib +h "${path}"`)
  } catch (err) {
    log.warn(err)
  }
}

const ILLEGAL_CHARACTERS = '/?<>\\:*|"'
const ILLEGAL_CHARACTERS_REGEXP = new RegExp(`[${ILLEGAL_CHARACTERS}]`, 'g')
const REPLACEMENT_CHARACTER = '_'

// Return a new name compatible with target filesystems by replacing invalid
// characters from the given file/dir name.
function validName(name /*: string */) {
  return name.replace(ILLEGAL_CHARACTERS_REGEXP, REPLACEMENT_CHARACTER)
}

async function sendToTrash(fullpath /*: string */) {
  try {
    await shell.trashItem(fullpath)
  } catch (err) {
    if (
      err.message === 'Failed to move item to trash' || // Error message on Linux
      err.message === 'Failed to parse path' || // Error message on Windows
      /doesn’t exist/.test(err.message) // Error message on macOS
    ) {
      const error = new Error()
      error.code = 'ENOENT'
      error.path = fullpath
      error.message = `${error.code}: No such file or directory, sendToTrash '${error.path}'`
      throw error
    }

    throw err
  }
}

module.exports = {
  hideOnWindows,
  sendToTrash,
  validName
}

@@ -146,16 +146,48 @@
 ectron')
+%0Aconst fse = require('fs-extra')
 %0A%0Aconst 
@@ -398,16 +398,20 @@
 Windows(
+full
 path /*:
@@ -543,16 +543,20 @@
 b +h %22$%7B
+full
 path%7D%22%60)
@@ -1115,238 +1115,64 @@
 if (
-%0A      err.message === 'Failed to move item to trash' %7C%7C // Error message on Linux%0A      err.message === 'Failed to parse path' %7C%7C // Error message on Windows%0A      /doesn%E2%80%99t exist/.test(err.message) // Error message on macOS%0A    )
+await fse.exists(fullpath)) %7B%0A      throw err%0A    %7D else
  %7B%0A 
@@ -1379,23 +1379,8 @@
    %7D
-%0A%0A    throw err
 %0A  %7D

Check for doc presence when handling trash errors (#2120)