/******************************************************************************* * Copyright (c) 2012, 2016 IBM Corporation and others. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ /*eslint-env node*/ var express = require('express'); var bodyParser = require('body-parser'); var ETag = require('./util/etag'); var fs = require('fs'); var nodePath = require('path'); var api = require('./api'); var fileUtil = require('./fileUtil'); var writeError = api.writeError; function getParam(req, paramName) { return req.query[paramName]; } module.exports = function(options) { var fileRoot = options.root; if (!fileRoot) { throw new Error('options.root is required'); } var writeFileMetadata = function() { var args = Array.prototype.slice.call(arguments, 0); var originalFileUrl = fileRoot; return fileUtil.writeFileMetadata.apply(null, [originalFileUrl].concat(args)); }; var getSafeFilePath = function(req, rest) { return fileUtil.safeFilePath(req.user.workspaceDir, rest); }; function writeFileContents(res, filepath, stats, etag) { if (stats.isDirectory()) { //shouldn't happen writeError(500, res, "Expected a file not a directory"); } else { var stream = fs.createReadStream(filepath); res.setHeader("Cache-Control", "no-cache"); res.setHeader('Content-Length', stats.size); res.setHeader('ETag', etag); res.setHeader('Accept-Patch', 'application/json-patch; charset=UTF-8'); stream.pipe(res); stream.on('error', function(e) { // FIXME this is wrong, headers have likely been committed at this point res.writeHead(500, e.toString()); res.end(); }); stream.on('end', res.end.bind(res)); } } function handleDiff(req, res, rest, body) { var diffs = body.diff || []; var contents = body.contents; var patchPath = getSafeFilePath(req, rest); fs.exists(patchPath, function(destExists) { if (destExists) { fs.readFile(patchPath, function (error, data) { if (error) { writeError(500, res, error); return; } try { var newContents = data.toString(); if (newContents.length > 0) { var code = newContents.charCodeAt(0); if (code === 0xFEFF || code === 0xFFFE) { newContents = newContents.substring(1); } } var buffer = { _text: [newContents], replaceText: function (text, start, end) { var offset = 0, chunk = 0, length; while (chunk