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

feat: add 'watch' mode #138

Merged
merged 2 commits into from Jun 13, 2018
Merged

feat: add 'watch' mode #138

merged 2 commits into from Jun 13, 2018

Conversation

eGavr
Copy link
Contributor

@eGavr eGavr commented Jun 5, 2018

@eGavr eGavr force-pushed the feat/watcher-mode branch 2 times, most recently from 3f3bbb2 to b85f4a4 Compare June 5, 2018 13:54
Copy link

@j0tunn j0tunn left a comment

Choose a reason for hiding this comment

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

Над тестами бы подумать, конечно. Но в целом ок

const lastArg = args[args.length - 1];

if (args.length > 1 && isPlainObject(lastArg)) {
Object.assign({}, lastArg, options);
Copy link

Choose a reason for hiding this comment

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

и с полученным в итоге объектом ты ничего не делаешь

package.json Outdated
"cp-file": "5.0.0",
"glob": "7.1.2",
"glob-stream": "6.1.0",
"graceful-fs": "4.1.11",
"lodash.isplainobject": "^4.0.6",
Copy link

Choose a reason for hiding this comment

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

нафиг оно нужно, подключай весь lodash и не парься. Это же не клиентский код

const micromatchOptions = { dot: options.dot };
const cwd = this._cwd = options.cwd;

const chokidar = proxyquire('chokidar', {
Copy link

Choose a reason for hiding this comment

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

оставь коммент зачем мы его так странно подключаем

/**
* Must be implemented in a child class of stream.Readable
*/
// eslint-disable-next-line class-methods-use-this
Copy link

Choose a reason for hiding this comment

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

это же отключает правило про пустую строчку сразу после объявления метода? А зачем там пустая строка? Почему нельзя написать:

_read() {}

_read() {
}

const cwd = this._cwd = options.cwd;

const chokidar = proxyquire('chokidar', {
anymatch: proxyquire('anymatch', { micromatch: micromatch.bindOptions(micromatchOptions) })
Copy link

Choose a reason for hiding this comment

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

разнеси по строчкам, ну сложно же читается

README.md Outdated

Tartifacts will work in an observe mode which means that all files and directories will be added to a destination directory or archive as soon as they appear on a file system.

Note: in order to stop tartifacts `SIGTERM` signal should be sent
Copy link

Choose a reason for hiding this comment

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

здесь нужно написать, что процесс будет завершен корректно (с закрытием всех файловых дескрипторов), но на это нужно время

watcher.on(WatcherEvents.add, path => this._push(path));
options.nodir || watcher.on(WatcherEvents.addDir, path => this._push(path));

process.on(SIGINT, () => {
Copy link

Choose a reason for hiding this comment

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

SIGTERM тоже нужно обрабатывать. И, да, при таком переопределении теряется стандартная логика про exitCode

@eGavr eGavr force-pushed the feat/watcher-mode branch 5 times, most recently from 81f3283 to e644d34 Compare June 5, 2018 14:51
Copy link
Collaborator

@blond blond left a comment

Choose a reason for hiding this comment

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

Спасибо! В целом решение с Watch-стримом нравится.

Написал вопросы по конкретным кейсам.


// 'chokidar' does not provide the ability to pass 'dot' option to 'micromatch' directly,
// so we use 'proxyquire' to monkey patch 'micromatch' in order to call all its methods with this option
const chokidar = proxyquire('chokidar', {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Давай вынесем это в отдельный модуль (файл), чтобы в стриме просто его рекваерить.

Тогда на эту логику можно будет написать тест: вызывается micromatch с необходимыми опциями.

* @param {object} options
* @returns {function}
*/
exports.bindOptions = (options) => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Добавь, пожалуйста, тесты на этот модуль и напиши пару слов зачем он нужен.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

А я в месте использования написал, что там за магия происходит

watcher.on(WATCHER_EVENTS.add, path => this._push(path));
options.nodir || watcher.on(WATCHER_EVENTS.addDir, path => this._push(path));

SIGNALS.forEach((signal) => process.on(signal, () => this._close(watcher)));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Как это будет работать в CLI?

Нажал я такой cltr + c, что должно произойти?) Что я увижу как пользователь?

});

const watcher = chokidar.watch(patterns, { cwd, followSymlinks: options.follow });
watcher.on(WATCHER_EVENTS.add, path => this._push(path));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Я правильно понимаю, что тут и файлы и симлинки?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Что с событиями удаления (unlink и unlinkDir)?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Если сработает change, что в итоге попадёт в архив? Первая версия этого файла? Файл вообще не попадёт?

Вот кейс который меня интересует. В ENB «таргеты» по смыслу являются кэшами.

Т.е. во время сборки не только добавляются новые файлы, но и старые могут быть изменены, а так же не изменены (если mtime подходит). Но эти файлы всё равно должны попасть в архив.

Как это будет работать с текущим решением?

Copy link

@j0tunn j0tunn left a comment

Choose a reason for hiding this comment

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

Ну и jsdoc ты зря повыгашивал, наверное


module.exports = class Artifact {
static create(destDir, streams) {
return new Artifact(destDir, streams);
Copy link

Choose a reason for hiding this comment

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

...args


write() {
return makeDir(this._destDir, { fs })
.then(() => {
Copy link

Choose a reason for hiding this comment

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

async await?

const TarStream = streams.TarStream;
const CopyStream = streams.CopyStream;
const TransformStream = streams.TransformStream;
const WatchStream = streams.WatchStream;
Copy link

Choose a reason for hiding this comment

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

desctructuring

};
const writeStreamOptions = {emptyFiles: options.emptyFiles, emptyDirs: options.emptyDirs};
const gzipOptions = {gzip: options.gzip, gzipOptions: options.gzipOptions};

Copy link

Choose a reason for hiding this comment

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

лишняя пустая строка. А тут линтер не настроен?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

он настроен, но не ругается

write() {
return makeDir(this._destDir, { fs })
.then(() => {
return new Promise((resolve, reject) => {
Copy link

Choose a reason for hiding this comment

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

этот промис нужно создавать до makeDir

@eGavr
Copy link
Contributor Author

eGavr commented Jun 8, 2018

Тестов новых пока не писал

После рефакторинга все старые тесты проходят (я сами тесты не выгашивал, а просто подправил род новую архитектуру)

@eGavr eGavr force-pushed the feat/watcher-mode branch 2 times, most recently from c88f7fb to 3f828c0 Compare June 9, 2018 12:43
Copy link
Collaborator

@blond blond left a comment

Choose a reason for hiding this comment

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

Пару замечаний по документации.

Тестов конечно не хватает :)

Давай после влития pr выпустим препатч и проверим с помощью dobby, что в проектах всё продолжает работать как и раньше.

README.md Outdated

Tartifacts will work in an observe mode which means that all files and directories will be added to a destination directory or archive as soon as they appear on a file system.

Note: in order to stop tartifacts `SIGTERM` or `SIGINT` signal should be sent; these signals stop observing of a file system, but do not abort the process, so all file descriptors will be closed correctly and all tasks will be finished after a while
Copy link
Collaborator

Choose a reason for hiding this comment

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

Поправь документацию, сейчас нужно вызывать метод, а не отправить сигналы.


process.on('SIGTERM', () => tartifacts.closeArtifacts());

tartifacts.writeArtifacts({
Copy link
Collaborator

Choose a reason for hiding this comment

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

Надо в API документации добавить про класс Tartifacts и его методы.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

добавил

@eGavr eGavr force-pushed the feat/watcher-mode branch 2 times, most recently from 18b7b72 to 1a9355e Compare June 13, 2018 14:05
@eGavr
Copy link
Contributor Author

eGavr commented Jun 13, 2018

Давай после влития pr выпустим препатч и проверим с помощью dobby, что в проектах всё продолжает работать как и раньше.

проверил

Тестов конечно не хватает :)

постараюсь на новую функциональность дописать в свободное время

@eGavr eGavr merged commit 12d7249 into yandex:master Jun 13, 2018
@eGavr eGavr deleted the feat/watcher-mode branch June 13, 2018 16:25
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

3 participants