Skip to content

Commit

Permalink
Review WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
tadatuta committed Feb 8, 2016
1 parent eb9720b commit 2e963de
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 51 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
"cheerio": "^0.19.0",
"debug": "^2.2.0",
"deep-diff": "^0.3.x",
"deep-extend": "^0.4.x",
"fs-extra": "^0.26.x",
"github": "^0.2.4",
"js2xmlparser": "^1.0.0",
Expand Down
60 changes: 22 additions & 38 deletions src/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import _ from 'lodash';
import deepDiff from 'deep-diff';
import deepExtend from 'deep-extend';

/**
* @desc Application model class
Expand Down Expand Up @@ -33,9 +32,9 @@ export default class Model {
* @returns {Object}
* @private
*/
static _generateUrlPageMap(arr) {
return arr.reduce((prev, item) => {
prev[item.url] = item;
static _generateUrlPageMap(pages) {
return pages.reduce((prev, page) => {
prev[page.url] = page;
return prev;
}, {});
}
Expand All @@ -45,9 +44,8 @@ export default class Model {
* @returns {Boolean}
*/
hasChanges() {
return this.getChanges().added.length > 0 ||
this.getChanges().modified.length > 0 ||
this.getChanges().removed.length > 0;
var changes = this.getChanges();
return changes.added.length || changes.modified.length || changes.removed.length;
}

/**
Expand All @@ -63,7 +61,7 @@ export default class Model {
* @param {Object} item
* @returns {Model}
*/
pushChangeAdd(item) {
pushChangeToAddedGroup(item) {
this.getChanges().added.push(item);
return this;
}
Expand All @@ -73,7 +71,7 @@ export default class Model {
* @param {Object} item
* @returns {Model}
*/
pushChangeModify(item) {
pushChangeToModifiedGroup(item) {
this.getChanges().modified.push(item);
return this;
}
Expand All @@ -83,7 +81,7 @@ export default class Model {
* @param {Object} item
* @returns {Model}
*/
pushChangeRemove(item) {
pushChangeToRemovedGroup(item) {
this.getChanges().removed.push(item);
return this;
}
Expand Down Expand Up @@ -119,31 +117,32 @@ export default class Model {
/*
Для массивов объектов из нового и старого файлов моделей
вызываем метод _generateUrlPageMap, который строит из данных массивов
объекты в которых ключами являются url страниц, а значениями сами объекты
объекты, в которых ключами являются url страниц, а значениями сами объекты
*/
const newModel = this.constructor._generateUrlPageMap(currentModel);
const oldModel = this.constructor._generateUrlPageMap(previousModel);
const generateUrlPageMap = this.constructor._generateUrlPageMap;
const newModel = generateUrlPageMap(currentModel);
const oldModel = generateUrlPageMap(previousModel);

const newPages = _.keys(newModel); // получить все url из новой модели
let oldPages = _.keys(oldModel); // получить все url из старой модели

/*
Добавленные страницы можно получить вычислив разницу между массивом url из новой и старой моделей
Для удаленных страницы наоборот надо вычислить разницу между массивом url из старой и новой моделей
Для удаленных страниц наоборот надо вычислить разницу между массивом url из старой и новой моделей
*/
const addedPages = _.difference(newPages, oldPages);
const removedPages = _.difference(oldPages, newPages);

removedPages.forEach(url => {
this.pushChangeRemove({type: 'page', url});
this.pushChangeToRemovedGroup({type: 'page', url});
});

// отбрасываем удаленные страницы
oldPages = _.difference(oldPages, removedPages);

/*
страницы в старой модели делятся на 2 группы:
1. Страницы мета-информация (набор полей в модели) для которых была изменена
1. Страницы, мета-информация (набор полей в модели) для которых была изменена
2. Страницы, которые остались неизменными
Соответственно вычисляя глубокий diff делим старые страницы на 2 таких группы
*/
Expand All @@ -159,7 +158,7 @@ export default class Model {
// add new pages
this.setPages(
this.getPages().concat(addedPages.map(url => {
this.pushChangeAdd({type: 'page', url});
this.pushChangeToAddedGroup({type: 'page', url});
return newModel[url];
}))
);
Expand All @@ -172,14 +171,14 @@ export default class Model {
}))
);

// Добавляем измененные страницы, предварительно внедряя изменения которые
// пришли и новой модели
// Добавляем измененные страницы, предварительно внедряя изменения, которые
// пришли, и новой модели
// merge modifications
// add modified pages
this.setPages(
this.getPages().concat(modifiedPages.map(url => {
this.pushChangeModify({type: 'page', url});
return deepExtend(oldModel[url], newModel[url]);
this.pushChangeToModifiedGroup({type: 'page', url});
return _.merge(oldModel[url], newModel[url]);
}, this))
);
return this;
Expand All @@ -202,29 +201,14 @@ export default class Model {
* Для остальных полей нужно провести проверку и выставить значения по умолчанию
*
*/
page.url = page.url + (_.endsWith(page.url, '/') ? '' : '/');

page.aliases = page.aliases || []; // массив алиасов
page.view = page.view || 'post'; // поле представления страницы
page.published = !!page.published;
page.aliases || (page.aliases = []); // массив алиасов
page.published = typeof page.published === 'undefined' ? true : !!page.published;

if(!page.title) {
page.published = false;
}
return page;
};

this.setPages(this.getPages().map(normalizePage));
return this;
}

/**
* Returns pages with anyone language version satisfy getCriteria function criteria
* @param {Function} criteria function
* @returns {Array} filtered array of pages
* @public
*/
getPagesByCriteria(criteria) {
return this.getPages().filter(criteria);
}
}
2 changes: 1 addition & 1 deletion src/tasks/core/merge-models.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default function mergeModels(model, options = {}) {
return function() {
return Q.all([
baseUtil.readFileFromCache('model.json', []),
baseUtil.readJSONFile(options.modelPath, null)
baseUtil.readJSONFile(options.modelPath)
])
.spread(model.merge.bind(model))
.then(logModelChanges)
Expand Down
8 changes: 4 additions & 4 deletions src/tasks/docs/load-from-file.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,23 +47,23 @@ export default function loadSourcesFromLocal(model) {
const fileName = path.basename(filePath); // имя файла (с расширением)
const fileExt = path.extname(fileName); // расширение файла

const localFilePath = path.resolve(filePath);
const absFilePath = path.resolve(filePath);
const cacheFilePath = path.join(page.url, ('index' + fileExt));

const onAddedDocument = (promise) => {
debug('Doc added: %s %s', page.url, page.title);
model.pushChangeAdd({type: 'doc', url: page.url, title: page.title});
model.pushChangeToAddedGroup({type: 'doc', url: page.url, title: page.title});
return baseUtil.writeFileToCache(cacheFilePath, promise.value);
};
const onModifiedDocument = (promise) => {
debug('Doc modified: %s %s', page.url, page.title);
model.pushChangeModify({type: 'doc', url: page.url, title: page.title});
model.pushChangeToModifiedGroup({type: 'doc', url: page.url, title: page.title});
return baseUtil.writeFileToCache(cacheFilePath, promise.value);
};

return Q.allSettled([
baseUtil.readFileFromCache(cacheFilePath),
baseUtil.readFile(localFilePath, null)
baseUtil.readFile(absFilePath)
]).spread((cache, local) => {
if(local.state === 'rejected') {
return Q.reject(local);
Expand Down
6 changes: 3 additions & 3 deletions src/tasks/meta/tags.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export default function generateTagPages(model, options = {}) {
}

/**
* Generates model pages for each of tag
* Generates model pages for each tag
* @param {Model} model - application model instance
* @param {String[]} tags - array of tags
* @returns {Object[]}
Expand Down Expand Up @@ -105,8 +105,8 @@ export default function generateTagPages(model, options = {}) {
* @returns {Object}
*/
function generateTagPagesMap(tagPages) {
return tagPages.reduce((prev, item) => {
prev[item.title] = _.pick(item, ['url', 'title']);
return tagPages.reduce((prev, tagPage) => {
prev[tagPage.title] = _.pick(tagPage, ['url', 'title']);
return prev;
}, {});
}
Expand Down
2 changes: 1 addition & 1 deletion src/tasks/override/override-docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export default function overrideDocLinks(model) {
*/
function findImageSourceReplacement(imgSrc, page) {
if(!imgSrc) {
return imgSrc;
return;
}

const url = Url.parse(imgSrc);
Expand Down
6 changes: 3 additions & 3 deletions src/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ export function readJSONFile(filePath, fallbackValue) {
*/
export function readFileFromCache(filePath, fallbackValue) {
debug(`read file from cache: ${filePath}`);
return (path.extname(filePath) === '.json' ? readJSONFile : readFile)
.call(null, path.join(getCacheFolder(), filePath), fallbackValue);
return (path.extname(filePath) === '.json' ?
readJSONFile : readFile)(path.join(getCacheFolder(), filePath), fallbackValue);
}

/**
Expand Down Expand Up @@ -130,7 +130,7 @@ export function processPagesAsync(model, criteria, processFunc, portionSize = 5)
criteria = criteria || (() => true);

return _(criteria)
.thru(model.getPagesByCriteria.bind(model))
.thru(model.getPages().filter)
.chunk(portionSize)
.reduce((prev, portion, index) => {
return prev.then(() => {
Expand Down

0 comments on commit 2e963de

Please sign in to comment.