Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#425] new tech "write-file" #426

Merged
merged 1 commit into from Feb 22, 2016
Merged

Conversation

pavelpower
Copy link
Contributor

No description provided.

@blond blond added the review label Jan 19, 2016
@pavelpower pavelpower closed this Jan 19, 2016
@pavelpower pavelpower reopened this Jan 19, 2016
@blond blond added review and removed review labels Jan 19, 2016
@pavelpower
Copy link
Contributor Author

@blond посмотри верно ли сделан тест?

.then(function () {

// При оспользовании "mockFS.fs().statSync" выскакивает ошибка
// mockFS.fs().statSync('bundle/bundle.txt').isFile().should.be.ok;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я к сожалению так и не разобрался почему mockFS.fs() фейлится но основная проблема как мне кажется в другом. MockFS манки патчит родной fs модуль ( для этого мы вызываем mockFs() и mockFs.restore() - чтобы добавить/удалить манки патчинг )

Заменив

mockFS.fs().statSync('bundle/bundle.txt').isFile().should.be.ok;

на

require('fs').statSync('bundle/bundle.txt').isFile().should.be.ok;

Все начинает работать как нужно

Также можно убедиться в том что нужно использовать fs модуль посмотрев тесты самого mockFs
https://github.com/tschaub/mock-fs/blob/master/test/integration/filecount.js#L3

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AiBoy спасибо за ревью! Действительно, так тест проходит!

enb = require('../lib/api'),
vfs = enb.asyncFs;

module.exports = inherit(enb.BaseTech, {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно проще переписать технологию с помощью build-flow.

@blond
Copy link
Member

blond commented Jan 28, 2016

@pavelpower написал замечания. И ещё надо добавить документацию в REAMDE.md.

@blond blond added ready and removed review labels Jan 28, 2016
@pavelpower
Copy link
Contributor Author

@blond спасибо, поправлю

@pavelpower
Copy link
Contributor Author

@blond попробовал сделать так

var enb = require('../lib/api'),
    vfs = enb.asyncFs;

module.exports = enb.buildFlow.create()
    .name('write-file')
    .target('target', '?.target')
    .defineRequiredOption('target')
    .defineRequiredOption('content')
    .defineOption('fileOptions', { encoding: 'utf8' })
    .builder(function () {
        var node = this.node,
            target = node.unmaskTargetName(this._target),
            filename = node.resolvePath(target);

        return vfs.write(filename, this._content, this._fileOptions)
            .then(function () {
                node.resolveTarget(target);
            }, function () {
                node.rejectTarget(target, new Error('file not write: ' + filename));
            });
    })
    .createTech();

Но возникла проблема в том, что такая реализация вызывает 'vfs.write' много раз.

Сделал тестовый проектик, для того, чтобы понять почему не проходит тест на проверку контента.

.enb/make.js

module.exports = function(config) {
    // Настраиваем сборку бандла
    config.node('bundle', function(nodeConfig) {
        // Декларируем модули технологий,
        // которые могут участвовать в сборке таргетов.

        nodeConfig.addTechs([
            [require('enb/techs/write-file'), {
                content: 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
                target: '?.png',
                fileOptions: {
                    encoding: 'base64'
                }
            }],
            [require('enb/techs/write-file'), {
                content: '## Test \n this a test text',
                target: '?.md',
                fileOptions: {
                    encoding: 'utf8'
                }
            }]
        ]);

        // Объявляем таргеты, которые хотим собрать.
        nodeConfig.addTargets(['?.png', '?.md']);
    });
};

Оказалось, что в целевых файлах undefined.

В рамках проекта поставил console.log(args) вот сюда: https://github.com/dfilatov/vow-fs/blob/master/lib/fs.js#L28

Вот, что получил:

 enb make

[ ‘~/Projects/opensource/test-enb/.enb/tmp',
  undefined,
  [Function] ]
[ ‘~/Projects/opensource/test-enb/.enb/tmp',
  [Function] ]
02:54:06.249 - build started
[ ‘~/Projects/opensource/test-enb/bundle',
  undefined,
  [Function] ]
[ ‘~/Projects/opensource/test-enb/bundle',
  [Function] ]
[ ‘~/Projects/opensource/test-enb/bundle/bundle.png',
  'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==',
  { encoding: 'base64' },
  [Function] ]
[ ‘~/Projects/opensource/test-enb/bundle/bundle.md',
  '## Test \n this a test text',
  { encoding: 'utf8' },
  [Function] ]
02:54:06.276 - [rebuild] [bundle/bundle.png] write-file
02:54:06.276 - [rebuild] [bundle/bundle.md] write-file
[ ‘~/Projects/opensource/test-enb/bundle/bundle.png',
  'undefined',
  'utf8',
  [Function] ]
[ ‘~/Projects/opensource/test-enb/bundle/bundle.md',
  'undefined',
  'utf8',
  [Function] ]

Заметь сколько раз вызывается плагин!

Может вариант использования enb.buildFlow не очень хорошая идея?

Или ее надо готовить иначе?

@pavelpower
Copy link
Contributor Author

Сделал трейс вызова writeFile:

Trace: [ '~/Projects/opensource/test-enb/bundle/bundle.md',
  '## Test \n this a test text',
  { encoding: 'utf8' },
  [Function] ]
    at Object.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:46:35
    at Object.vow.invoke (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:1050:20)
    at Object.Queue._runTask (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:204:27)
    at Object.Queue._run (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:186:18)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
03:00:16.378 - [rebuild] [bundle/bundle.md] write-file
Trace: [ '~/Projects/opensource/test-enb/bundle/bundle.md',
  'undefined',
  'utf8',
  [Function] ]
    at Object.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:46:35
    at Object.vow.invoke (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:1050:20)
    at Object.Queue._runTask (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:204:27)
    at Object.Queue._run (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:186:18)
    at processImmediate [as _immediateCallback] (timers.js:383:17)

@pavelpower
Copy link
Contributor Author

@blond кстати при текущей реализации тот же trace работает два раза для папок но один раз для файла.

Выглядит так:

> enb make

Trace: [ '~/Projects/opensource/test-enb/.enb/tmp',
  undefined,
  [Function] ]
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:316:24
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
Trace: [ '~/Projects/opensource/test-enb/.enb/tmp',
  [Function] ]
    at Object.stat (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at Object.module.exports.isDir (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:234:21)
    at onFailed (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:307:28)
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
03:19:37.083 - build started
Trace: [ '~/Projects/opensource/test-enb/bundle',
  undefined,
  [Function] ]
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:316:24
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
Trace: [ '~/Projects/opensource/test-enb/bundle',
  [Function] ]
    at Object.stat (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at Object.module.exports.isDir (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:234:21)
    at onFailed (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:307:28)
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
Trace: [ '~/Projects/opensource/test-enb/bundle/bundle.md',
  '## Test \n this a test text',
  { encoding: 'utf8' },
  [Function] ]
    at Object.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:46:35
    at Object.vow.invoke (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:1050:20)
    at Object.Queue._runTask (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:204:27)
    at Object.Queue._run (~/Projects/opensource/test-enb/node_modules/vow-queue/lib/queue.js:186:18)
    at processImmediate [as _immediateCallback] (timers.js:383:17)

@blond
Copy link
Member

blond commented Feb 4, 2016

Но возникла проблема в том, что такая реализация вызывает 'vfs.write' много раз.

Это логичное поведение для build-flow. builder записывает возвращаемый в него результат.

Чтобы переопределить это поведение, нужно задекларировать метод saver:

var enb = require('../lib/api'),
    vfs = enb.asyncFs;

module.exports = enb.buildFlow.create()
    .name('write-file')
    .target('target', '?.target')
    .defineRequiredOption('target')
    .defineRequiredOption('content')
    .defineOption('fileOptions', { encoding: 'utf8' })
    .builder(function () {
        return this._content;
    })
    .saver(function (filename, content) {
        return vfs.write(filename, content, this._fileOptions);
    })
    .createTech();

@blond
Copy link
Member

blond commented Feb 4, 2016

кстати при текущей реализации тот же trace работает два раза для папок но один раз для файла.

Это связано с технологией write-file или отдельно?

@pavelpower
Copy link
Contributor Author

@blond Решение с .saver сработало. все теперь работает как надо.

Это связано с технологией write-file или отдельно?

Похоже на то, что это связано не с технологией write-file.

Бандлы для нод так же создаются по два раза:

.enb/make.js:

module.exports = function(config) {
    // Настраиваем сборку бандла
    config.node('bundle', function(nodeConfig) {

    });
};

console:

> enb make

Trace: ----> [ '~/Projects/opensource/test-enb/.enb/tmp',
  undefined,
  [Function] ]
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:316:24
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
Trace: ----> [ '~/Projects/opensource/test-enb/.enb/tmp',
  [Function] ]
    at Object.stat (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at Object.module.exports.isDir (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:234:21)
    at onFailed (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:307:28)
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
01:04:53.166 - build started
Trace: ----> [ '~/Projects/opensource/test-enb/bundle',
  undefined,
  [Function] ]
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25
    at ~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:316:24
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)
Trace: ----> [ '~/Projects/opensource/test-enb/bundle',
  [Function] ]
    at Object.stat (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:28:25)
    at Object.module.exports.isDir (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:234:21)
    at onFailed (~/Projects/opensource/test-enb/node_modules/vow-fs/lib/fs.js:307:28)
    at Array.<anonymous> (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:712:56)
    at Immediate.callFns [as _onImmediate] (~/Projects/opensource/test-enb/node_modules/vow/lib/vow.js:23:35)
    at processImmediate [as _immediateCallback] (timers.js:383:17)

@blond blond added review and removed ready labels Feb 15, 2016
@blond
Copy link
Member

blond commented Feb 18, 2016

Бандлы для нод так же создаются по два раза:

Почему так мыслей нет, предлагаю поискать это отдельно. Например, может кто-то вызывает makePlatform.init 2 раза. Или проблема в projectConfig.

@pavelpower
Copy link
Contributor Author

@blond у меня предположение, что проблема в vow-fs. На самом деле в текущей версии тоже самое происходит.


bundle = new MockNode('bundle');
resolveSpy = sinon.spy(bundle, 'resolveTarget');
rejectSpy = sinon.spy(bundle, 'rejectTarget');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolveSpy и rejectSpy не нужены

@blond
Copy link
Member

blond commented Feb 18, 2016

Написал замечания по коду.

@blond
Copy link
Member

blond commented Feb 18, 2016

у меня предположение, что проблема в vow-fs. На самом деле в текущей версии тоже самое происходит.

@pavelpower, не очень понимаю как это связано =)

@tadatuta
Copy link
Member

Бандлы для нод так же создаются по два раза:
Почему так мыслей нет, предлагаю поискать это отдельно. Например, может кто-то вызывает makePlatform.init 2 раза. Или проблема в projectConfig.

Они всегда вызываются по 2 раза, воспроизводится давно и при любых вариациях конфига.
Почему — не знаю, но оно мне изрядно портило жизнь.

@blond
Copy link
Member

blond commented Feb 22, 2016

@pavelpower 👍

Соскваш коммиты и вливаем.

@pavelpower
Copy link
Contributor Author

:okay:

@pavelpower
Copy link
Contributor Author

@blond done

blond added a commit that referenced this pull request Feb 22, 2016
@blond blond merged commit 8394e12 into enb:master Feb 22, 2016
@blond
Copy link
Member

blond commented Feb 22, 2016

LGTM

@blond blond removed the review label Feb 22, 2016
@pavelpower
Copy link
Contributor Author

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants