import { Promise, map, promisify } from 'bluebird';
import { resolve, basename, dirname, join } from 'path';
import { createReadStream, writeFile } from 'fs';
import { createGunzip } from 'zlib';
import { Extract } from 'tar';
import { fromFile } from 'check-hash';
import wreck from 'wreck';
import { mkdirp } from 'mkdirp';

const mkdirpAsync = promisify(mkdirp);
const wreckGetAsync = promisify(wreck.get, wreck);
const checkHashFromFileAsync = promisify(fromFile);
const writeFileAsync = promisify(writeFile);

export default function downloadNodeBuilds(grunt) {
  const platforms = grunt.config.get('platforms');
  const downloadLimit = 3;

  const shaSums = {};
  const getShaSums = () => {
    const nodeVersion = grunt.config.get('nodeVersion');
    const shaSumsUri = `https://nodejs.org/dist/v${nodeVersion}/SHASUMS256.txt`;

    return wreckGetAsync(shaSumsUri).then(([resp, payload]) => {
      if (resp.statusCode !== 200) {
        throw new Error(`${shaSumsUri} failed with a ${resp.statusCode} response`);
      }
      payload
      .toString('utf8')
      .split('\n')
      .forEach(line => {
Exemple #2
0
let { join } = require('path');
let { promisify } = require('bluebird');
const read = promisify(require('fs').readFile);
const write = promisify(require('fs').writeFile);
const unlink = promisify(require('fs').unlink);
const stat = promisify(require('fs').stat);

module.exports = class UiBundle {
  constructor(opts) {

    opts = opts || {};
    this.id = opts.id;
    this.modules = opts.modules;
    this.template = opts.template;
    this.env = opts.env;

    const pathBase = join(this.env.workingDir, this.id);
    this.entryPath = `${pathBase}.entry.js`;
    this.outputPath = `${pathBase}.bundle.js`;

  }

  renderContent() {
    return this.template({
      env: this.env,
      bundle: this
    });
  }

  async readEntryFile() {
Exemple #3
0
/**
 * Created by Bell on 16/8/10.
 */

import mongoose from 'mongoose';
import bcrypt from 'bcrypt';
import config from '../config';
import jwt from 'jsonwebtoken';
import Promise from 'bluebird';

const hashAsync = Promise.promisify(bcrypt.hash);
const compareAsync = Promise.promisify(bcrypt.compare);

mongoose.Promise = global.Promise;

const User = new mongoose.Schema({
    type: {type: String, default: 'User'},
    name: {type: String},
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true}
});

User.pre('save', async function preSave(next) {
    const user = this;

    if (!user.isModified('password')) {
        return next();
    }
    try {
        const hash = await hashAsync(user.password, 10);
        user.password = hash;
var gulp = require('gulp');
var runSequence = require('run-sequence');

var child = require('child_process');
var path = require('path');
var Promise = require('bluebird');
var rimraf = require('rimraf-promise');
var svn = require('svn-interface');
var mkdirp = require('mkdirp');


mkdirp = Promise.promisify(mkdirp);
svn = Promise.promisifyAll(svn);


var buildRoot = './build';
var libphonenumberUrl = 'https://github.com/googlei18n/libphonenumber/';
var closureCompilerUrl = 'https://github.com/google/closure-compiler.git';
var closureLibraryUrl = 'https://github.com/google/closure-library/';
var closureLinterUrl = 'https://github.com/google/closure-linter.git';
var pythonGflagsUrl = 'https://github.com/google/python-gflags.git';

var isDebug = process.env.DEBUG && process.env.DEBUG !== '0';

gulp.task('clean', () => rimraf(buildRoot)
);

gulp.task('make-build-dir', () => mkdirp(buildRoot)
);
Exemple #5
0
var async = require("async");
var Promise = require("bluebird");
var mkdirp = Promise.promisify(require("mkdirp"));
var del = require("del");
var fs = require("fs");
var DefaultBuilder = require("truffle-default-builder");
var Contracts = require("./contracts");
var BuildError = require("./errors/builderror");
var child_process = require("child_process");
var spawnargs = require("spawn-args");
var _ = require("lodash");
var expect = require("./expect");

function CommandBuilder(command) {
  this.command = command;
};

CommandBuilder.prototype.build = function(options, callback) {
  console.log("Running `" + this.command + "`...")

  var args = spawnargs(this.command);
  var ps = args.shift();

  var cmd = child_process.spawn(ps, args, {
    detached: false,
    cwd: options.working_directory,
    env: _.merge(process.env, {
      WORKING_DIRECTORY: options.working_directory,
      BUILD_DESTINATION_DIRECTORY: options.destination_directory,
      BUILD_CONTRACTS_DIRECTORY: options.contracts_build_directory,
      WEB3_PROVIDER_LOCATION: "http://" + options.rpc.host + ":" + options.rpc.port
import _fs from 'fs';
import rimraf from 'rimraf';
import md5file from 'md5-file';
import ncp from 'ncp';
import B from 'bluebird';
import mv from 'mv';
import which from 'which';
import glob from 'glob';


const md5 = B.promisify(md5file);

let fs = {
  hasAccess: async function (path) {
    try {
      await this.access(path, fs.F_OK | fs.R_OK);
    } catch (err) {
      return false;
    }
    return true;
  },
  exists: function (path) { return this.hasAccess(path); },
  rimraf: B.promisify(rimraf),
  mkdir: async function (dirName) {
    let _mkdir = B.promisify(_fs.mkdir);
    try {
      await _mkdir(dirName);
    } catch (err) {
      if (err && err.code !== "EEXIST") {
        throw err;
      }
Exemple #7
0
// jscs:disable requireMultipleVarDecl

'use strict';

var fs = require('fs-extra'),
    os = require('os'),
    path = require('path'),
    Promise = require('bluebird'),
    config = require('../config'),
    utils = require('../utils'),
    LocalFileStorage = require('../adapters/storage/LocalFileStorage'),
    remove = Promise.promisify(fs.remove);

/**
 * @TODO: combine with loader.js?
 */
class ThemeStorage extends LocalFileStorage {
    constructor() {
        super();

        this.storagePath = config.getContentPath('themes');
    }

    getTargetDir() {
        return this.storagePath;
    }

    serve(options) {
        var self = this;

        return function downloadTheme(req, res, next) {
Exemple #8
0
// static
import Static from './utils/static';

// initialize Hapi server
const server = new Hapi.Server({
  connections: {
    routes: {
      files: {
        relativeTo: path.join(__dirname, '../client')
      }
    }
  }
});

// Promisify server methods
const register = Promise.promisify(server.register, {context: server});
const start = Promise.promisify(server.start, {context: server});

// initialize server connections
server.connection({
  host: conf.host,
  port: conf.port
});

const goodOptions = {
  reporters: [
    {
      reporter: goodConsole,    // Log everything to console
      events: {log: '*', response: '*'}
    }
  ]
Exemple #9
0
 return P.try(function(){
     return P.promisify(env.flushdb);
 })
Exemple #10
0
'use strict'

const path = require('path')
const fs = require('graceful-fs')
const linkIfExists = require('gentle-fs').linkIfExists
const cmdShimIfExists = require('cmd-shim').ifExists
const asyncMap = require('slide').asyncMap
const BB = require('bluebird')
const open = BB.promisify(fs.open)
const close = BB.promisify(fs.close)
const stat = BB.promisify(fs.stat)
const chmod = BB.promisify(fs.chmod)
const Transform = require('stream').Transform
const fsWriteStreamAtomic = require('fs-write-stream-atomic')

module.exports = BB.promisify(binLinks)

function binLinks (pkg, folder, global, opts, cb) {
  // if it's global, and folder is in {prefix}/node_modules,
  // then bins are in {prefix}/bin
  // otherwise, then bins are in folder/../.bin
  var parent = pkg.name && pkg.name[0] === '@' ? path.dirname(path.dirname(folder)) : path.dirname(folder)
  var gnm = global && opts.globalDir
  var gtop = parent === gnm

  opts.log.info('linkStuff', opts.pkgId)
  opts.log.silly('linkStuff', opts.pkgId, 'has', parent, 'as its parent node_modules')
  if (global) opts.log.silly('linkStuff', opts.pkgId, 'is part of a global install')
  if (gnm) opts.log.silly('linkStuff', opts.pkgId, 'is installed into a global node_modules')
  if (gtop) opts.log.silly('linkStuff', opts.pkgId, 'is installed into the top-level global node_modules')
 .then(() => {
     return Promise.promisify(n.db.create)("test");
 })
Exemple #12
0
import fs from 'fs';
import { createHash } from 'crypto';
import { resolve, dirname, isAbsolute, sep } from 'path';
import { createGunzip } from 'zlib';
import { inspect } from 'util';

import vfs from 'vinyl-fs';
import { promisify } from 'bluebird';
import mkdirpCb from 'mkdirp';
import del from 'del';
import deleteEmpty from 'delete-empty';
import { createPromiseFromStreams, createMapStream } from '../../../legacy/utils';

import tar from 'tar';

const mkdirpAsync = promisify(mkdirpCb);
const writeFileAsync = promisify(fs.writeFile);
const readFileAsync = promisify(fs.readFile);
const readdirAsync = promisify(fs.readdir);
const utimesAsync = promisify(fs.utimes);

export function assertAbsolute(path) {
  if (!isAbsolute(path)) {
    throw new TypeError(
      'Please use absolute paths to keep things explicit. You probably want to use `build.resolvePath()` or `config.resolveFromRepo()`.'
    );
  }
}

function longInspect(value) {
  return inspect(value, {
var seneca = require('seneca')();
var promise = require('bluebird');

seneca.client({ port:10101, pin:'role:database' })
      .client({ port:10102, pin:'role:auth' })
      .client({ port:10103, pin:'role:sms' });

seneca.actAsync = promise.promisify(seneca.act, {
    multiArgs: false,
    context: seneca
});

module.exports = seneca;
Exemple #14
0
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

const BBPromise = require('bluebird');
const colors = require('ansi-colors');
const gulp = require('gulp-help')(require('gulp'));
const log = require('fancy-log');
const request = BBPromise.promisify(require('request'));
const srcGlobs = require('../config').presubmitGlobs;
const through2 = require('through2');

const GITHUB_ACCESS_TOKEN = process.env.GITHUB_ACCESS_TOKEN;

/** @type {!Object<string, !Promise<number>>} */
const issueCache = Object.create(null);


/**
 * Test if a file's contents contains closed TODOs.
 *
 * @param {!File} file file is a vinyl file object
 * @return {Promise<number>} Number of found closed TODOs.
 */
const port = process.env.PORT || '8080';

var apiURL = 'http://' + host + ':' + port + '/' + 'api/0/waypoints';

var mongoLocalURL = "mongodb://localhost/unacademic_api";
var mongoLabURL = "mongodb://*****:*****@ds029051.mongolab.com:29051/unacademic_api";

var mongoURL = mongoLabURL;

function resetWaypoints() {
    return new BPromise(function(resolve, reject) {
        mongoose.connection.collections['waypoints'].drop(resolve, reject);
    });
}

var connectDB = BPromise.promisify(mongoose.connect, mongoose);

var con = mongoose.connection;

con.once('open', function() {
	console.log('connected to mongodb successfully');
});

con.once('error', function() {
	console.log('MongoLab connection error');
	console.error.bind(console, 'connection error:');
});


app.use(require('../api'));
Exemple #16
0
 .then(function(){
     return P.promisify(env.flushdb);
 });
Exemple #17
0
var _ = require('lodash');
var fs = require('fs-extra');
var Promise = require('bluebird');
var readFile = Promise.promisify(fs.readFile);
var writeFile = require('./writeFile');

/**
 * Copies a file to the target directory
 *
 * @param options
 * @returns Promise
 */
var CopyFileWriter = function(options) {
  this.options = options || {};
};

_.extend(CopyFileWriter.prototype, {

  write: function(source, target, options) {
    return readFile(source).then(function(data) {
      return writeFile(target, data, options);
    });
  }

});

module.exports = CopyFileWriter;
Exemple #18
0
 return Promise.promisify(fs.copy)(image.path, savedpath).then(function(){
     return Promise.promisify(fs.readFile)(savedpath);
 }).then(function(data){
var helper      = require("./test-helper");
var Promise     = require("bluebird");
var _           = require("lodash");

var request     = Promise.promisify(require('request'));
var assert      = require('assert');
var sinon       = require('sinon');

var PaysharesdStubby  = require('./paysharesd-stubby');
var Payments        = require('../lib/payments');
var MockSigner      = require('./mock-signer');
var MockSubmitter   = require('./mock-submitter');
var Database     = require('../lib/database');

var sandbox = sinon.sandbox.create();

// The payments object we'll be testing
var payments;

describe("payments tests", function () {
    var database;
    var signer;
    var signerMock;
    var submitter;
    var submitterMock;
    var networkMock;
    var networkStubby;
    var databaseMock;
    var paymentsMock;
    beforeEach(function () {
        signer = new MockSigner();
Exemple #20
0
 }).then(function() {
     // Remove temp file
     return Promise.promisify(fs.unlink)(savedpath);
 }).then(function () {
Exemple #21
0
 .then(function () {
     return Promise.promisify(utils.zipFolder)(themePath, zipPath);
 })
Exemple #22
0
'use strict'

const BB = require('bluebird')

const fetch = require('./fetch')
const manifest = require('./manifest')
const optCheck = require('../../util/opt-check')
const PassThrough = require('stream').PassThrough
const pickRegistry = require('./pick-registry')
const pipe = BB.promisify(require('mississippi').pipe)
const ssri = require('ssri')
const url = require('url')

module.exports = tarball
function tarball (spec, opts) {
  opts = optCheck(opts)
  const stream = new PassThrough()
  manifest(spec, opts).then(manifest => {
    stream.emit('manifest', manifest)
    return pipe(
      fromManifest(manifest, spec, opts).on(
        'integrity', i => stream.emit('integrity', i)
      ),
      stream
    )
  }).catch(err => stream.emit('error', err))
  return stream
}

module.exports.fromManifest = fromManifest
function fromManifest (manifest, spec, opts) {
    function defineMeasurementsSchema() {
        let measurements = schema.defineSchema('Measurements', {
            name: {
                type: 'string',
                nullable: false
            },

            attribute: {
                type: 'string',
                nullable: false
            },

            otype: {
                type: 'string',
                nullable: false,
                isValidPropertyType: true
            },

            value: {
                nullable: false
            },

            units: {
                type: 'string',
                nullable: false,
                isValidUnit: true
            },

            project_id: {
                type: 'string',
                nullable: true
            },

            sample_id: {
                type: 'string',
                nullable: false,
                mustExistInProject: 'samples'
            },

            attribute_id: {
                oneOf: 'attribute_id:attribute_set_id',
                mustBeForSample: 'attribute'
            },

            attribute_set_id: {
                oneOf: 'attribute_id:attribute_set_id',
                mustBeForSample: 'attributeset'
            },

            from_measurements: {
                type: 'array',
                nullable: true,
                mustBeValidMeasurements: true
            },

            from_file: {
                nullable: true,

                file_id: {
                    type: 'string',
                    nullable: false,
                    mustExistInProject: 'datafiles'
                },

                grid: {
                    nullable: true,

                    row_start: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 0
                    },

                    row_end: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 'row_start'
                    },

                    column_start: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 0
                    },

                    column_end: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 'column_start'
                    }
                },

                offset: {
                    nullable: true,

                    start: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 0
                    },

                    end: {
                        type: 'number',
                        nullable: false,
                        gtOrEq: 'start'
                    }
                }
            }
        });
        measurements.validateAsync = promise.promisify(measurements.validate);
        return measurements;
    }
Exemple #24
0
// Deploy cesium to s3
function deployCesium(bucketName, uploadDirectory, cacheControl, done) {
    var readFile = Promise.promisify(fs.readFile);
    var gzip = Promise.promisify(zlib.gzip);
    var getCredentials = Promise.promisify(aws.config.getCredentials, {context: aws.config});
    var concurrencyLimit = 2000;

    var s3 = new Promise.promisifyAll(new aws.S3({
        maxRetries : 10,
        retryDelayOptions : {
            base : 500
        }
    }));

    var existingBlobs = [];
    var totalFiles = 0;
    var uploaded = 0;
    var skipped = 0;
    var errors = [];

    return getCredentials()
    .then(function() {
        var prefix = uploadDirectory + '/';
        return listAll(s3, bucketName, prefix, existingBlobs)
        .then(function() {
            return globby([
                'Apps/**',
                'Build/**',
                'Source/**',
                'Specs/**',
                'ThirdParty/**',
                '*.md',
                'favicon.ico',
                'gulpfile.js',
                'index.html',
                'package.json',
                'server.js',
                'web.config',
                '*.zip',
                '*.tgz'
            ], {
                dot : true, // include hidden files
                nodir : true // only directory files
            });
        })
        .then(function(files) {
            return Promise.map(files, function(file) {
                var blobName = uploadDirectory + '/' + file;
                var mimeLookup = getMimeType(blobName);
                var contentType = mimeLookup.type;
                var compress = mimeLookup.compress;
                var contentEncoding = compress ? 'gzip' : undefined;
                var etag;

                totalFiles++;

                return readFile(file)
                .then(function(content) {
                    return compress ? gzip(content) : content;
                })
                .then(function(content) {
                    // compute hash and etag
                    var hash = crypto.createHash('md5').update(content).digest('hex');
                    etag = crypto.createHash('md5').update(content).digest('base64');

                    var index = existingBlobs.indexOf(blobName);
                    if (index <= -1) {
                        return content;
                    }

                    // remove files as we find them on disk
                    existingBlobs.splice(index, 1);

                    // get file info
                    return s3.headObjectAsync({
                        Bucket : bucketName,
                        Key : blobName
                    })
                    .then(function(data) {
                        if (data.ETag !== ('"' + hash + '"') ||
                            data.CacheControl !== cacheControl ||
                            data.ContentType !== contentType ||
                            data.ContentEncoding !== contentEncoding) {
                            return content;
                        }

                        // We don't need to upload this file again
                        skipped++;
                        return undefined;
                    })
                    .catch(function(error) {
                        errors.push(error);
                    });
                })
                .then(function(content) {
                    if (!content) {
                        return;
                    }

                    console.log('Uploading ' + blobName + '...');
                    var params = {
                        Bucket : bucketName,
                        Key : blobName,
                        Body : content,
                        ContentMD5 : etag,
                        ContentType : contentType,
                        ContentEncoding : contentEncoding,
                        CacheControl : cacheControl
                    };

                    return s3.putObjectAsync(params).then(function() {
                        uploaded++;
                    })
                    .catch(function(error) {
                        errors.push(error);
                    });
                });
            }, {concurrency : concurrencyLimit});
        })
        .then(function() {
            console.log('Skipped ' + skipped + ' files and successfully uploaded ' + uploaded + ' files of ' + (totalFiles - skipped) + ' files.');
            if (existingBlobs.length === 0) {
                return;
            }

            var objectToDelete = [];
            existingBlobs.forEach(function(file) {
                //Don't delete generate zip files.
                if (!/\.(zip|tgz)$/.test(file)) {
                    objectToDelete.push({Key : file});
                }
            });

            if (objectToDelete.length > 0) {
                console.log('Cleaning up old files...');
                return s3.deleteObjectsAsync({
                                                 Bucket : bucketName,
                                                 Delete : {
                                                     Objects : objectToDelete
                                                 }
                                             })
                    .then(function() {
                        console.log('Cleaned ' + existingBlobs.length + ' files.');
                    });
            }
        })
        .catch(function(error) {
            errors.push(error);
        })
        .then(function() {
            if (errors.length === 0) {
                done();
                return;
            }

            console.log('Errors: ');
            errors.map(function(e) {
                console.log(e);
            });
            done(1);
        });
    })
    .catch(function(error) {
        console.log('Error: Could not load S3 credentials.');
        done();
    });
}
Exemple #25
0
'use strict'

const BB = require('bluebird')

const exec = require('child_process').execFile
const spawn = require('./spawn')
const npm = require('../npm.js')
const which = require('which')
const git = npm.config.get('git')
const assert = require('assert')
const log = require('npmlog')
const noProgressTillDone = require('./no-progress-while-running.js').tillDone

exports.spawn = spawnGit
exports.exec = BB.promisify(execGit)
exports.chainableExec = chainableExec
exports.whichAndExec = whichAndExec

function prefixGitArgs () {
  return process.platform === 'win32' ? ['-c', 'core.longpaths=true'] : []
}

function execGit (args, options, cb) {
  log.info('git', args)
  const fullArgs = prefixGitArgs().concat(args || [])
  return exec(git, fullArgs, options, noProgressTillDone(cb))
}

function spawnGit (args, options) {
  log.info('git', args)
  return spawn(git, prefixGitArgs().concat(args || []), options)
Exemple #26
0
gulp.task('sortRequires', function() {
    var noModulesRegex = /[\s\S]*?define\(function\(\)/;
    var requiresRegex = /([\s\S]*?(define|defineSuite|require)\((?:{[\s\S]*}, )?\[)([\S\s]*?)]([\s\S]*?function\s*)\(([\S\s]*?)\) {([\s\S]*)/;
    var splitRegex = /,\s*/;

    var fsReadFile = Promise.promisify(fs.readFile);
    var fsWriteFile = Promise.promisify(fs.writeFile);

    var files = globby.sync(filesToSortRequires);
    return Promise.map(files, function(file) {

        return fsReadFile(file).then(function(contents) {

            var result = requiresRegex.exec(contents);

            if (result === null) {
                if (!noModulesRegex.test(contents)) {
                    console.log(file + ' does not have the expected syntax.');
                }
                return;
            }

            // In specs, the first require is significant,
            // unless the spec is given an explicit name.
            var preserveFirst = false;
            if (result[2] === 'defineSuite' && result[4] === ', function') {
                preserveFirst = true;
            }

            var names = result[3].split(splitRegex);
            if (names.length === 1 && names[0].trim() === '') {
                names.length = 0;
            }

            var i;
            for (i = 0; i < names.length; ++i) {
                if (names[i].indexOf('//') >= 0 || names[i].indexOf('/*') >= 0) {
                    console.log(file + ' contains comments in the require list.  Skipping so nothing gets broken.');
                    return;
                }
            }

            var identifiers = result[5].split(splitRegex);
            if (identifiers.length === 1 && identifiers[0].trim() === '') {
                identifiers.length = 0;
            }

            for (i = 0; i < identifiers.length; ++i) {
                if (identifiers[i].indexOf('//') >= 0 || identifiers[i].indexOf('/*') >= 0) {
                    console.log(file + ' contains comments in the require list.  Skipping so nothing gets broken.');
                    return;
                }
            }

            var requires = [];

            for (i = preserveFirst ? 1 : 0; i < names.length && i < identifiers.length; ++i) {
                requires.push({
                    name : names[i].trim(),
                    identifier : identifiers[i].trim()
                });
            }

            requires.sort(function(a, b) {
                var aName = a.name.toLowerCase();
                var bName = b.name.toLowerCase();
                if (aName < bName) {
                    return -1;
                } else if (aName > bName) {
                    return 1;
                } else {
                    return 0;
                }
            });

            if (preserveFirst) {
                requires.splice(0, 0, {
                    name : names[0].trim(),
                    identifier : identifiers[0].trim()
                });
            }

            // Convert back to separate lists for the names and identifiers, and add
            // any additional names or identifiers that don't have a corresponding pair.
            var sortedNames = requires.map(function(item) {
                return item.name;
            });
            for (i = sortedNames.length; i < names.length; ++i) {
                sortedNames.push(names[i].trim());
            }

            var sortedIdentifiers = requires.map(function(item) {
                return item.identifier;
            });
            for (i = sortedIdentifiers.length; i < identifiers.length; ++i) {
                sortedIdentifiers.push(identifiers[i].trim());
            }

            var outputNames = ']';
            if (sortedNames.length > 0) {
                outputNames = os.EOL + '        ' +
                              sortedNames.join(',' + os.EOL + '        ') +
                              os.EOL + '    ]';
            }

            var outputIdentifiers = '(';
            if (sortedIdentifiers.length > 0) {
                outputIdentifiers = '(' + os.EOL + '        ' +
                                    sortedIdentifiers.join(',' + os.EOL + '        ');
            }

            contents = result[1] +
                       outputNames +
                       result[4].replace(/^[,\s]+/, ', ').trim() +
                       outputIdentifiers +
                       ') {' +
                       result[6];

            return fsWriteFile(file, contents);
        });
    });
});
Exemple #27
0
};

function generateAssetModule_DEPRECATED(module) {
  var code = 'module.exports = ' + JSON.stringify({
    uri: module.id.replace(/^[^!]+!/, ''),
    isStatic: true,
  }) + ';';

  return {
    code: code,
    sourceCode: code,
    sourcePath: module.path,
  };
}

var sizeOf = Promise.promisify(imageSize);

function generateAssetModule(module, relPath) {
  return sizeOf(module.path).then(function(dimensions) {
    var img = {
      isStatic: true,
      path: module.path, //TODO(amasad): this should be path inside tar file.
      uri: relPath,
      width: dimensions.width,
      height: dimensions.height,
    };

    var code = 'module.exports = ' + JSON.stringify(img) + ';';

    return {
      code: code,
Exemple #28
0
const AWS = require('aws-sdk')
const fs = require('fs')
const mime = require('mime')
import { promisify } from 'bluebird'
import { walk } from 'walk'
import { commitTag } from './util'

var bucket

const readFile = promisify(fs.readFile)

const upload = (path, destPath, put) => {
  return readFile(path)
  .then(body => put({
    Key: destPath,
    Body: body,
    ContentType: mime.lookup(path),
    Bucket: bucket,
    ACL: 'public-read'
  }))
}

export default function () {
  // deferring assignment because env vars are not yet assigned
  // when the file is first loaded
  bucket = process.env.AWS_S3_BUCKET

  var s3 = new AWS.S3()
  let head = promisify(s3.headObject, {context: s3})
  let put = promisify(s3.putObject, {context: s3})
const Promise = require('bluebird');
const request = require('request');
const get = Promise.promisify(request.get);
const logger = require('./logger');
const { extend, isPlainObject } = require('./utils');

function getMimeType (contentType) {
	return contentType ? contentType.split(';')[0] : null;
}

function defaultResponseHandler ({response}) {
	return Promise.resolve(response.body);
}

function transformResult (result) {
	switch (true) {
		case typeof result === 'string':
			return {
				body: result,
				metadata: null
			};
		case isPlainObject(result):
			return {
				body: result.body,
				metadata: result.metadata || null
			};
		case result === null:
			return null;
		default:
			throw new Error('Wrong response handler result. Expected string or object, but received ' + typeof result);
	}
Exemple #30
0
 .map(function(i){
   return Promise.promisify(glob)(i);
 })