]> arthur.barton.de Git - atom-ax-pipe.git/blob - lib/pipe.coffee
5ccd6b0349fa0c321b1a077583a12a12186f2ca8
[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       commandString = "cd '#{atom.project.rootDirectory.path}' && #{commandString}"
26       properties = { reversed: true, invalidate: 'never' }
27
28       for range in editor.getSelectedBufferRanges()
29         marker = editor.markBufferRange range, properties
30         processRange marker, editor, commandString
31
32       view.focus()
33
34 processRange = (marker, editor, commandString) ->
35   stdout = ''
36   stderr = ''
37
38   proc = spawn process.env.SHELL, ["-l", "-c", commandString]
39
40   proc.stdout.on 'data', (text) ->
41     stdout += text
42
43   proc.stderr.on 'data', (text) ->
44     stderr += text
45
46   proc.on 'close', (code) ->
47     text = stderr || stdout
48     editor.setTextInBufferRange(marker.getBufferRange(), text)
49
50   proc.stdin.write(editor.getTextInBufferRange(marker.getBufferRange()))
51   proc.stdin.end()