all-contributors-cli/lib/generate/index.js

73 lines
2.5 KiB
JavaScript
Raw Normal View History

2016-03-01 22:30:14 +00:00
'use strict';
var _ = require('lodash/fp');
2016-03-27 15:08:25 +00:00
var injectContentBetween = require('../util').markdown.injectContentBetween;
2016-05-05 14:27:26 +00:00
var formatBadge = require('./format-badge');
var formatContributor = require('./format-contributor');
2016-05-05 14:27:26 +00:00
var badgeRegex = /\[!\[All Contributors\]\([a-zA-Z0-9\-\.\/_:\?=]+\)\]\(#\w+\)/;
function injectListBetweenTags(newContent) {
return function (previousContent) {
var tagToLookFor = '<!-- ALL-CONTRIBUTORS-LIST:';
var closingTag = '-->';
var startOfOpeningTagIndex = previousContent.indexOf(tagToLookFor + 'START');
var endOfOpeningTagIndex = previousContent.indexOf(closingTag, startOfOpeningTagIndex);
var startOfClosingTagIndex = previousContent.indexOf(tagToLookFor + 'END', endOfOpeningTagIndex);
if (startOfOpeningTagIndex === -1 || endOfOpeningTagIndex === -1 || startOfClosingTagIndex === -1) {
return previousContent;
}
return previousContent.slice(0, endOfOpeningTagIndex + closingTag.length) +
newContent +
previousContent.slice(startOfClosingTagIndex);
};
}
2016-03-01 22:30:14 +00:00
function formatLine(contributors) {
return '| ' + contributors.join(' | ') + ' |';
}
function createColumnLine(options, contributors) {
var nbColumns = Math.min(options.contributorsPerLine, contributors.length);
return _.repeat(nbColumns, '| :---: ') + '|';
}
2016-03-01 22:30:14 +00:00
function generateContributorsList(options, contributors) {
return _.flow(
_.map(function formatEveryContributor(contributor) {
2016-03-01 22:30:14 +00:00
return formatContributor(options, contributor);
}),
_.chunk(options.contributorsPerLine),
_.map(formatLine),
function insertColumns(lines) {
var columnLine = createColumnLine(options, contributors);
return injectContentBetween(lines, columnLine, 1, 1);
},
_.join('\n'),
function (newContent) {
return '\n' + newContent + '\n';
}
2016-03-01 22:30:14 +00:00
)(contributors);
}
function replaceBadge(newContent) {
return function (previousContent) {
var regexResult = badgeRegex.exec(previousContent);
if (!regexResult) {
return previousContent;
}
return previousContent.slice(0, regexResult.index) +
newContent +
previousContent.slice(regexResult.index + regexResult[0].length);
};
}
2016-03-01 22:30:14 +00:00
module.exports = function generate(options, contributors, fileContent) {
var contributorsList = contributors.length === 0 ? '\n' : generateContributorsList(options, contributors);
var badge = formatBadge(options, contributors);
2016-03-01 22:30:14 +00:00
return _.flow(
injectListBetweenTags(contributorsList),
replaceBadge(badge)
)(fileContent);
2016-03-01 22:30:14 +00:00
};