Replicate filesPromise functionality from webServer. Unfortunately we can’t access the webServer child DI injector from here where the filesPromise lives.
969831
function createFilesPromise(fileList, emitter, basePath) {
	var filesPromise = new common.PromiseContainer();
	// Set an empty list of files to avoid race issues with
	// file_list_modified not having been emitted yet
	filesPromise.set(Promise.resolve(fileList.files));
	emitter.on('file_list_modified', function (files) {
		filesPromise.set(Promise.resolve(files))
	});
	return filesPromise;
}
925174
function(fileObj) {
  return new Promise(function (resolve, reject) {
    window.requestFileSystem(window.TEMPORARY, 4*1024*1024*1024,
        function({root}){
          resolve({root:root, fileObj: fileObj})
        },
        function(err) {
          reject(err)
        }
    );
  });
}
798353
function createSourceFilesMiddleware (filesPromise, serveFile, basePath, urlRoot) {
  return function (request, response, next) {
    const requestedFilePath = composeUrl(request.url, basePath, urlRoot)
    // When a path contains HTML-encoded characters (e.g %2F used by Jenkins for branches with /)
    const requestedFilePathUnescaped = composeUrl(querystring.unescape(request.url), basePath, urlRoot)

    request.pause()

    log.debug(`Requesting ${request.url}`)
    log.debug(`Fetching ${requestedFilePath}`)

    return filesPromise.then(function (files) {
      // TODO(vojta): change served to be a map rather then an array
      const file = findByPath(files.served, requestedFilePath) || findByPath(files.served, requestedFilePathUnescaped)
      const rangeHeader = request.headers['range']

      if (file) {
        const acceptEncodingHeader = request.headers['accept-encoding']
        const matchedEncoding = Object.keys(file.encodings).find(
          (encoding) => new RegExp(`(^|.*, ?)${encoding}(,|$)`).test(acceptEncodingHeader)
        )
        const content = file.encodings[matchedEncoding] || file.content

        serveFile(file.contentPath || file.path, rangeHeader, response, function () {
          if (/\?\w+/.test(request.url)) {
            common.setHeavyCacheHeaders(response) // files with timestamps - cache one year, rely on timestamps
          } else {
            common.setNoCacheHeaders(response) // without timestamps - no cache (debug)
          }
          if (matchedEncoding) {
            response.setHeader('Content-Encoding', matchedEncoding)
          }
        }, content, file.doNotCache)
      } else {
        next()
      }

      request.resume()
    })
  }
}
57933
function copyFile(source, target) {
    var deferred,
        rd,
        wr;

    if (typeof fs.copyFile === 'function') {
        return Q.ninvoke(fs, 'copyFile', source, target);
    }

    deferred = Q.defer();

    rd = fs.createReadStream(source);
    wr = fs.createWriteStream(target);

    rd.on('error', function (err) {
        deferred.reject(err);
    });

    wr.on('error', function (err) {
        deferred.reject(err);
    });
    wr.on('close', function () {
        deferred.resolve();
    });

    rd.pipe(wr);

    return deferred.promise;
}
293337
function copyFile(srcPath, destPath) {
        let srcFileInfo = path.parse(srcPath) || {};
        if (!path.extname(destPath) && srcFileInfo.ext) {
            // destination is a directory!
            return copyFileIntoDirectory(srcPath, destPath);
        } else {
            return new Promise(function (resolve, reject) {
                fs.copy(srcPath, destPath, function (err) {
                    if (!err) {
                        resolve();
                    } else {
                        reject(err);
                    }
                });
            });
        }
    }
1332907
function(filepath, req, res) {
    var path = require("path"),
        config = module.exports.config,
        result = false,
        parentdir;
    do {
        var defaultdir = path.resolve(path.join(config.responsesdefault, filepath));
        parentdir = path.resolve(path.join(config.responses, filepath));
        if (isValidDir(parentdir) && isValidFile(path.join(parentdir, "index.js"))) {
            //Parent module response handler exists.
            require(parentdir)(req, res);
            result = true;
        } else if (isValidDir(defaultdir) && isValidFile(path.join(defaultdir, "index.js"))) {
            //Default response handler
            require(defaultdir)(req, res);
            result = true;
        }
        if (filepath === path.sep) break;
        filepath = path.dirname(filepath);
    } while (result === false && parentdir !== filepath);
    return result;
}
883950
def safe_inject_into_file(relative_path, *args, **options, &block)
      inject_into_file(relative_path, *args, **(options.merge(force: false)), &block)
    end
