]> arthur.barton.de Git - atom-ax-pipe.git/blob - lib/pipe.coffee
Merge pull request #8 from andrewwillis/remove_deprecations
[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         editor.commitTransaction()
32         view.focus()
33
34       wg.add(ranges.length)
35
36       editor.beginTransaction()
37       for range, i in ranges
38         marker = editor.markBufferRange range, properties
39         processRange marker, editor, commandString, wg
40
41 processRange = (marker, editor, commandString, wg) ->
42   stdout = ''
43   stderr = ''
44
45   proc = spawn process.env.SHELL, ["-l", "-c", commandString]
46
47   proc.stdout.on 'data', (text) ->
48     stdout += text
49
50   proc.stderr.on 'data', (text) ->
51     stderr += text
52
53   proc.on 'close', (code) ->
54     text = stderr || stdout
55     editor.setTextInBufferRange(marker.getBufferRange(), text)
56     wg.done()
57
58   proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
59   proc.stdin.end()
60
61 class WaitGroup
62   constructor: (cb) ->
63     @n = 0
64     @cb = cb
65
66   add: (n) ->
67     @n += n
68
69   done: ->
70     @n -= 1
71     if @n <= 0
72       @cb()