]> arthur.barton.de Git - atom-ax-pipe.git/blob - lib/pipe.coffee
Update ./lib/pipe.coffe to use current API
[atom-ax-pipe.git] / lib / pipe.coffee
1 {Range} = require 'atom'
2 {spawn} = require 'child_process'
3 CommandView = require './command-view'
4
5 history = []
6
7 module.exports =
8   activate: ->
9     atom.commands.add 'atom-workspace', "pipe:run", => @run()
10
11   run: ->
12     editor = atom.workspace.getActiveTextEditor()
13     return if not editor?
14
15     view = atom.views.getView(atom.workspace)
16
17     new CommandView history, (commandString) ->
18       if not commandString
19         view.focus()
20         return
21
22       history.push commandString
23       if history.length > 300
24         history.shift()
25
26       if atom.project.rootDirectory?
27         commandString = "cd '#{atom.project.rootDirectory.path}' && #{commandString}"
28       properties = { reversed: true, invalidate: 'never' }
29
30       ranges = editor.getSelectedBufferRanges()
31       wg = new WaitGroup ->
32         editor.commitTransaction()
33         view.focus()
34
35       wg.add(ranges.length)
36
37       editor.beginTransaction()
38       for range, i in ranges
39         marker = editor.markBufferRange range, properties
40         processRange marker, editor, commandString, wg
41
42 processRange = (marker, editor, commandString, wg) ->
43   stdout = ''
44   stderr = ''
45
46   proc = spawn process.env.SHELL, ["-l", "-c", commandString]
47
48   proc.stdout.on 'data', (text) ->
49     stdout += text
50
51   proc.stderr.on 'data', (text) ->
52     stderr += text
53
54   proc.on 'close', (code) ->
55     text = stderr || stdout
56     editor.setTextInBufferRange(marker.getBufferRange(), text)
57     wg.done()
58
59   proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
60   proc.stdin.end()
61
62 class WaitGroup
63   constructor: (cb) ->
64     @n = 0
65     @cb = cb
66
67   add: (n) ->
68     @n += n
69
70   done: ->
71     @n -= 1
72     if @n <= 0
73       @cb()