]> arthur.barton.de Git - atom-ax-pipe.git/blob - lib/pipe.coffee
5294840bd507d0833bc6a85f296f20a40320056f
[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.workspaceView.command '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       for range in editor.getSelectedBufferRanges()
30         marker = editor.markBufferRange range, properties
31         processRange marker, editor, commandString
32
33       view.focus()
34
35 processRange = (marker, editor, commandString) ->
36   stdout = ''
37   stderr = ''
38
39   proc = spawn process.env.SHELL, ["-l", "-c", commandString]
40
41   proc.stdout.on 'data', (text) ->
42     stdout += text
43
44   proc.stderr.on 'data', (text) ->
45     stderr += text
46
47   proc.on 'close', (code) ->
48     text = stderr || stdout
49     editor.setTextInBufferRange(marker.getBufferRange(), text)
50
51   proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
52   proc.stdin.end()