]> arthur.barton.de Git - atom-ax-pipe.git/blob - lib/pipe.coffee
7c97563e4eb1e2028090ad4a35a7b6e7fa1547ad
[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.getActiveEditor()
13     view = atom.workspaceView.getActiveView()
14     return if not editor?
15
16     new CommandView history, (commandString) ->
17       if not commandString
18         view.focus()
19         return
20
21       history.push commandString
22       if history.length > 300
23         history.shift()
24
25       if atom.project.rootDirectory?
26         commandString = "cd '#{atom.project.rootDirectory.path}' && #{commandString}"
27       properties = { reversed: true, invalidate: 'never' }
28
29       ranges = editor.getSelectedBufferRanges()
30       wg = new WaitGroup ->
31         view.focus()
32
33       wg.add(ranges.length)
34
35       for range, i in ranges
36         marker = editor.markBufferRange range, properties
37         processRange marker, editor, commandString, wg
38
39 processRange = (marker, editor, commandString, wg) ->
40   stdout = ''
41   stderr = ''
42
43   proc = spawn process.env.SHELL, ["-l", "-c", commandString]
44
45   proc.stdout.on 'data', (text) ->
46     stdout += text
47
48   proc.stderr.on 'data', (text) ->
49     stderr += text
50
51   proc.on 'close', (code) ->
52     text = stderr || stdout
53     editor.setTextInBufferRange(marker.getBufferRange(), text)
54     wg.done()
55
56   proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
57   proc.stdin.end()
58
59 class WaitGroup
60   constructor: (cb) ->
61     @n = 0
62     @cb = cb
63
64   add: (n) ->
65     @n += n
66
67   done: ->
68     @n -= 1
69     if @n <= 0
70       @cb()