fs = require('fs')
temp = require('temp')
child_process = require('child_process')
async = require('async')
winston = require('winston')
message = require('smc-util/message')
misc_node = require('smc-util-node/misc_node')
misc = require('smc-util/misc')
common = require('./common')
exports.read_file_from_project = (socket, mesg) ->
data = undefined
path = misc_node.abspath(mesg.path)
is_dir = undefined
id = undefined
archive = undefined
stats = undefined
async.series([
(cb) ->
fs.stat path, (err, _stats) ->
if err
cb(err)
else
stats = _stats
is_dir = stats.isDirectory()
cb()
(cb) ->
cb(common.check_file_size(stats.size))
(cb) ->
if is_dir
if mesg.archive != 'tar.bz2'
cb("The only supported directory archive format is tar.bz2")
return
target = temp.path(suffix:'.' + mesg.archive)
archive = mesg.archive
if path[path.length-1] == '/'
path = path.slice(0,path.length-1)
split = misc.path_split(path)
path = target
args = ["--exclude=.sagemathcloud*", '--exclude=.forever', '--exclude=.node*', '--exclude=.npm', '--exclude=.sage', '-jcf', target, split.tail]
child_process.execFile 'tar', args, {cwd:split.head}, (err, stdout, stderr) ->
if err
winston.debug("Issue creating tarball: #{err}, #{stdout}, #{stderr}")
cb(err)
else
cb()
else
cb()
(cb) ->
fs.readFile path, (err, _data) ->
data = _data
cb(err)
(cb) ->
id = misc_node.uuidsha1(data)
cb()
(cb) ->
socket.write_mesg 'json', message.file_read_from_project(id:mesg.id, data_uuid:id, archive:archive)
socket.write_mesg 'blob', {uuid:id, blob:data}
cb()
], (err) ->
if err and err != 'file already known'
socket.write_mesg('json', message.error(id:mesg.id, error:err))
if is_dir
fs.exists path, (exists) ->
if exists
fs.unlink(path)
)
exports.write_file_to_project = (socket, mesg) ->
data_uuid = mesg.data_uuid
path = misc_node.abspath(mesg.path)
write_file = (type, value) ->
if type == 'blob' and value.uuid == data_uuid
socket.removeListener('mesg', write_file)
async.series([
(cb) ->
misc_node.ensure_containing_directory_exists(path, cb)
(cb) ->
fs.writeFile(path, value.blob, cb)
], (err) ->
if err
socket.write_mesg 'json', message.error(id:mesg.id, error:err)
else
socket.write_mesg 'json', message.file_written_to_project(id:mesg.id)
)
socket.on('mesg', write_file)