forked from kiddkai/atom-node-debugger
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebugger.coffee
More file actions
417 lines (354 loc) · 12.8 KB
/
debugger.coffee
File metadata and controls
417 lines (354 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
R = require 'ramda'
path = require 'path'
kill = require 'tree-kill'
Promise = require 'bluebird'
{Client} = require '_debugger'
childprocess = require 'child_process'
{EventEmitter} = require './eventing'
Event = require 'geval/event'
logger = require './logger'
fs = require 'fs'
NodeDebuggerView = require './node-debugger-view'
jumpToBreakpoint = require './jump-to-breakpoint'
log = (msg) -> #console.log(msg)
class ProcessManager extends EventEmitter
constructor: (@atom = atom)->
super()
@process = null
parseEnv: (env) ->
return null unless env
key = (s) -> s.split("=")[0]
value = (s) -> s.split("=")[1]
result = {}
result[key(e)] = value(e) for e in env.split(";")
return result
startActiveFile: () ->
@start true
start: (withActiveFile) ->
startActive = withActiveFile
@cleanup()
.then =>
packagePath = @atom.project.resolvePath('package.json')
packageJSON = JSON.parse(fs.readFileSync(packagePath)) if fs.existsSync(packagePath)
nodePath = @atom.config.get('node-debugger.nodePath')
nodeArgs = @atom.config.get('node-debugger.nodeArgs')
appArgs = @atom.config.get('node-debugger.appArgs')
port = @atom.config.get('node-debugger.debugPort')
env = @parseEnv @atom.config.get('node-debugger.env')
scriptMain = @atom.project.resolvePath(@atom.config.get('node-debugger.scriptMain'))
dbgFile = scriptMain || packageJSON && @atom.project.resolvePath(packageJSON.main)
if startActive == true || !dbgFile
editor = @atom.workspace.getActiveTextEditor()
appPath = editor.getPath()
dbgFile = appPath
cwd = path.dirname(dbgFile)
args = []
args = args.concat (nodeArgs.split(' ')) if nodeArgs
args.push "--debug-brk=#{port}"
args.push dbgFile
args = args.concat (appArgs.split(' ')) if appArgs
logger.error 'spawn', {args:args, env:env}
@process = childprocess.spawn nodePath, args, {
detached: true
cwd: cwd
env: env if env
}
@process.stdout.on 'data', (d) ->
logger.info 'child_process', d.toString()
@process.stderr.on 'data', (d) ->
logger.info 'child_process', d.toString()
@process.stdout.on 'end', () ->
logger.info 'child_process', 'end out'
@process.stderr.on 'end', () ->
logger.info 'child_process', 'end error'
@emit 'processCreated', @process
@process.once 'error', (err) =>
switch err.code
when "ENOENT"
logger.error 'child_process', "ENOENT exit code. Message: #{err.message}"
atom.notifications.addError(
"Failed to start debugger.
Exit code was ENOENT which indicates that the node
executable could not be found.
Try specifying an explicit path in your atom config file
using the node-debugger.nodePath configuration setting."
)
else
logger.error 'child_process', "Exit code #{err.code}. #{err.message}"
@emit 'processEnd', err
@process.once 'close', () =>
logger.info 'child_process', 'close'
@emit 'processEnd', @process
@process.once 'disconnect', () =>
logger.info 'child_process', 'disconnect'
@emit 'processEnd', @process
return @process
cleanup: ->
self = this
new Promise (resolve, reject) =>
return resolve() if not @process?
if @process.exitCode
logger.info 'child_process', 'process already exited with code ' + @process.exitCode
@process = null
return resolve()
onProcessEnd = R.once =>
logger.info 'child_process', 'die'
@emit 'processEnd', @process
@process = null
resolve()
logger.info 'child_process', 'start killing process'
kill @process.pid
@process.once 'disconnect', onProcessEnd
@process.once 'exit', onProcessEnd
@process.once 'close', onProcessEnd
class Breakpoint
constructor: (@editor, @script, @line) ->
@marker = null
@marker = @editor.markBufferPosition([@line, 0], invalidate: 'never')
@decoration = null
@onDidChangeSubscription = @marker.onDidChange (event) =>
log "Breakpoint.markerchanged: #{event.newHeadBufferPosition}"
@line = event.newHeadBufferPosition.row
@onDidDestroySubscription = @marker.onDidDestroy () =>
@marker = null
@decoration = null
@id = null
@updateVisualization()
dispose: () ->
@onDidChangeSubscription.dispose()
@onDidDestroySubscription.dispose()
@id = null
@decoration.destroy() if @decoration
@decoration = null
@marker.destroy() if @marker
@marker = null
setId: (@id) =>
@updateVisualization()
clearId: () =>
@setId(null)
updateVisualization: () =>
@decoration.destroy() if @decoration
className = if @id then 'node-debugger-attached-breakpoint' else 'node-debugger-detached-breakpoint'
@decoration = @editor.decorateMarker(@marker, type: 'line-number', class: className) if @marker
class BreakpointManager
constructor: (@debugger) ->
log "BreakpointManager.constructor"
@breakpoints = []
@client = null
@removeOnConnected = @debugger.subscribe 'connected', =>
log "BreakpointManager.connected"
@client = @debugger.client
@attachBreakpoint(breakpoint) for breakpoint in @breakpoints
@removeOnDisconnected = @debugger.subscribe 'disconnected', =>
log "BreakpointManager.disconnected"
@client = null
breakpoint.clearId() for breakpoint in @breakpoints
@onAddBreakpointEvent = Event()
@onRemoveBreakpointEvent = Event()
dispose: () ->
@removeOnConnected() if @removeOnConnected
@removeOnConnected = null
@removeOnDisconnected() if @removeOnDisconnected
@removeOnDisconnected = null
toggleBreakpoint: (editor, script, line) ->
log "BreakpointManager.toggleBreakpoint #{script}, #{line}"
maybeBreakpoint = @tryFindBreakpoint script, line
if maybeBreakpoint
@removeBreakpoint maybeBreakpoint.breakpoint, maybeBreakpoint.index
else
@addBreakpoint editor, script, line
removeBreakpoint: (breakpoint, index) ->
log "BreakpointManager.removeBreakpoint #{index}"
@breakpoints.splice index, 1
@onRemoveBreakpointEvent.broadcast breakpoint
@detachBreakpoint breakpoint.id
breakpoint.dispose()
addBreakpoint: (editor, script, line) ->
log "BreakpointManager.addBreakpoint #{script}, #{line}"
breakpoint = new Breakpoint(editor, script, line)
log "BreakpointManager.addBreakpoint - adding to list"
@breakpoints.push breakpoint
log "BreakpointManager.addBreakpoint - publishing event, num breakpoints=#{@breakpoints.length}"
@onAddBreakpointEvent.broadcast breakpoint
log "BreakpointManager.addBreakpoint - attaching"
@attachBreakpoint breakpoint
attachBreakpoint: (breakpoint) ->
log "BreakpointManager.attachBreakpoint"
self = this
new Promise (resolve, reject) ->
return resolve() unless self.client
log "BreakpointManager.attachBreakpoint - client request"
self.client.setBreakpoint {
type: 'script'
target: breakpoint.script
line: breakpoint.line
condition: breakpoint.condition
}, (err, res) ->
log "BreakpointManager.attachBreakpoint - done"
if err
breakpoint.clearId()
reject(err)
else
breakpoint.setId(res.breakpoint)
resolve(breakpoint)
detachBreakpoint: (breakpointId) ->
log "BreakpointManager.detachBreakpoint"
self = this
new Promise (resolve, reject) ->
return resolve() unless self.client
return resolve() unless breakpointId
log "BreakpointManager.detachBreakpoint - client request"
self.client.clearBreakpoint {
breakpoint: breakpointId
}, (err) ->
resolve()
tryFindBreakpoint: (script, line) ->
return { breakpoint: breakpoint, index: i } for breakpoint, i in @breakpoints when breakpoint.script is script and breakpoint.line is line
class Debugger extends EventEmitter
constructor: (@atom)->
super()
@client = null
@breakpointManager = new BreakpointManager(this)
@onBreakEvent = Event()
@onBreak = @onBreakEvent.listen
@onAddBreakpoint = @breakpointManager.onAddBreakpointEvent.listen
@onRemoveBreakpoint = @breakpointManager.onRemoveBreakpointEvent.listen
@processManager = new ProcessManager(@atom)
@processManager.on 'processCreated', @attachInternal
@processManager.on 'processEnd', @cleanupInternal
@onSelectedFrameEvent = Event()
@onSelectedFrame = @onSelectedFrameEvent.listen
@selectedFrame = null
jumpToBreakpoint(this)
getSelectedFrame: () => @selectedFrame
setSelectedFrame: (frame, index) =>
@selectedFrame = {frame, index}
@onSelectedFrameEvent.broadcast(@selectedFrame)
dispose: ->
@breakpointManager.dispose() if @breakpointManager
@breakpointManager = null
NodeDebuggerView.destroy()
jumpToBreakpoint.destroy()
stopRetrying: ->
return unless @timeout?
clearTimeout @timeout
step: (type, count) ->
self = this
new Promise (resolve, reject) =>
@client.step type, count, (err) ->
return reject(err) if err
resolve()
reqContinue: ->
self = this
new Promise (resolve, reject) =>
@client.req {
command: 'continue'
}, (err) ->
return reject(err) if err
resolve()
getScriptById: (id) ->
self = this
new Promise (resolve, reject) =>
@client.req {
command: 'scripts',
arguments: {
ids: [id],
includeSource: true
}
}, (err, res) ->
return reject(err) if err
resolve(res[0])
fullTrace: () ->
new Promise (resolve, reject) =>
@client.fullTrace (err, res) ->
return reject(err) if err
resolve(res)
start: =>
@debugHost = "127.0.0.1"
@debugPort = @atom.config.get('node-debugger.debugPort')
@externalProcess = false
NodeDebuggerView.show(this)
@processManager.start()
# debugger will attach when process is started
startActiveFile: =>
@debugHost = "127.0.0.1"
@debugPort = @atom.config.get('node-debugger.debugPort')
@externalProcess = false
NodeDebuggerView.show(this)
@processManager.startActiveFile()
# debugger will attach when process is started
attach: =>
@debugHost = @atom.config.get('node-debugger.debugHost')
@debugPort = @atom.config.get('node-debugger.debugPort')
@externalProcess = true
NodeDebuggerView.show(this)
@attachInternal()
attachInternal: =>
logger.info 'debugger', 'start connect to process'
self = this
attemptConnectCount = 0
attemptConnect = ->
logger.info 'debugger', 'attempt to connect to child process'
if not self.client?
logger.info 'debugger', 'client has been cleanup'
return
attemptConnectCount++
self.client.connect(
self.debugPort,
self.debugHost
)
onConnectionError = =>
logger.info 'debugger', "trying to reconnect #{attemptConnectCount}"
timeout = 500
@emit 'reconnect', {
count: attemptConnectCount
port: self.debugPort
host: self.debugHost
timeout: timeout
}
@timeout = setTimeout =>
attemptConnect()
, timeout
@client = new Client()
@client.once 'ready', @bindEvents
@client.on 'unhandledResponse', (res) => @emit 'unhandledResponse', res
@client.on 'break', (res) =>
@onBreakEvent.broadcast(res.body); @emit 'break', res.body
@setSelectedFrame(null)
@client.on 'exception', (res) => @emit 'exception', res.body
@client.on 'error', onConnectionError
@client.on 'close', () -> logger.info 'client', 'client closed'
attemptConnect()
bindEvents: =>
logger.info 'debugger', 'connected'
@emit 'connected'
@client.on 'close', =>
logger.info 'debugger', 'connection closed'
@processManager.cleanup()
.then =>
@emit 'close'
lookup: (ref) ->
new Promise (resolve, reject) =>
@client.reqLookup [ref], (err, res) ->
return reject(err) if err
resolve(res[ref])
eval: (text) ->
new Promise (resolve, reject) =>
@client.reqFrameEval text, @selectedFrame?.index or 0, (err, result) ->
return reject(err) if err
return resolve(result)
cleanup: =>
@processManager.cleanup()
NodeDebuggerView.destroy()
@cleanupInternal()
cleanupInternal: =>
@client.destroy() if @client
@client = null
jumpToBreakpoint.cleanup()
@emit 'disconnected'
isConnected: =>
return @client?
toggle: =>
NodeDebuggerView.toggle(this)
exports.Debugger = Debugger
exports.ProcessManager = ProcessManager