balena-cli/lib/actions/logs.coffee
2014-12-01 10:06:03 -04:00

49 lines
1.3 KiB
CoffeeScript

_ = require('lodash')
PubNub = require('pubnub')
resin = require('../resin')
helpers = require('../helpers/helpers')
LOGS_HISTORY_COUNT = 200
getLogData = (logs) ->
return logs[0] if _.isArray(logs)
return logs
printLogs = (logs, number) ->
logs = getLogData(logs)
logs = _.last(logs, number) if _.isNumber(number)
resin.log.array(logs, resin.log.out)
exports.logs = (uuid) ->
numberOfLines = resin.cli.getArgument('num', _.parseInt)
tailOutput = resin.cli.getArgument('tail') or false
if numberOfLines? and not _.isNumber(numberOfLines)
resin.errors.handle(new Error('n/num should be a number'))
helpers.isDeviceUUIDValid uuid, (error, isValidUUID) ->
resin.errors.handle(error) if error?
if not isValidUUID
return resin.errors.handle(new Error('Invalid UUID'))
# PubNub needs to be initialised after logs
# action was called, otherwise it prevents
# all other actions from exiting on completion
pubnub = PubNub.init(resin.config.pubnub)
channel = _.template(resin.config.events.deviceLogs, { uuid })
pubnub.history
count: LOGS_HISTORY_COUNT
channel: channel
callback: (logs) ->
printLogs(logs, numberOfLines)
if not tailOutput or numberOfLines?
process.exit(0)
if tailOutput
pubnub.subscribe
channel: channel
callback: printLogs