728815
function (filePath,buffer)
		{
			if (!_.isString(filePath))
				done.reject(false);
			else {
				var realPath = done.promise.filePath = this.instanceOf('wnModule')?this.modulePath+filePath:filePath;
				done.promise.returnAsBuffer=buffer=buffer || true;

				fs.readFile(realPath,function (err,text) {
					if (err)
						done.reject(err);
					else
					{
						if (!buffer)
							text=text.toString('utf8');
						done.resolve(text);
					}
				});
			}

			return done.promise;
		}
1366074
function injectBefore(replServer, method, beforeFn) {
  var _orig = replServer[method];
  replServer[method] = function() {
    var args = Array.prototype.slice.call(arguments);
    var callback = args.pop();
    beforeFn.apply(null, args.concat(function(err, res) {
      if (err || res) {
        callback(err, res);
      } else {
        _orig.apply(replServer, args.concat(callback));
      }
    }));
  };
  return replServer;
}
1198998
function (serverRelativeUrl, list, ctx) {
		var dfd = $.Deferred();

		folderExists(serverRelativeUrl, ctx, list.get_parentWeb()).done(function (folder) {
			if (folder === false) {

				var parentFolders = pathSteps(serverRelativeUrl);
				var parentFolderPath = parentFolders[1];
				var bits = serverRelativeUrl.split("/");
				var name = bits[bits.length - 1];
				ensureFolderInList(parentFolderPath, list, ctx).done(function () /*parentSpFolder*/ {
					createFolderInList(name, parentFolderPath, list, ctx).done(function (folder) {
						dfd.resolve(folder);
					});
				});
			} else {
				dfd.resolve(folder);
			}
		});
		return dfd.promise();
	}
246644
function copyFile(from, to) {
  return new Promise((resolve, reject) => {
    fs.copyFile(from, to, (err) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(to);
    });
  });
}
56258
function copy(inputdir, outputdir, options) {
	const _options = Object.assign({ dir: '.' }, options);
	fsPlus.copySync(path.join(inputdir, _options.dir), outputdir);
	return Promise.resolve();
}
1119265
function output(sourceCode, filePath) {
    return new Promise(function (resolve, reject) {
        mkdirp(path.dirname(filePath), function (ioErr) {
            if (ioErr) {
                reject(ioErr);
                throw ioErr;
            }
            fs.writeFile(filePath, sourceCode, function (writeErr) {
                if (writeErr) {
                    reject(writeErr);
                    throw writeErr;
                }
                resolve();
            });
        });
    });
}
354828
function execPromise (cmd) {
  if (isTest) {
    return Promise.resolve(cmd)
  }
  return new Promise((resolve, reject) => {
    exec(cmd, (err, stdout, stderr) => {
      if (err || stderr) reject(err || stderr)
      else resolve(stdout)
    })
  })
}
142105
function pretendRequire(file)
{
  if (file && file.substr(0, 1) == '/')
  {
    file = path.join(projectPath, file.substr(1));
  }

  return require(file);
}
324772
function createUploadPromise(filepath, destination, options) {
    return function () {
      // get the name of the file and construct the url for uploading it
      var filename = getFilename(filepath),
        dropboxPath = destination + (options.version_name ? ("/" + options.version_name + "/") : "/") + filepath,
        // read the file and start the upload, decrementing the in-flight count when complete
        // Use encoding = null to keep the file as a Buffer
        reqOptions = {
          access_token: options.access_token,
          dropboxPath: dropboxPath,
          fileBuffer: grunt.file.read(filepath, { encoding : null })
        };

      grunt.log.writeln("Uploading " + filepath + " to " + dropboxPath + "...");

      // return the upload promise
      return dropboxClient.upload(reqOptions);
    };
  }
986260
function fork(modulePath, args, options) {
	return new Promise((resolve, reject) => {
		const newEnv = generatePatchedEnv(process.env, options.IN_PORT, options.OUT_PORT),
		childProcess = cp.spawn(modulePath, args, {
			silent: true,
			cwd: options.cwd,
			env: newEnv,
			execArgv: options.execArgv
		});
		childProcess.once('error', function(err) {
			logger.error("Java process error event");
			logger.error(err);
			reject(err);
		});
		childProcess.once('exit', function(err) {
			logger.error("Java process exit event");
			logger.error(err);
			reject(err);
		});
		resolve(childProcess);
	});
}