'use strict';

const fs = require('fs'),
  Promise = require('bluebird'),
  path = require('path'),
  urlParser = require('url'),
  moment = require('moment');

Promise.promisifyAll(fs);
const mkdirp = Promise.promisify(require('mkdirp'));

const defaultDir = 'sitespeed-result';
let timestamp = moment().format().replace(/:/g, '');

class StorageManager {
  constructor(options) {
    this.baseDir = path.resolve(process.cwd(), options.resultBaseDir || defaultDir, timestamp);
  }

  relativePathFromUrl(url) {
    let parsedUrl = urlParser.parse(url);

    let p = path.join.apply(null, parsedUrl.pathname.split('/'));

    return path.join(parsedUrl.hostname, p);
  }

  createDataDir() {
    return Promise.resolve(this.baseDir)
      .tap((baseDir) => mkdirp(baseDir));
  }

  writeData(filename, data) {
    return this._write(this.createDataDir(), filename, data);
  }

  createDataDirForUrl(url) {
    return Promise.resolve(path.join(this.baseDir, this.relativePathFromUrl(url)))
      .tap((dirPath) => mkdirp(dirPath));
  }

  writeDataForUrl(url, filename, data) {
    return this._write(this.createDataDirForUrl(url), filename, data);
  }

  _write(dirPath, filename, data) {
    return Promise.join(dirPath, filename, data,
      (dirPath, filename, data) =>
        fs.writeFileAsync(path.join(dirPath, filename), data, 'utf8'));
  }
}

module.exports = StorageManager;

@@ -93,16 +93,46 @@
 path'),%0A
+  crypto = require('crypto'),%0A
   urlPar
@@ -181,16 +181,55 @@
 moment')
+,%0A  isEmpty = require('./util').isEmpty
 ;%0A%0APromi
@@ -578,18 +578,20 @@
 ) %7B%0A    
-le
+cons
 t parsed
@@ -620,44 +620,30 @@
 url)
-;%0A
+,
 %0A    
-let p = path.join.apply(null,
+  pathSegments =
  par
@@ -672,54 +672,309 @@
 '/')
-);%0A%0A    return path.join(parsedUrl.hostname, p
+;%0A%0A    pathSegments.unshift(parsedUrl.hostname);%0A%0A    if (!isEmpty(parsedUrl.search)) %7B%0A      const md5 = crypto.createHash('md5'),%0A        hash = md5.update(parsedUrl.search).digest('hex').substring(0, 8);%0A      pathSegments.push('query-' + hash);%0A    %7D%0A%0A    return path.join.apply(null, pathSegments
 );%0A 

Make filename unique with md5 sum of query string