All files / src/utils MakefileEditor.js

5.75% Statements 5/87
0% Branches 0/31
0% Functions 0/34
6.02% Lines 5/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197            24x 24x 24x 24x 24x                                                                                                                                                                                                                                                                                                                                                                                    
import {join, last, pipe, replace, split} from 'ramda';
import {existsSync} from 'fs-extra';
import createJsonEditor from './createJsonEditor';
import createModuleEditor from './createModuleEditor';
import {getBinDirectory, parse} from './common';
 
const {assign, entries} = Object;
const {isArray} = Array;
const kebabCase = pipe(split(':'), join('-'));
const silent = () => {};
const isLocalNpmCommand = (command, path = process.cwd()) => {
    const [packageDirectory] = path.split('Makefile');
    const Editor = createJsonEditor('package.json');
    const pkg = new Editor(packageDirectory);
    const pkgHasCommmand = pkg.hasAll(command);
    const binHasCommand = existsSync(`${getBinDirectory(path)}${command}`);
    return pkgHasCommmand || binHasCommand;
};
/**
 * Create and edit Makefiles. Includes ability to import package.json scripts.
 */
export class MakefileEditor extends createModuleEditor('Makefile') {
    contents = '';
    scripts = {};
    useBinVariable = false;
    constructor(path = process.cwd()) {
        super(path);
    }
    write(contents) {
        const self = this;
        const {fs, path, queue} = self;
        queue
            .add(() => fs.write(path, contents))
            .then(() => self.created = existsSync(path))
            .catch(silent);
        return assign(self, {contents});
    }
    /**
     * Append line(s) to end of Makefile
     * @param {(string|Symbol)} [lines=Symbol('skip')] Lines to append
     * @return {MakefileEditor} Chaining OK
     */
    append(lines = Symbol('skip')) {
        const {contents} = this;
        const shouldSkip = (typeof lines === 'symbol');
        return shouldSkip ? this : this.write(`${contents}\n${lines}`);
    }
    /**
     * Prepend line(s) to top of Makefile (similar API to {@link MakefileEditor#append})
     * @param {(string|Symbol)} [lines=Symbol('skip')] Lines to append
     * @return {MakefileEditor} Chaining OK
     */
    prepend(lines = Symbol('skip')) {
        const {contents} = this;
        const shouldSkip = (typeof lines === 'symbol');
        return shouldSkip ? this : this.write(`${lines}\n${contents}`);
    }
    /**
     * Format task and remove package.json dependency by replacing npm with make and such
     * @param {string} action Task action
     * @param {object} scripts Scripts object imported from package.json (must run {@link MakefileEditor#importScripts} first)
     * @return {string} Formatted action
     */
    formatTask(action, scripts = {}) {
        const {path} = this;
        const formatTaskName = pipe(
            split(':'),
            join('-'),
            split(' '),
            last,
            replace(/["']/g, '')
        );
        const replaceNpmRunQuotes = initial => {
            const re = /['"]npm run .[^"]*['"]/g;
            const matches = action.match(re);
            return isArray(matches) ? matches.reduce((acc, match) => acc.replace(match, `'make ${formatTaskName(match)}'`), initial) : initial;
        };
        const replaceNpmWithArguments = initial => {
            const re = /npm .* -- --.*/g;
            const matches = action.match(re);
            const getTaskName = pipe(split(' '), last);
            return isArray(matches) ? matches.reduce((acc, match) => {
                const [commands, options] = match.split(' -- ');
                return acc.replace(match, `${scripts[getTaskName(commands)]} ${options}`);
            }, initial) : initial;
        };
        const replaceNpmRunCommands = initial => {
            const re = /^npm run .*/g;
            const matches = action.match(re);
            return isArray(matches) ? matches.reduce((acc, match) => acc.replace(match, `$(MAKE) ${formatTaskName(match)}`), initial) : initial;
        };
        const formatted = action
            |> replaceNpmRunQuotes
            |> replaceNpmWithArguments
            |> replaceNpmRunCommands;
        const [command] = formatted.split(' ');
        const useBinVariable = isLocalNpmCommand(command, path);
        this.useBinVariable = this.useBinVariable || useBinVariable;
        return `${useBinVariable ? `$(bin)` : ''}${formatted}`;
    }
    /**
     * Add task to Makefile (appended to end)
     * @param {string} name Task name ("build", "lint", etc...)
     * @param {string[]} tasks Lines of code to be executed during task
     * @param {object} options Configure task
     * @param {string} [options.description] Task description used in help task
     * @param {boolean} [options.silent=false] Prepend "@" (true) or not (false)
     * @return {MakefileEditor} Chaining OK
     */
    addTask(name, tasks, options = {description: 'Task description'}) {
        const self = this;
        const {scripts} = self;
        const {description} = options;
        return tasks.reduce((tasks, action) => tasks
            .append(`\t${self.formatTask(action, scripts)}`)
            .addTaskDescription(name, description)
        , self.append(`${name}:`));
    }
    /**
     * Add deescription to task for use during help task
     * @param {string} task Task name
     * @param {string} description Description text
     * @example
     * const makefile = await (new MakefileEditor())
     *     .addTask('foo', 'echo foo')
     *     .commit();
     * // foo: ## Task description <-- default task description
     * //     echo foo
     * //
     * await makefile
     *     .addTaskDescription('foo', 'This task does foo')
     *     .commit();
     * // foo: ## This task does foo
     * //     echo foo
     * //
     * @return {MakefileEditor} Chaining OK
     */
    addTaskDescription(task, description = 'Task description') {
        const contents = this.contents.replace(`${kebabCase(task)}:\n`, `${kebabCase(task)}: ## ${description}\n`);
        return this.write(contents);
    }
    appendHelpTask() {
        const task = `@fgrep -h "##" $(MAKEFILE_LIST) | fgrep -v fgrep | sed -e 's/\\$$//' | sed -e 's/##/\\n    /'`;
        return this.addTask('help', [task], {description: 'Show this help'});
    }
    /**
     * Add Makefile comment
     * @param {string} text Comment text
     * @return {MakefileEditor} Chaining OK
     */
    addComment(text) {
        return this.append(`# ${text}`);
    }
    importScripts() {
        const {path} = this;
        const [packageDirectory] = path.split('Makefile');
        const Editor = createJsonEditor('package.json');
        const pkg = (new Editor(packageDirectory)).read();
        const {scripts} = parse(pkg);
        return assign(this, {scripts});
    }
    /**
     * Append tasks imported from package.json
     * @example <caption>Must execute importScripts first</caption>
     * const makefile = await (new MakefileEditor())
     *     .importScripts()
     *     .appendScripts()
     *     .commit();
     * @return {MakefileEditor} Chaining OK
     */
    appendScripts() {
        const self = this;
        const {path, scripts} = self;
        const tasks = entries(scripts).map(([key, value]) => [kebabCase(key), [value]]);
        const getPreTask = (tasks, name) => {
            const [data] = tasks
                .filter(([name]) => name.startsWith('pre'))
                .map(([name, values]) => [name.substring('pre'.length), values])
                .filter(task => task[0] === name);
            return isArray(data) ? data[1] : [];
        };
        const getPostTask = (tasks, name) => {
            const [data] = tasks
                .filter(([name]) => name.startsWith('post'))
                .map(([name, values]) => [name.substring('post'.length), values])
                .filter(task => task[0] === name);
            return isArray(data) ? data[1] : [];
        };
        return tasks
            .filter(([name]) => !(name.startsWith('pre') || name.startsWith('post')))
            .map(([name, values]) => [name, [...getPreTask(tasks, name), ...values, ...getPostTask(tasks, name)]])
            .reduce((tasks, [key, values]) => tasks.addTask(key, values).append(''), self.append(''))
            .prepend(self.useBinVariable ? `bin := ${getBinDirectory(path)}` : Symbol('skip'))
            .prepend(`# Built from ${path}/package.json`);
    }
}
export default MakefileEditor;