Buffers emit 'before-save' and 'after-save' events during save

This commit is contained in:
Nathan Sobo
2012-04-17 17:45:40 -06:00
parent 331984148f
commit 0a9e14a408
2 changed files with 35 additions and 7 deletions

View File

@@ -159,23 +159,39 @@ describe 'Buffer', ->
describe ".save()", ->
describe "when the buffer has a path", ->
filePath = null
[filePath, buffer] = []
beforeEach ->
filePath = require.resolve('fixtures') + '/temp.txt'
expect(fs.exists(filePath)).toBeFalsy()
filePath = '/tmp/temp.txt'
fs.remove filePath if fs.exists(filePath)
buffer = new Buffer filePath
afterEach ->
fs.remove filePath
fs.remove filePath if fs.exists(filePath)
it "saves the contents of the buffer to the path", ->
buffer = new Buffer filePath
buffer.setText 'Buffer contents!'
buffer.save()
expect(fs.read(filePath)).toEqual 'Buffer contents!'
it "fires beforeSave and afterSave events around the call to fs.write", ->
events = []
beforeSave1 = -> events.push('beforeSave1')
beforeSave2 = -> events.push('beforeSave2')
afterSave1 = -> events.push('afterSave1')
afterSave2 = -> events.push('afterSave2')
buffer.on 'before-save', beforeSave1
buffer.on 'before-save', beforeSave2
spyOn(fs, 'write').andCallFake -> events.push 'fs.write'
buffer.on 'after-save', afterSave1
buffer.on 'after-save', afterSave2
buffer.save()
expect(events).toEqual ['beforeSave1', 'beforeSave2', 'fs.write', 'afterSave1', 'afterSave2']
describe "when the buffer no path", ->
it "throw an exception", ->
it "throws an exception", ->
buffer = new Buffer
expect(-> buffer.save()).toThrow()
@@ -313,6 +329,13 @@ describe 'Buffer', ->
expect(buffer.lineForRow(5)).toBe ' foo = items.shift();'
expect(buffer.lineForRow(6)).toBe ' foo < pivot ? left.push(foo) : right.push(current);'
it "allows the match to be replaced with the empty string", ->
buffer.scanInRange /current/g, [[4,0], [6,59]], (match, range, { replace }) ->
replace("")
expect(buffer.lineForRow(5)).toBe ' = items.shift();'
expect(buffer.lineForRow(6)).toBe ' < pivot ? left.push() : right.push(current);'
describe "when the iterator calls the 'stop' control function", ->
it "stops the traversal", ->
ranges = []

View File

@@ -142,7 +142,9 @@ class Buffer
save: ->
if not @getPath() then throw new Error("Tried to save buffer with no file path")
@trigger 'before-save'
fs.write @getPath(), @getText()
@trigger 'after-save'
saveAs: (path) ->
@setPath(path)
@@ -185,6 +187,9 @@ class Buffer
matches
scan: (regex, iterator) ->
@scanInRange(regex, @getRange(), iterator)
scanInRange: (regex, range, iterator, reverse=false) ->
range = Range.fromObject(range)
global = regex.global
@@ -214,7 +219,7 @@ class Buffer
replacementText = null
iterator(match, range, { stop, replace })
if replacementText
if replacementText?
@change(range, replacementText)
lengthDelta += replacementText.length - matchLength unless reverse