 Q = require 'q'
 _ = require 'underscore-plus'
 fs = require 'fs-plus'
+path = require 'path'
 
 Point = require './point'
 Range = require './range'

    @emit 'will-be-saved', this if Grim.includeDeprecatedAPIs
    @setPath(filePath)

    if options?.backup and @file.existsSync()
      backupFilePath = filePath + '~'
      backupFilePath += '~' while fs.existsSync(backupFilePath)
      fs.writeFileSync(backupFilePath, @file.readSync())

    try
      @file.writeSync(@getText())
      fs.removeSync(backupFilePath) if backupFilePath?
    catch error
      if backupFilePath?
        fs.writeFileSync(filePath, fs.readFileSync(backupFilePath))

    Q(@file?.read(flushCache) ? "").then (contents) =>
      @cachedDiskContents = contents
      callback?()

  # Creates a backup file for the given path when writing.
  backupFileContentsBeforeWriting: ->
    return unless @file.existsSync()

    backupFilePath = @getPath() + '~'
    backupFilePath += '~' while fs.existsSync(backupFilePath)
    backupFD = fs.openSync(backupFilePath, 'w')
    fs.writeSync(backupFD, @file.readSync())

    # ensure backup file contents are really on disk before proceeding
    fs.fdatasyncSync(backupFD)
    fs.closeSync(backupFD)

    # ensure backup file directory entry is really on disk before proceeding
    backupDirectoryFD = fs.openSync(path.dirname(backupFilePath), 'r')
    fs.fdatasyncSync(backupDirectoryFD)
    fs.closeSync(backupDirectoryFD)

    backupFilePath

  ###
  Section: Private Utility Methods
