]> arthur.barton.de Git - atom-ax-pipe.git/blobdiff - lib/pipe.coffee
Merge pull request #15 from alexbarton/fix-keymaps-tag
[atom-ax-pipe.git] / lib / pipe.coffee
index ec25ab594b2d63b307ff4aa46424f9277c7c833d..97ada8a8b67092cfa294a493be4fdc635a32694f 100644 (file)
@@ -2,36 +2,71 @@
 {spawn} = require 'child_process'
 CommandView = require './command-view'
 
+history = []
+
 module.exports =
   activate: ->
-    atom.workspaceView.command 'pipe:run', => @run()
+    atom.commands.add 'atom-workspace', "pipe:run", => @run()
 
   run: ->
     editor = atom.workspace.getActiveEditor()
     view = atom.workspaceView.getActiveView()
     return if not editor?
 
-    new CommandView (commandString) ->
+    new CommandView history, (commandString) ->
       if not commandString
         view.focus()
         return
 
-      range = editor.getSelectedBufferRange()
-      stdout = ''
-      stderr = ''
+      history.push commandString
+      if history.length > 300
+        history.shift()
 
-      proc = spawn process.env.SHELL, ["-l", "-c", commandString]
+      if atom.project.rootDirectory?
+        commandString = "cd '#{atom.project.rootDirectory.path}' && #{commandString}"
+      properties = { reversed: true, invalidate: 'never' }
 
-      proc.stdout.on 'data', (text) ->
-        stdout += text
+      ranges = editor.getSelectedBufferRanges()
+      wg = new WaitGroup ->
+        editor.commitTransaction()
+        view.focus()
 
-      proc.stderr.on 'data', (text) ->
-        stderr += text
+      wg.add(ranges.length)
 
-      proc.on 'close', (code) ->
-        editor.setTextInBufferRange(range, stderr || stdout)
-        editor.setSelectedBufferRange(new Range(range.start, range.start))
-        view.focus()
+      editor.beginTransaction()
+      for range, i in ranges
+        marker = editor.markBufferRange range, properties
+        processRange marker, editor, commandString, wg
+
+processRange = (marker, editor, commandString, wg) ->
+  stdout = ''
+  stderr = ''
+
+  proc = spawn process.env.SHELL, ["-l", "-c", commandString]
+
+  proc.stdout.on 'data', (text) ->
+    stdout += text
+
+  proc.stderr.on 'data', (text) ->
+    stderr += text
+
+  proc.on 'close', (code) ->
+    text = stderr || stdout
+    editor.setTextInBufferRange(marker.getBufferRange(), text)
+    wg.done()
+
+  proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
+  proc.stdin.end()
+
+class WaitGroup
+  constructor: (cb) ->
+    @n = 0
+    @cb = cb
+
+  add: (n) ->
+    @n += n
 
-      proc.stdin.write(editor.getSelectedText())
-      proc.stdin.end()
+  done: ->
+    @n -= 1
+    if @n <= 0
+      @cb()