<commit_before>"use strict";

var process = require("process");
var path = require("path");
var fs = require('fs-extra');
var glob = require("glob");
var rimraf = require("rimraf");
var pjson = require('../package.json');
var child_process = require('child_process');
var targz = require('tar.gz');

const CATEGORY = "-category";

// `i-am-article` becomes `I Am Article`
function prettify(str) {
    return str.split('-').map(function capitalize(part) {
        return part.charAt(0).toUpperCase() + part.slice(1);
    }).join(' ');
}

// Folder name 'ui-examples' becomes 'ui' (the way it should be displayed in the documentation tree)
function updateSubfoldersName(str) {
    return str.slice(0, str.lastIndexOf("-"));
}

function compareFiles(leftFile, rightFile) {
    var l = prettify(path.basename(path.dirname(leftFile)));
    var r = prettify(path.basename(path.dirname(rightFile)));
    return l.localeCompare(r, "en-US");
}

// Sort the examples based on the example-order defined in metadata.md. The missing example will be sort aphabetically at the end
// Example:
// metadata.md - action-bar
// example-order: title, action-items
function orderExamples (array, order, dirName) {
    var customSortArray = [];
    order.forEach(function(item){
        var index = array.indexOf(dirName+"/"+item+"/article.md");
        if(index >= 0){
            customSortArray.push(array[index]);
            array.splice(index, 1);
        }
    });
    array = array.sort(compareFiles);
    var resultArray = customSortArray.concat(array);
    return resultArray;
};

function build() {
    // Re-create the `dist` dir
    var cwd = process.cwd();
    var distDir = path.join(cwd, "dist");
    rimraf.sync(distDir);
    fs.mkdirSync(distDir);

    var articlesDir = path.join(distDir, "code-samples");
    fs.mkdirSync(articlesDir);

    var appDir = path.join(cwd, "app");

    var mainOverview = path.join(appDir, "global-overview.md");
    fs.copySync(mainOverview, path.join(articlesDir, "overview.md"));

    var jenkinsPosition = 1;

    gatherArticles(cwd, appDir, articlesDir, jenkinsPosition);
};

function gatherArticles(cwd, appDir, articlesDir, jenkinsPosition) {
    // Gather all main subfolders - ui
    var subDirs = fs.readdirSync(appDir).filter(function (file) {
        var filePath = path.join(appDir, file);
        var dir = fs.statSync(filePath);

        return dir.isDirectory() && path.parse(filePath).name.indexOf(CATEGORY) !== -1;
    });

    subDirs.forEach(function (subDir) {
        var currentDir = path.join(articlesDir, subDir);
        currentDir = updateSubfoldersName(currentDir);
        fs.mkdirSync(currentDir);

        var subDirPath = path.join(appDir, subDir);

        // Gather all component overviews in the subdirs - ng-ui-widgets-category, ui-extended-category
        var components = glob.sync(subDirPath + "/*/overview.md").filter(function (file) {
            return !path.parse(file).dir.endsWith(CATEGORY);
        }).sort(compareFiles);
        getComponents(cwd, components, currentDir, jenkinsPosition);
        gatherArticles(cwd, subDirPath, currentDir, jenkinsPosition);
    });

    // Gather all component overviews in the main folders - app
    var components = glob.sync(appDir + "/**/overview.md").filter(function (file) {
        return path.parse(file).dir.indexOf(CATEGORY) === -1;
    }).sort(compareFiles);

    getComponents(cwd, components, articlesDir, jenkinsPosition);
}

// Gather all component overviews
function getComponents(cwd, components, currentDir, jenkinsPosition) {
    var imgDir = path.join(currentDir, "img");
    if (!fs.existsSync(imgDir)) {
        fs.mkdirSync(imgDir);
    }

   components.forEach(function (overview) {
            var componentDirName = path.dirname(overview);
            var componentHeader = path.basename(componentDirName);
            // Create the component article file, i.e. button.md
            var componentArticleFile = path.join(currentDir, componentHeader + ".md");

            var componentPrettyHeader = prettify(componentHeader);

            var componentArticlesOrder = [];
            // Jenkins Header
            // MetaData.md
            var subDirPath = overview.replace("/overview.md", "");
            var pathExists = fs.existsSync(path.join(subDirPath, "metadata.md"));

            if (pathExists) {
                var metadata = path.join(subDirPath, "metadata.md");
                var metadataContents = fs.readFileSync(metadata, { encoding: 'utf8' });
                var metadataSplit = metadataContents.split("---");
                fs.appendFileSync(componentArticleFile, "---\n", { encoding: 'utf8' });
                fs.appendFileSync(componentArticleFile, metadataSplit[1] , { encoding: 'utf8' });
                fs.appendFileSync(componentArticleFile, "---\n\n", { encoding: 'utf8' });

                if(metadataSplit[2].indexOf("example-order") >=0){
                    var exampleOrderString = metadataSplit[2].split(":");
                    var orderString  = exampleOrderString[1].replace(/\s/g,'');
                    componentArticlesOrder = orderString.split(",");
                }
            }
            else {
                fs.appendFileSync(componentArticleFile, "---\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "title: " + componentPrettyHeader + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "description: " + componentPrettyHeader + " SDK Examples" + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "position: " + jenkinsPosition++  + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "slug: " + componentHeader + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "---\n\n",  {encoding:'utf8'});
            }

            // Component Markdown Header
            fs.appendFileSync(componentArticleFile, "# " + componentPrettyHeader + "\n\n",  {encoding:'utf8'});

            // Component Overview
            var overviewContents = fs.readFileSync(overview,  {encoding:'utf8'});
            fs.appendFileSync(componentArticleFile, overviewContents + "\n\n",  {encoding:'utf8'});

            // Component Images
            let componentImage = path.join(componentDirName, "image.png");
            if (fs.existsSync(componentImage)) {
                let newImageFileName = componentHeader + "-" + "image.png";
                fs.copySync(componentImage, path.join(imgDir, newImageFileName));

                fs.appendFileSync(componentArticleFile, "![Image](img/" + newImageFileName + " \"Image\")\n\n",  {encoding:'utf8'});
            }

            var articles = [];
            if(componentArticlesOrder.length >0){
                articles = orderExamples(glob.sync(componentDirName + "/**/article.md"), componentArticlesOrder, componentDirName);
            } else{
                articles = glob.sync(componentDirName + "/**/article.md").sort(compareFiles);
            }

            // Append each example to the big article file.
            articles.forEach(function (article) {
                var articleDirName = path.dirname(article);
                var articleHeader = path.basename(articleDirName);

                // Header
                var prettyArticleHeader = prettify(articleHeader);
                fs.appendFileSync(componentArticleFile, "## " + prettyArticleHeader + "\n\n",  {encoding:'utf8'});

                // Content
                var articleContents = fs.readFileSync(article,  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, articleContents + "\n\n",  {encoding:'utf8'});

                // Article Images
                let articleImage = path.join(articleDirName, "image.png");

                if (fs.existsSync(articleImage)) {
                    let newArticleImageFileName = componentHeader + "-" + articleHeader + "-image.png";
                    let joined = path.join(imgDir, newArticleImageFileName);
                    fs.copySync(articleImage, joined);

                    fs.appendFileSync(componentArticleFile, "![Image](img/" + newArticleImageFileName + " \"Image\")\n\n",  {encoding:'utf8'});
                }

                // Links
                var githubDirUrl = pjson.homepage + "/edit/master/" + path.relative(cwd, articleDirName).replace(/\\/g, "/");

                var linkToDocument = "[Improve this document](" + githubDirUrl + "/" + path.basename(article) + ")"
                fs.appendFileSync(componentArticleFile, linkToDocument + "\n\n",  {encoding:'utf8'});

                var linkToSource = "[Demo Source](" + githubDirUrl + ")"
                fs.appendFileSync(componentArticleFile, linkToSource + "\n\n",  {encoding:'utf8'});

                // Horizontal Line
                fs.appendFileSync(componentArticleFile, "---\n\n",  {encoding:'utf8'});
            });

            //End.md
            var subDirPath = overview.replace("/overview.md", "");
            var end = path.join(subDirPath, "end.md");
            var endContents = fs.readFileSync(end,  {encoding:'utf8'});
            fs.appendFileSync(componentArticleFile, endContents + "\n\n",  {encoding:'utf8'});
        });
}

build();
<commit_msg>collect images from folder<commit_after>"use strict";

var process = require("process");
var path = require("path");
var fs = require('fs-extra');
var glob = require("glob");
var rimraf = require("rimraf");
var pjson = require('../package.json');
var child_process = require('child_process');
var targz = require('tar.gz');

const CATEGORY = "-category";

// `i-am-article` becomes `I Am Article`
function prettify(str) {
    return str.split('-').map(function capitalize(part) {
        return part.charAt(0).toUpperCase() + part.slice(1);
    }).join(' ');
}

// Folder name 'ui-examples' becomes 'ui' (the way it should be displayed in the documentation tree)
function updateSubfoldersName(str) {
    return str.slice(0, str.lastIndexOf("-"));
}

function compareFiles(leftFile, rightFile) {
    var l = prettify(path.basename(path.dirname(leftFile)));
    var r = prettify(path.basename(path.dirname(rightFile)));
    return l.localeCompare(r, "en-US");
}

// Sort the examples based on the example-order defined in metadata.md. The missing example will be sort aphabetically at the end
// Example:
// metadata.md - action-bar
// example-order: title, action-items
function orderExamples (array, order, dirName) {
    var customSortArray = [];
    order.forEach(function(item){
        var index = array.indexOf(dirName+"/"+item+"/article.md");
        if(index >= 0){
            customSortArray.push(array[index]);
            array.splice(index, 1);
        }
    });
    array = array.sort(compareFiles);
    var resultArray = customSortArray.concat(array);
    return resultArray;
};

function build() {
    // Re-create the `dist` dir
    var cwd = process.cwd();
    var distDir = path.join(cwd, "dist");
    rimraf.sync(distDir);
    fs.mkdirSync(distDir);

    var articlesDir = path.join(distDir, "code-samples");
    fs.mkdirSync(articlesDir);

    var appDir = path.join(cwd, "app");

    var mainOverview = path.join(appDir, "global-overview.md");
    fs.copySync(mainOverview, path.join(articlesDir, "overview.md"));

    var jenkinsPosition = 1;

    gatherArticles(cwd, appDir, articlesDir, jenkinsPosition);
};

function gatherArticles(cwd, appDir, articlesDir, jenkinsPosition) {
    // Gather all main subfolders - ui
    var subDirs = fs.readdirSync(appDir).filter(function (file) {
        var filePath = path.join(appDir, file);
        var dir = fs.statSync(filePath);

        return dir.isDirectory() && path.parse(filePath).name.indexOf(CATEGORY) !== -1;
    });

    subDirs.forEach(function (subDir) {
        var currentDir = path.join(articlesDir, subDir);
        currentDir = updateSubfoldersName(currentDir);
        fs.mkdirSync(currentDir);

        var subDirPath = path.join(appDir, subDir);

        // Gather all component overviews in the subdirs - ng-ui-widgets-category, ui-extended-category
        var components = glob.sync(subDirPath + "/*/overview.md").filter(function (file) {
            return !path.parse(file).dir.endsWith(CATEGORY);
        }).sort(compareFiles);
        getComponents(cwd, components, currentDir, jenkinsPosition);
        gatherArticles(cwd, subDirPath, currentDir, jenkinsPosition);
    });

    // Gather all component overviews in the main folders - app
    var components = glob.sync(appDir + "/**/overview.md").filter(function (file) {
        return path.parse(file).dir.indexOf(CATEGORY) === -1;
    }).sort(compareFiles);

    getComponents(cwd, components, articlesDir, jenkinsPosition);
}

// Gather all component overviews
function getComponents(cwd, components, currentDir, jenkinsPosition) {
    var imgDir = path.join(currentDir, "img");
    if (!fs.existsSync(imgDir)) {
        fs.mkdirSync(imgDir);
    }

   components.forEach(function (overview) {
            var componentDirName = path.dirname(overview);
            var componentHeader = path.basename(componentDirName);
            // Create the component article file, i.e. button.md
            var componentArticleFile = path.join(currentDir, componentHeader + ".md");

            var componentPrettyHeader = prettify(componentHeader);

            var componentArticlesOrder = [];
            // Jenkins Header
            // MetaData.md
            var subDirPath = overview.replace("/overview.md", "");
            var pathExists = fs.existsSync(path.join(subDirPath, "metadata.md"));

            if (pathExists) {
                var metadata = path.join(subDirPath, "metadata.md");
                var metadataContents = fs.readFileSync(metadata, { encoding: 'utf8' });
                var metadataSplit = metadataContents.split("---");
                fs.appendFileSync(componentArticleFile, "---\n", { encoding: 'utf8' });
                fs.appendFileSync(componentArticleFile, metadataSplit[1] , { encoding: 'utf8' });
                fs.appendFileSync(componentArticleFile, "---\n\n", { encoding: 'utf8' });

                if(metadataSplit[2].indexOf("example-order") >=0){
                    var exampleOrderString = metadataSplit[2].split(":");
                    var orderString  = exampleOrderString[1].replace(/\s/g,'');
                    componentArticlesOrder = orderString.split(",");
                }
            }
            else {
                fs.appendFileSync(componentArticleFile, "---\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "title: " + componentPrettyHeader + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "description: " + componentPrettyHeader + " SDK Examples" + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "position: " + jenkinsPosition++  + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "slug: " + componentHeader + "\n",  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, "---\n\n",  {encoding:'utf8'});
            }

            // Component Markdown Header
            fs.appendFileSync(componentArticleFile, "# " + componentPrettyHeader + "\n\n",  {encoding:'utf8'});

            // Component Overview
            var overviewContents = fs.readFileSync(overview,  {encoding:'utf8'});
            fs.appendFileSync(componentArticleFile, overviewContents + "\n\n",  {encoding:'utf8'});

            // Component Images
            let componentImage = path.join(componentDirName, "image.png");
            if (fs.existsSync(componentImage)) {
                let newImageFileName = componentHeader + "-" + "image.png";
                fs.copySync(componentImage, path.join(imgDir, newImageFileName));

                fs.appendFileSync(componentArticleFile, "![Image](img/" + newImageFileName + " \"Image\")\n\n",  {encoding:'utf8'});
            }

            var articles = [];
            if(componentArticlesOrder.length >0){
                articles = orderExamples(glob.sync(componentDirName + "/**/article.md"), componentArticlesOrder, componentDirName);
            } else{
                articles = glob.sync(componentDirName + "/**/article.md").sort(compareFiles);
            }

            // Append each example to the big article file.
            articles.forEach(function (article) {
                var articleDirName = path.dirname(article);
                var articleHeader = path.basename(articleDirName);

                // Header
                var prettyArticleHeader = prettify(articleHeader);
                fs.appendFileSync(componentArticleFile, "## " + prettyArticleHeader + "\n\n",  {encoding:'utf8'});

                // Content
                var articleContents = fs.readFileSync(article,  {encoding:'utf8'});
                fs.appendFileSync(componentArticleFile, articleContents + "\n\n",  {encoding:'utf8'});

                // Article Images
                let articleImage = path.join(articleDirName, "image.png");

                if (fs.existsSync(articleImage)) {
                    let newArticleImageFileName = componentHeader + "-" + articleHeader + "-image.png";
                    let joined = path.join(imgDir, newArticleImageFileName);
                    fs.copySync(articleImage, joined);

                    fs.appendFileSync(componentArticleFile, "![Image](img/" + newArticleImageFileName + " \"Image\")\n\n",  {encoding:'utf8'});
                }
                let articleImages = glob.sync(articleDirName + "/*.png");
                articleImages.forEach(function(imagePath){
                    let stringSplitResult = imagePath.split("/");
                    let imageName = stringSplitResult[stringSplitResult.length - 1];
                    let joined = path.join(imgDir, imageName);
                    fs.copySync(imagePath, joined);
                })

                // Links
                var githubDirUrl = pjson.homepage + "/edit/master/" + path.relative(cwd, articleDirName).replace(/\\/g, "/");

                var linkToDocument = "[Improve this document](" + githubDirUrl + "/" + path.basename(article) + ")"
                fs.appendFileSync(componentArticleFile, linkToDocument + "\n\n",  {encoding:'utf8'});

                var linkToSource = "[Demo Source](" + githubDirUrl + ")"
                fs.appendFileSync(componentArticleFile, linkToSource + "\n\n",  {encoding:'utf8'});

                // Horizontal Line
                fs.appendFileSync(componentArticleFile, "---\n\n",  {encoding:'utf8'});
            });

            //End.md
            var subDirPath = overview.replace("/overview.md", "");
            var end = path.join(subDirPath, "end.md");
            var endContents = fs.readFileSync(end,  {encoding:'utf8'});
            fs.appendFileSync(componentArticleFile, endContents + "\n\n",  {encoding:'utf8'});
        });
}

build();
<|endoftext|>


<commit_before>//Import dependencies
var path = require('path');
var gulp = require('gulp');
var rename = require('gulp-rename');
var nunjucks = require('gulp-nunjucks-render');
var sass = require('gulp-sass');
var rmr = require('rmr');

//Import build methods
var projects = require('./projects.js');

//Destination folders
var dest = {};
dest.base = './dist'; //Base destination folder
dest.css = path.join(dest.base, './css'); //Output css folder
dest.js = path.join(dest.base, './js'); //Output js folder
dest.images = path.join(dest.base, './images'); //Output images folder

//Clean the output folder
rmr.sync(dest.base);

//Initialize the global configuration
var config = {};

//Function to compile the html files
var buildHTML = function()
{
  //Get the source files
  gulp.src('./src/**/*.html')

  //Build the page
  .pipe(nunjucks({ path: './templates/', data: config }))

  //Output path
  .pipe(gulp.dest(dest.base));
};

//Function to compile the scss files and generate the css files
var buildCSS = function()
{
  //Get the scss files
  gulp.src('./src/scss/**/*.scss')

  //Build the scss files
  .pipe(sass({ includePaths: [ 'bower_components', 'node_modules' ] }).on('error', sass.logError))

  //Save in the dist/css folder
  .pipe(gulp.dest(dest.css));
};

//Function to copy the assets and other files
var Copy = function()
{
  //Copy the yaml files
  gulp.src(['./**.yaml']).pipe(gulp.dest(dest.base));

  //Copy the javascript files
  //gulp.src('./src/js/*.js').pipe(gulp.dest(dest.js));

  //Copy the images folder
  gulp.src('./src/images/**').pipe(gulp.dest(dest.images));

  //Copy the siimple modules
  gulp.src('./bower_components/siimple/dist/siimple.css').pipe(gulp.dest(dest.css));
  gulp.src('./bower_components/siimple-colors/dist/siimple-colors.css').pipe(gulp.dest(dest.css));

  //Copy the plume layout files
  gulp.src('./bower_components/plume/dist/plume.css').pipe(gulp.dest(dest.css));
  gulp.src('./bower_components/plume/dist/plume.js').pipe(gulp.dest(dest.js));

  //For each module
  config.projects.forEach(function(project)
  {
    //Output folder
    var output = path.join(dest.images, project.name);

    //Copy the base image
    gulp.src('./bower_components/' + project.name + '/media/logo-inverted.png').pipe(rename({ basename: 'logo' })).pipe(gulp.dest(output));

    //Copy the header image
    gulp.src('./bower_components/' + project.name + '/media/logo-header.png').pipe(rename({ basename: 'header' })).pipe(gulp.dest(output));
  });
};

//Import the projects list
projects(function(error, list)
{
  //check the error
  if(error){ throw error; }

  //Save the projects list
  config.projects = list;

  //Build the HTML files
  buildHTML();

  //Build the css files
  buildCSS();

  //Copy the assets and other files
  Copy();
});
<commit_msg>Removed old build script<commit_after><|endoftext|>


<commit_before>var isArray = require("x-is-array")
var isObject = require("is-object")

var VPatch = require("./vpatch")
var isVNode = require("./is-vnode")
var isVText = require("./is-vtext")
var isWidget = require("./is-widget")
var isThunk = require("./is-thunk")

module.exports = diff

function diff(a, b) {
    var patch = { a: a }
    walk(a, b, patch, 0)
    return patch
}

function walk(a, b, patch, index) {
    if (isThunk(b)) {
        if (isThunk(a)) {
            b = b.vnode = b.render(a)
            a = a.vnode
        } else {
            b = b.vnode = b.render(null)
        }
    }

    if (a === b) {
        hooks(b, patch, index)
        return
    }

    var apply = patch[index]

    if (b == null) {
        apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
        destroyWidgets(a, patch, index)
    } else if (isVNode(b)) {
        if (isVNode(a)) {
            if (a.tagName === b.tagName &&
                a.namespace === b.namespace &&
                a.key === b.key) {
                var propsPatch = diffProps(a.properties, b.properties, b.hooks)
                if (propsPatch) {
                    apply = appendPatch(apply,
                        new VPatch(VPatch.PROPS, a, propsPatch))
                }
            } else {
                apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
                destroyWidgets(a, patch, index)
            }

            apply = diffChildren(a, b, patch, apply, index)
        } else {
            apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
            destroyWidgets(a, patch, index)
        }
    } else if (isVText(b)) {
        if (!isVText(a)) {
            apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
            destroyWidgets(a, patch, index)
        } else if (a.text !== b.text) {
            apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
        }
    } else if (isWidget(b)) {
        apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))

        if (!isWidget(a)) {
            destroyWidgets(a, patch, index)
        }
    }

    if (apply) {
        patch[index] = apply
    }
}

function diffProps(a, b, hooks) {
    var diff

    for (var aKey in a) {
        if (!(aKey in b)) {
            diff = diff || {}
            diff[aKey] = undefined
        }

        var aValue = a[aKey]
        var bValue = b[aKey]

        if (hooks && aKey in hooks) {
            diff = diff || {}
            diff[aKey] = bValue
        } else {
            if (isObject(aValue) && isObject(bValue)) {
                if (getPrototype(bValue) !== getPrototype(aValue)) {
                    diff = diff || {}
                    diff[aKey] = bValue
                } else {
                    var objectDiff = diffProps(aValue, bValue)
                    if (objectDiff) {
                        diff = diff || {}
                        diff[aKey] = objectDiff
                    }
                }
            } else if (aValue !== bValue && bValue !== undefined) {
                diff = diff || {}
                diff[aKey] = bValue
            }
        }
    }

    for (var bKey in b) {
        if (!(bKey in a)) {
            diff = diff || {}
            diff[bKey] = b[bKey]
        }
    }

    return diff
}

function getPrototype(value) {
    if (Object.getPrototypeOf) {
        return Object.getPrototypeOf(value)
    } else if (value.__proto__) {
        return value.__proto__
    } else if (value.constructor) {
        return value.constructor.prototype
    }
}

function diffChildren(a, b, patch, apply, index) {
    var aChildren = a.children
    var bChildren = reorder(aChildren, b.children)

    var aLen = aChildren.length
    var bLen = bChildren.length
    var len = aLen > bLen ? aLen : bLen

    for (var i = 0; i < len; i++) {
        var leftNode = aChildren[i]
        var rightNode = bChildren[i]
        index += 1

        if (!leftNode) {
            if (rightNode) {
                // Excess nodes in b need to be added
                apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode))
            }
        } else if (!rightNode) {
            if (leftNode) {
                // Excess nodes in a need to be removed
                patch[index] = new VPatch(VPatch.REMOVE, leftNode, null)
                destroyWidgets(leftNode, patch, index)
            }
        } else {
            walk(leftNode, rightNode, patch, index)
        }

        if (isVNode(leftNode) && leftNode.count) {
            index += leftNode.count
        }
    }

    if (bChildren.moves) {
        // Reorder nodes last
        apply = appendPatch(apply, new VPatch(VPatch.ORDER, a, bChildren.moves))
    }

    return apply
}

// Patch records for all destroyed widgets must be added because we need
// a DOM node reference for the destroy function
function destroyWidgets(vNode, patch, index) {
    if (isWidget(vNode)) {
        if (typeof vNode.destroy === "function") {
            patch[index] = new VPatch(VPatch.REMOVE, vNode, null)
        }
    } else if (isVNode(vNode) && vNode.hasWidgets) {
        var children = vNode.children
        var len = children.length
        for (var i = 0; i < len; i++) {
            var child = children[i]
            index += 1

            destroyWidgets(child, patch, index)

            if (isVNode(child) && child.count) {
                index += child.count
            }
        }
    }
}

// Execute hooks when two nodes are identical
function hooks(vNode, patch, index) {
    if (isVNode(vNode)) {
        if (vNode.hooks) {
            patch[index] = new VPatch(VPatch.PROPS, vNode.hooks, vNode.hooks)
        }

        if (vNode.descendantHooks) {
            var children = vNode.children
            var len = children.length
            for (var i = 0; i < len; i++) {
                var child = children[i]
                index += 1

                hooks(child, patch, index)

                if (isVNode(child) && child.count) {
                    index += child.count
                }
            }
        }
    }
}

// List diff, naive left to right reordering
function reorder(aChildren, bChildren) {

    var bKeys = keyIndex(bChildren)

    if (!bKeys) {
        return bChildren
    }

    var aKeys = keyIndex(aChildren)

    if (!aKeys) {
        return bChildren
    }

    var bMatch = {}, aMatch = {}

    for (var key in bKeys) {
        bMatch[bKeys[key]] = aKeys[key]
    }

    for (var key in aKeys) {
        aMatch[aKeys[key]] = bKeys[key]
    }

    var aLen = aChildren.length
    var bLen = bChildren.length
    var len = aLen > bLen ? aLen : bLen
    var shuffle = []
    var freeIndex = 0
    var i = 0
    var moveIndex = 0
    var moves = shuffle.moves = {}

    while (freeIndex < len) {
        var move = aMatch[i]
        if (move !== undefined) {
            shuffle[i] = bChildren[move]
            moves[move] = moveIndex++
        } else if (i in aMatch) {
            shuffle[i] = undefined
            moves[move] = moveIndex++
        } else {
            while (bMatch[freeIndex] !== undefined) {
                freeIndex++
            }

            if (freeIndex < len) {
                var freeChild = bChildren[freeIndex]
                if (freeChild) {
                    moves[freeIndex] = moveIndex++
                    shuffle[i] = freeChild
                }
                freeIndex++
            }
        }
        i++
    }

    return shuffle
}

function keyIndex(children) {
    var i, keys

    for (i = 0; i < children.length; i++) {
        var child = children[i]

        if (child.key !== undefined) {
            keys = keys || {}
            keys[child.key] = i
        }
    }

    return keys
}

function appendPatch(apply, patch) {
    if (apply) {
        if (isArray(apply)) {
            apply.push(patch)
        } else {
            apply = [apply, patch]
        }

        return apply
    } else {
        return patch
    }
}
<commit_msg>produce diffs for undefined values<commit_after>var isArray = require("x-is-array")
var isObject = require("is-object")

var VPatch = require("./vpatch")
var isVNode = require("./is-vnode")
var isVText = require("./is-vtext")
var isWidget = require("./is-widget")
var isThunk = require("./is-thunk")

module.exports = diff

function diff(a, b) {
    var patch = { a: a }
    walk(a, b, patch, 0)
    return patch
}

function walk(a, b, patch, index) {
    if (isThunk(b)) {
        if (isThunk(a)) {
            b = b.vnode = b.render(a)
            a = a.vnode
        } else {
            b = b.vnode = b.render(null)
        }
    }

    if (a === b) {
        hooks(b, patch, index)
        return
    }

    var apply = patch[index]

    if (b == null) {
        apply = appendPatch(apply, new VPatch(VPatch.REMOVE, a, b))
        destroyWidgets(a, patch, index)
    } else if (isVNode(b)) {
        if (isVNode(a)) {
            if (a.tagName === b.tagName &&
                a.namespace === b.namespace &&
                a.key === b.key) {
                var propsPatch = diffProps(a.properties, b.properties, b.hooks)
                if (propsPatch) {
                    apply = appendPatch(apply,
                        new VPatch(VPatch.PROPS, a, propsPatch))
                }
            } else {
                apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
                destroyWidgets(a, patch, index)
            }

            apply = diffChildren(a, b, patch, apply, index)
        } else {
            apply = appendPatch(apply, new VPatch(VPatch.VNODE, a, b))
            destroyWidgets(a, patch, index)
        }
    } else if (isVText(b)) {
        if (!isVText(a)) {
            apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
            destroyWidgets(a, patch, index)
        } else if (a.text !== b.text) {
            apply = appendPatch(apply, new VPatch(VPatch.VTEXT, a, b))
        }
    } else if (isWidget(b)) {
        apply = appendPatch(apply, new VPatch(VPatch.WIDGET, a, b))

        if (!isWidget(a)) {
            destroyWidgets(a, patch, index)
        }
    }

    if (apply) {
        patch[index] = apply
    }
}

function diffProps(a, b, hooks) {
    var diff

    for (var aKey in a) {
        if (!(aKey in b)) {
            diff = diff || {}
            diff[aKey] = undefined
        }

        var aValue = a[aKey]
        var bValue = b[aKey]

        if (hooks && aKey in hooks) {
            diff = diff || {}
            diff[aKey] = bValue
        } else {
            if (isObject(aValue) && isObject(bValue)) {
                if (getPrototype(bValue) !== getPrototype(aValue)) {
                    diff = diff || {}
                    diff[aKey] = bValue
                } else {
                    var objectDiff = diffProps(aValue, bValue)
                    if (objectDiff) {
                        diff = diff || {}
                        diff[aKey] = objectDiff
                    }
                }
            } else if (aValue !== bValue) {
                diff = diff || {}
                diff[aKey] = bValue
            }
        }
    }

    for (var bKey in b) {
        if (!(bKey in a)) {
            diff = diff || {}
            diff[bKey] = b[bKey]
        }
    }

    return diff
}

function getPrototype(value) {
    if (Object.getPrototypeOf) {
        return Object.getPrototypeOf(value)
    } else if (value.__proto__) {
        return value.__proto__
    } else if (value.constructor) {
        return value.constructor.prototype
    }
}

function diffChildren(a, b, patch, apply, index) {
    var aChildren = a.children
    var bChildren = reorder(aChildren, b.children)

    var aLen = aChildren.length
    var bLen = bChildren.length
    var len = aLen > bLen ? aLen : bLen

    for (var i = 0; i < len; i++) {
        var leftNode = aChildren[i]
        var rightNode = bChildren[i]
        index += 1

        if (!leftNode) {
            if (rightNode) {
                // Excess nodes in b need to be added
                apply = appendPatch(apply, new VPatch(VPatch.INSERT, null, rightNode))
            }
        } else if (!rightNode) {
            if (leftNode) {
                // Excess nodes in a need to be removed
                patch[index] = new VPatch(VPatch.REMOVE, leftNode, null)
                destroyWidgets(leftNode, patch, index)
            }
        } else {
            walk(leftNode, rightNode, patch, index)
        }

        if (isVNode(leftNode) && leftNode.count) {
            index += leftNode.count
        }
    }

    if (bChildren.moves) {
        // Reorder nodes last
        apply = appendPatch(apply, new VPatch(VPatch.ORDER, a, bChildren.moves))
    }

    return apply
}

// Patch records for all destroyed widgets must be added because we need
// a DOM node reference for the destroy function
function destroyWidgets(vNode, patch, index) {
    if (isWidget(vNode)) {
        if (typeof vNode.destroy === "function") {
            patch[index] = new VPatch(VPatch.REMOVE, vNode, null)
        }
    } else if (isVNode(vNode) && vNode.hasWidgets) {
        var children = vNode.children
        var len = children.length
        for (var i = 0; i < len; i++) {
            var child = children[i]
            index += 1

            destroyWidgets(child, patch, index)

            if (isVNode(child) && child.count) {
                index += child.count
            }
        }
    }
}

// Execute hooks when two nodes are identical
function hooks(vNode, patch, index) {
    if (isVNode(vNode)) {
        if (vNode.hooks) {
            patch[index] = new VPatch(VPatch.PROPS, vNode.hooks, vNode.hooks)
        }

        if (vNode.descendantHooks) {
            var children = vNode.children
            var len = children.length
            for (var i = 0; i < len; i++) {
                var child = children[i]
                index += 1

                hooks(child, patch, index)

                if (isVNode(child) && child.count) {
                    index += child.count
                }
            }
        }
    }
}

// List diff, naive left to right reordering
function reorder(aChildren, bChildren) {

    var bKeys = keyIndex(bChildren)

    if (!bKeys) {
        return bChildren
    }

    var aKeys = keyIndex(aChildren)

    if (!aKeys) {
        return bChildren
    }

    var bMatch = {}, aMatch = {}

    for (var key in bKeys) {
        bMatch[bKeys[key]] = aKeys[key]
    }

    for (var key in aKeys) {
        aMatch[aKeys[key]] = bKeys[key]
    }

    var aLen = aChildren.length
    var bLen = bChildren.length
    var len = aLen > bLen ? aLen : bLen
    var shuffle = []
    var freeIndex = 0
    var i = 0
    var moveIndex = 0
    var moves = shuffle.moves = {}

    while (freeIndex < len) {
        var move = aMatch[i]
        if (move !== undefined) {
            shuffle[i] = bChildren[move]
            moves[move] = moveIndex++
        } else if (i in aMatch) {
            shuffle[i] = undefined
            moves[move] = moveIndex++
        } else {
            while (bMatch[freeIndex] !== undefined) {
                freeIndex++
            }

            if (freeIndex < len) {
                var freeChild = bChildren[freeIndex]
                if (freeChild) {
                    moves[freeIndex] = moveIndex++
                    shuffle[i] = freeChild
                }
                freeIndex++
            }
        }
        i++
    }

    return shuffle
}

function keyIndex(children) {
    var i, keys

    for (i = 0; i < children.length; i++) {
        var child = children[i]

        if (child.key !== undefined) {
            keys = keys || {}
            keys[child.key] = i
        }
    }

    return keys
}

function appendPatch(apply, patch) {
    if (apply) {
        if (isArray(apply)) {
            apply.push(patch)
        } else {
            apply = [apply, patch]
        }

        return apply
    } else {
        return patch
    }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const log = require('loglevel');
const colors = require('colors/safe');
const spawn = require('child_process').spawn;
const { Map } = require('immutable');
const path = require('path');
const fs = require('fs');
const requireAll = require('require-all');

const configs = new Map(requireAll({
  dirname: path.resolve('config'),
  filter: /\.json$/i,
  recursive: false,
  map: (name, filePath) => path.basename(filePath, '.json'),
}));

process.env.NODE_ENV = 'production';
log.enableAll();

const buildLog = fs.createWriteStream(path.resolve('build.log'), { flags: 'w+' });
buildLog.on('open', () => {
  log.info('📦  Generate config files');
  const distDir = path.resolve('dist-configs');
  fs.mkdir(distDir, () => {
    configs.forEach((config, environment) => {
      const file = `${environment}.js`;
      const fileDir = path.join(distDir, file);
      try {
        fs.writeFileSync(fileDir, `var __CONFIG__ = Object.freeze(${JSON.stringify(config)})`);
        log.info(colors.green(`   📄  ${file} generated`));
      } catch (e) {
        log.error(colors.red(`   📄  ${file} could not be generated`));
        buildLog.write(e);
        process.exit(1);
      }
    });

    log.info('📦  Build app');
    const webpack = spawn('node', ['node_modules/webpack/bin/webpack.js', '-p', '--bail', '--progress', '--colors'], { env: process.env, stdio: [buildLog, buildLog, buildLog] });
    webpack.on('close', (code) => {
      if (code) {
        log.error(colors.red('   💣  App build failed!'));
        process.exit(code);
      }

      log.info(colors.green('   📦  App built'));
    });
  });
});
<commit_msg>Made sure the child process is killed in build.js<commit_after>#!/usr/bin/env node

const log = require('loglevel');
const colors = require('colors/safe');
const spawn = require('child_process').spawn;
const { Map } = require('immutable');
const path = require('path');
const fs = require('fs');
const requireAll = require('require-all');

const configs = new Map(requireAll({
  dirname: path.resolve('config'),
  filter: /\.json$/i,
  recursive: false,
  map: (name, filePath) => path.basename(filePath, '.json'),
}));

process.env.NODE_ENV = 'production';
log.enableAll();

const processes = [];

process.on('exit', killAll);
process.on('SIGINT', killAll);
process.on('SIGTERM', killAll);

const buildLog = fs.createWriteStream(path.resolve('build.log'), { flags: 'w+' });
buildLog.on('open', () => {
  log.info('📦  Generate config files');
  const distDir = path.resolve('dist-configs');
  fs.mkdir(distDir, () => {
    configs.forEach((config, environment) => {
      const file = `${environment}.js`;
      const fileDir = path.join(distDir, file);
      try {
        fs.writeFileSync(fileDir, `var __CONFIG__ = Object.freeze(${JSON.stringify(config)})`);
        log.info(colors.green(`   📄  ${file} generated`));
      } catch (e) {
        log.error(colors.red(`   📄  ${file} could not be generated`));
        buildLog.write(e);
        process.exit(1);
      }
    });

    log.info('📦  Build app');
    const webpack = spawn('node', ['node_modules/webpack/bin/webpack.js', '-p', '--bail', '--progress', '--colors'], { env: process.env, stdio: [buildLog, buildLog, buildLog] });
    processes.push(webpack);
    webpack.on('close', (code) => {
      if (code) {
        log.error(colors.red('   💣  App build failed!'));
        process.exit(code);
      }

      log.info(colors.green('   📦  App built'));
    });
  });
});

function killAll() {
  log.debug(colors.grey('🔪  Will kill all processes'));
  processes.forEach((child) => {
    child.kill('SIGINT');
  });
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var buildify = require('buildify');
var _ = require('lodash');
var fixIife = _.partialRight(_.replace, ';\n(function', ';(function');
var beautify = _.partialRight(require('js-beautify'), {indent_size: 2}); // eslint-disable-line camelcase
var formatDist = _.flow(beautify, fixIife);
var removeComments = _.partialRight(_.replace, /\s\/[*\/][^\*].*/g, '');

var pkg = require('../package.json');
var srcFiles = pkg.config.srcFiles;
var licenseTemplate = 'scripts/license.tmpl.js';
var licenseOptions = {
  version: pkg.version,
  year: (new Date()).getFullYear()
};

buildify()
  .concat(srcFiles)
  .wrap('scripts/umd.tmpl.js')
  .perform(_.flow(removeComments, formatDist))
  .wrap(licenseTemplate, licenseOptions)
  .save('dist/funkey.js')
  .uglify()
  .wrap(licenseTemplate, licenseOptions)
  .save('dist/funkey.min.js');
<commit_msg>Reorder build<commit_after>#!/usr/bin/env node

var buildify = require('buildify');
var _ = require('lodash');

var removeComments = _.partialRight(_.replace, /\s\/[*\/][^\*].*/g, '');
var beautify = _.partialRight(require('js-beautify'), {indent_size: 2}); // eslint-disable-line camelcase
var fixIife = _.partialRight(_.replace, ';\n(function', ';(function');
var formatDist = _.flow(removeComments, beautify, fixIife);

var pkg = require('../package.json');
var srcFiles = pkg.config.srcFiles;
var licenseTemplate = 'scripts/license.tmpl.js';
var licenseOptions = {
  version: pkg.version,
  year: (new Date()).getFullYear()
};

buildify()
  .concat(srcFiles)
  .wrap('scripts/umd.tmpl.js')
  .perform(formatDist)
  .wrap(licenseTemplate, licenseOptions)
  .save('dist/funkey.js')
  .uglify()
  .wrap(licenseTemplate, licenseOptions)
  .save('dist/funkey.min.js');
<|endoftext|>


<commit_before>//Import dependencies
var path = require('path');
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var header = require('gulp-header');
var rename = require('gulp-rename');
var cleanCSS = require('gulp-clean-css');
var sass = require('gulp-sass');
var keue = require('keue');
var rmr = require('rmr');

//Import configuration
var config = require('./config.js');

//Initialize the new keue
var k = new keue(function(next)
{
  //Clean the output directory
  rmr.sync(config.dist);

  //Continue
  return next();
});

//Compile the css files
k.then(function(next)
{
  //Output stream
  var output = gulp.dest(config.dist);

  //Build task completed
  output.on('finish', function()
  {
    //Continue with the next task
    return next();
  });

  //Select all the SCSS files
  return gulp.src('scss/**/*.scss')

  //Build the scss files
  .pipe(sass().on('error', sass.logError))

  //Autoprefix
  .pipe(autoprefixer({ browsers: ['last 3 versions', 'IE 9'], cascade: false }))

  //Add the header
  .pipe(header(config.banner, { } ))

  //Save on the dist folder
  .pipe(output);
});

//Minimize the css files
k.then(function(next)
{
  //Output stream
  var output = gulp.dest(config.dist);

  //Build task completed
  output.on('finish', function()
  {
    //Continue with the next task
    return next();
  });

  //Set the source file
  return gulp.src(path.join(config.dist, './siimple-colors.css'))

  //Clean the css
  .pipe(cleanCSS({ compatibility: '*' }))

  //Rename the file
  .pipe(rename({ extname: '.min.css' }))

  //Add the header
  .pipe(header(config.banner, { } ))

  //Save on the dist folder
  .pipe(output);
});

//Queue finished
k.finish(function()
{
  //Display in console
  console.log('Build completed');
});

<commit_msg>Removed old build script file<commit_after><|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/**
 * script to build (transpile) files.
 * By default it transpiles js files for all packages and writes them
 * into `build/` directory.
 * Non-js files not matching IGNORE_PATTERN will be copied without transpiling.
 *
 * Example:
 *  node ./scripts/build.js
 *  node ./scripts/build.js /users/123/jest/packages/jest-111/src/111.js
 *
 * NOTE: this script is node@6 compatible
 */

'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const makeDir = require('make-dir');

const babel = require('@babel/core');
const chalk = require('chalk');
const micromatch = require('micromatch');
const prettier = require('prettier');
const {getPackages, adjustToTerminalWidth, OK} = require('./buildUtils');
const browserBuild = require('./browserBuild');

const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const BUILD_ES5_DIR = 'build-es5';
const JS_FILES_PATTERN = '**/*.js';
const TS_FILES_PATTERN = '**/*.ts';
const IGNORE_PATTERN = '**/__{tests,mocks}__/**';
const PACKAGES_DIR = path.resolve(__dirname, '../packages');

const INLINE_REQUIRE_BLACKLIST = /packages\/expect|(jest-(circus|diff|get-type|jasmine2|matcher-utils|message-util|regex-util|snapshot))|pretty-format\//;

const transformOptions = require('../babel.config.js');

const prettierConfig = prettier.resolveConfig.sync(__filename);
prettierConfig.trailingComma = 'none';
prettierConfig.parser = 'babel';

function getPackageName(file) {
  return path.relative(PACKAGES_DIR, file).split(path.sep)[0];
}

function getBuildPath(file, buildFolder) {
  const pkgName = getPackageName(file);
  const pkgSrcPath = path.resolve(PACKAGES_DIR, pkgName, SRC_DIR);
  const pkgBuildPath = path.resolve(PACKAGES_DIR, pkgName, buildFolder);
  const relativeToSrcPath = path.relative(pkgSrcPath, file);
  return path.resolve(pkgBuildPath, relativeToSrcPath).replace(/\.ts$/, '.js');
}

function buildNodePackage(p) {
  const srcDir = path.resolve(p, SRC_DIR);
  const pattern = path.resolve(srcDir, '**/*');
  const files = glob.sync(pattern, {nodir: true});

  process.stdout.write(adjustToTerminalWidth(`${path.basename(p)}\n`));

  files.forEach(file => buildFile(file, true));

  process.stdout.write(`${OK}\n`);
}

function buildBrowserPackage(p) {
  const srcDir = path.resolve(p, SRC_DIR);
  const pkgJsonPath = path.resolve(p, 'package.json');

  if (!fs.existsSync(pkgJsonPath)) {
    return;
  }

  const browser = require(pkgJsonPath).browser;
  if (browser) {
    if (browser.indexOf(BUILD_ES5_DIR) !== 0) {
      throw new Error(
        `browser field for ${pkgJsonPath} should start with "${BUILD_ES5_DIR}"`
      );
    }
    let indexFile = path.resolve(srcDir, 'index.js');

    if (!fs.existsSync(indexFile)) {
      indexFile = indexFile.replace(/\.js$/, '.ts');
    }

    browserBuild(p.split('/').pop(), indexFile, path.resolve(p, browser))
      .then(() => {
        process.stdout.write(adjustToTerminalWidth(`${path.basename(p)}\n`));
        process.stdout.write(`${OK}\n`);
      })
      .catch(e => {
        console.error(e);
        process.exit(1);
      });
  }
}

function buildFile(file, silent) {
  const destPath = getBuildPath(file, BUILD_DIR);

  if (micromatch.isMatch(file, IGNORE_PATTERN)) {
    silent ||
      process.stdout.write(
        chalk.dim('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          ' (ignore)\n'
      );
    return;
  }

  makeDir.sync(path.dirname(destPath));
  if (
    !micromatch.isMatch(file, JS_FILES_PATTERN) &&
    !micromatch.isMatch(file, TS_FILES_PATTERN)
  ) {
    fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
    silent ||
      process.stdout.write(
        chalk.red('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          chalk.red(' \u21D2 ') +
          path.relative(PACKAGES_DIR, destPath) +
          ' (copy)' +
          '\n'
      );
  } else {
    const options = Object.assign({}, transformOptions);
    options.plugins = options.plugins.slice();

    if (INLINE_REQUIRE_BLACKLIST.test(file)) {
      // The modules in the blacklist are injected into the user's sandbox
      // We need to guard some globals there.
      options.plugins.push(
        require.resolve('./babel-plugin-jest-native-globals')
      );
    } else {
      options.plugins = options.plugins.map(plugin => {
        if (
          Array.isArray(plugin) &&
          plugin[0] === '@babel/plugin-transform-modules-commonjs'
        ) {
          return [
            plugin[0],
            Object.assign({}, plugin[1], {
              lazy: string =>
                // we want to lazyload all non-local modules plus `importMjs` - the latter to avoid syntax errors. Set to just `true` when we drop support for node 8
                !string.startsWith('./') || string === './importMjs',
            }),
          ];
        }

        return plugin;
      });
    }

    const transformed = babel.transformFileSync(file, options).code;
    const prettyCode = prettier.format(transformed, prettierConfig);

    fs.writeFileSync(destPath, prettyCode);

    silent ||
      process.stdout.write(
        chalk.green('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          chalk.green(' \u21D2 ') +
          path.relative(PACKAGES_DIR, destPath) +
          '\n'
      );
  }
}

const files = process.argv.slice(2);

if (files.length) {
  files.forEach(buildFile);
} else {
  const packages = getPackages();
  process.stdout.write(chalk.inverse(' Building packages \n'));
  packages.forEach(buildNodePackage);
  process.stdout.write('\n');

  process.stdout.write(chalk.inverse(' Building browser packages \n'));
  packages.forEach(buildBrowserPackage);
}
<commit_msg>chore: correct logging in local build watch mode<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/**
 * script to build (transpile) files.
 * By default it transpiles js files for all packages and writes them
 * into `build/` directory.
 * Non-js files not matching IGNORE_PATTERN will be copied without transpiling.
 *
 * Example:
 *  node ./scripts/build.js
 *  node ./scripts/build.js /users/123/jest/packages/jest-111/src/111.js
 *
 * NOTE: this script is node@6 compatible
 */

'use strict';

const fs = require('fs');
const path = require('path');
const glob = require('glob');
const makeDir = require('make-dir');

const babel = require('@babel/core');
const chalk = require('chalk');
const micromatch = require('micromatch');
const prettier = require('prettier');
const {getPackages, adjustToTerminalWidth, OK} = require('./buildUtils');
const browserBuild = require('./browserBuild');

const SRC_DIR = 'src';
const BUILD_DIR = 'build';
const BUILD_ES5_DIR = 'build-es5';
const JS_FILES_PATTERN = '**/*.js';
const TS_FILES_PATTERN = '**/*.ts';
const IGNORE_PATTERN = '**/__{tests,mocks}__/**';
const PACKAGES_DIR = path.resolve(__dirname, '../packages');

const INLINE_REQUIRE_BLACKLIST = /packages\/expect|(jest-(circus|diff|get-type|jasmine2|matcher-utils|message-util|regex-util|snapshot))|pretty-format\//;

const transformOptions = require('../babel.config.js');

const prettierConfig = prettier.resolveConfig.sync(__filename);
prettierConfig.trailingComma = 'none';
prettierConfig.parser = 'babel';

function getPackageName(file) {
  return path.relative(PACKAGES_DIR, file).split(path.sep)[0];
}

function getBuildPath(file, buildFolder) {
  const pkgName = getPackageName(file);
  const pkgSrcPath = path.resolve(PACKAGES_DIR, pkgName, SRC_DIR);
  const pkgBuildPath = path.resolve(PACKAGES_DIR, pkgName, buildFolder);
  const relativeToSrcPath = path.relative(pkgSrcPath, file);
  return path.resolve(pkgBuildPath, relativeToSrcPath).replace(/\.ts$/, '.js');
}

function buildNodePackage(p) {
  const srcDir = path.resolve(p, SRC_DIR);
  const pattern = path.resolve(srcDir, '**/*');
  const files = glob.sync(pattern, {nodir: true});

  process.stdout.write(adjustToTerminalWidth(`${path.basename(p)}\n`));

  files.forEach(file => buildFile(file, true));

  process.stdout.write(`${OK}\n`);
}

function buildBrowserPackage(p) {
  const srcDir = path.resolve(p, SRC_DIR);
  const pkgJsonPath = path.resolve(p, 'package.json');

  if (!fs.existsSync(pkgJsonPath)) {
    return;
  }

  const browser = require(pkgJsonPath).browser;
  if (browser) {
    if (browser.indexOf(BUILD_ES5_DIR) !== 0) {
      throw new Error(
        `browser field for ${pkgJsonPath} should start with "${BUILD_ES5_DIR}"`
      );
    }
    let indexFile = path.resolve(srcDir, 'index.js');

    if (!fs.existsSync(indexFile)) {
      indexFile = indexFile.replace(/\.js$/, '.ts');
    }

    browserBuild(p.split('/').pop(), indexFile, path.resolve(p, browser))
      .then(() => {
        process.stdout.write(adjustToTerminalWidth(`${path.basename(p)}\n`));
        process.stdout.write(`${OK}\n`);
      })
      .catch(e => {
        console.error(e);
        process.exit(1);
      });
  }
}

function buildFile(file, silent) {
  const destPath = getBuildPath(file, BUILD_DIR);

  if (micromatch.isMatch(file, IGNORE_PATTERN)) {
    silent ||
      process.stdout.write(
        chalk.dim('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          ' (ignore)\n'
      );
    return;
  }

  makeDir.sync(path.dirname(destPath));
  if (
    !micromatch.isMatch(file, JS_FILES_PATTERN) &&
    !micromatch.isMatch(file, TS_FILES_PATTERN)
  ) {
    fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
    silent ||
      process.stdout.write(
        chalk.red('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          chalk.red(' \u21D2 ') +
          path.relative(PACKAGES_DIR, destPath) +
          ' (copy)' +
          '\n'
      );
  } else {
    const options = Object.assign({}, transformOptions);
    options.plugins = options.plugins.slice();

    if (INLINE_REQUIRE_BLACKLIST.test(file)) {
      // The modules in the blacklist are injected into the user's sandbox
      // We need to guard some globals there.
      options.plugins.push(
        require.resolve('./babel-plugin-jest-native-globals')
      );
    } else {
      options.plugins = options.plugins.map(plugin => {
        if (
          Array.isArray(plugin) &&
          plugin[0] === '@babel/plugin-transform-modules-commonjs'
        ) {
          return [
            plugin[0],
            Object.assign({}, plugin[1], {
              lazy: string =>
                // we want to lazyload all non-local modules plus `importMjs` - the latter to avoid syntax errors. Set to just `true` when we drop support for node 8
                !string.startsWith('./') || string === './importMjs',
            }),
          ];
        }

        return plugin;
      });
    }

    const transformed = babel.transformFileSync(file, options).code;
    const prettyCode = prettier.format(transformed, prettierConfig);

    fs.writeFileSync(destPath, prettyCode);

    silent ||
      process.stdout.write(
        chalk.green('  \u2022 ') +
          path.relative(PACKAGES_DIR, file) +
          chalk.green(' \u21D2 ') +
          path.relative(PACKAGES_DIR, destPath) +
          '\n'
      );
  }
}

const files = process.argv.slice(2);

if (files.length) {
  files.forEach(file => buildFile(file));
} else {
  const packages = getPackages();
  process.stdout.write(chalk.inverse(' Building packages \n'));
  packages.forEach(buildNodePackage);
  process.stdout.write('\n');

  process.stdout.write(chalk.inverse(' Building browser packages \n'));
  packages.forEach(buildBrowserPackage);
}
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const lib = require('./lib.js');
const parseCSVString = lib.parseCSVString;
const findDuplicates = lib.findDuplicates;
const objArrToString = lib.objArrToString;
const args = process.argv;
const isTestRun = !!args.find((arg) => (arg === '--testOnly'));
const exec = require('child_process').exec;

// only hex colors with 6 values
const hexColorValidation = /^#[0-9a-f]{6}$/;
const errors = [];

// spaces regex
const spacesValidation = /^\s+|\s{2,}|\s$/;

// setting
const baseFolder = __dirname + '/../';
const folderSrc = 'src/';
const folderDist = 'dist/';
const fileNameSrc = 'colornames';
const readmeFileName = 'README.md';

const sortBy = 'name';
const csvKeys = ['name', 'hex'];

// reads the CSV file contents
const src = fs.readFileSync(
    path.normalize(`${baseFolder}${folderSrc}${fileNameSrc}.csv`),
    'utf8'
).toString();
const colorsSrc = parseCSVString(src);

// sort by sorting criteria
colorsSrc.entires.sort((a, b) => {
  return a[sortBy].localeCompare(b[sortBy]);
});

csvKeys.forEach((key) => {
  // find duplicates
  const dupes = findDuplicates(colorsSrc.values[key]);
  dupes.forEach((dupe) => {
    log(key, dupe, `found a double ${key}`);
  });
});

// loop hex values
colorsSrc.values['hex'].forEach((hex) => {
  // validate HEX values
  if ( !hexColorValidation.test(hex) ) {
    log('hex', hex, `${hex} is not a valid hex value. (Or to short, we avoid using the hex shorthands, no capital letters)`);
  }
});

// loop names
colorsSrc.values['name'].forEach((name) => {
  // check for spaces
  if (spacesValidation.test(name)) {
    log('name', name, `${name} found either a leading or trailing space (or both)`);
  }
});

showLog();

if (isTestRun) {
  console.log('⇪ See test results above ⇪');
  process.exit();
}

// creates JS related files
const JSONExportString = JSON.stringify(colorsSrc.entires);

fs.writeFileSync(
    path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.json`),
    JSONExportString
);

// creates a more compact JSON file, where the HEX color serves as an id
const miniJSONExportObj = colorsSrc.entires.reduce((obj, entry) => {
  obj[entry.hex.replace('#', '')] = entry.name;
  return obj;
}, {});

fs.writeFileSync(
  path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.min.json`),
  JSON.stringify(miniJSONExportObj)
);

// gets UMD template
const umdTpl = fs.readFileSync(
    path.normalize(__dirname + '/umd.js.tpl'),
    'utf8'
).toString();

// create UMD
fs.writeFileSync(
    path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.umd.js`),
    umdTpl.replace('"{{COLORS}}"', JSONExportString)
);

// create foreign formats
// configuration for the file outputs
const outputFormats = {
  'csv': {
    insertBefore: csvKeys.join(',') + '\r\n',
  },
  'yaml': {
    insertBefore: '-\r\n  ',
    beforeValue: '"',
    afterValue: '"',
    includeKeyPerItem: true,
    rowDelimitor: '\r\n-\r\n  ',
    itemDelimitor: '\r\n  ',
  },
  'scss': {
    insertBefore: '$color-name-list: (',
    beforeValue: '"',
    afterValue: '"',
    insertAfter: ');',
    itemDelimitor: ':',
    rowDelimitor: ',',
  },
  'css': {
    insertBefore: ':root{\r\n--color-',
    beforeValue: '',
    afterValue: '',
    insertAfter: '};',
    itemDelimitor: ':',
    rowDelimitor: ';\r\n--color-',
  },
  'html': {
    insertBefore: `<table><thead><tr><th>${csvKeys.join('</th><th>')}</th></tr><thead><tbody><tr><td>`,
    itemDelimitor: '	',
    rowDelimitor: '

',
    insertAfter: `</td></tr></tbody></table>`,
  },
  'xml': {
    insertBefore: `<?xml version='1.0'?>\r\n<colors>\r\n<color>\r\n<${csvKeys[0]}>`,
    itemDelimitor: `</${csvKeys[0]}>\r\n<${csvKeys[1]}>`,
    rowDelimitor: `</${csvKeys[1]}>\r\n</color>\r\n<color>\r\n<${csvKeys[0]}>`,
    insertAfter: `</${csvKeys[1]}>\r\n</color>\r\n</colors>`,
  },
};

for (const outputFormat in outputFormats) {
  if (outputFormats[outputFormat]) {
    let outputString = objArrToString(
        colorsSrc.entires,
        csvKeys,
        outputFormats[outputFormat]
    );
    if (outputFormat === 'html' || outputFormat === 'xml') {
      outputString = outputString.replace(/&/g, '&');
    }
    if (outputFormat === 'css') {
      outputString = outputString.toLowerCase();
      outputString = outputString.replace(/'/g, '');
      outputString = outputString.replace(/ /g, '-');
      outputString = outputString.replace(/&/g, 'and');
      outputString = outputString.replace(/%/g, 'percent');
    }
    fs.writeFileSync(
        path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.${outputFormat}`),
        outputString
    );
  }
}

// updates the color count in readme file
const readme = fs.readFileSync(
    path.normalize(`${baseFolder}${readmeFileName}`),
    'utf8'
).toString();
fs.writeFileSync(
    path.normalize(`${baseFolder}${readmeFileName}`),
    readme.replace(/__\d+__/g, `__${colorsSrc.entires.length}__`)
        .replace(
            /\d+-colors-orange/,
            `${colorsSrc.entires.length}-colors-orange`
        ).replace(
            /__\d+(\.\d+)?%__/,
            `__${((colorsSrc.entires.length / (256 * 256 * 256)) * 100).toFixed(2)}%__`
        ), 'utf8'
);

/**
 * outputs the collected logs
 */
function showLog() {
  let totalErrors = 0;
  errors.forEach((error, i) => {
    totalErrors = i + 1;
    errorLevel = error.errorLevel || errorLevel;
    console.log(`${error.errorLevel ? '⛔' : '⚠'}  ${error.message}`);
    console.log(JSON.stringify(error.entries));
    console.log('*-------------------------*');
  });
  if (errorLevel) {
    throw `⚠ failed because of the ${totalErrors} error${totalErrors > 1 ? 's' : ''} above ⚠`;
  }
  return totalErrors;
}

/**
 * logs errors and warning
 * @param   {string} key        key to look for in input
 * @param   {string} value      value to look for
 * @param   {string} message    error message
 * @param   {Number} errorLevel if any error is set to 1, the program will exit
 */
function log(key, value, message, errorLevel = 1) {
  const error = {};
  // looks for the original item that caused the error
  error.entries = colorsSrc.entires.filter((entry) => {
    return entry[key] === value;
  });

  error.message = message;
  error.errorLevel = errorLevel;

  errors.push(error);
}

// gets SVG template
const svgTpl = fs.readFileSync(
  path.normalize(__dirname + '/changes.svg.tpl'),
  'utf8'
).toString();

function diffSVG() {
  exec(`git diff HEAD ${baseFolder}${folderSrc}${fileNameSrc}.csv`,
  function (err, stdout, stderr) {
    const diffTxt = stdout;
    if (!/(?<=^[\+])[^\+].*/gm.test(diffTxt)) return;
    const changes = diffTxt.match(/(?<=^[\+])[^\+].*/gm).filter(i => i);
    const svgTxtStr = changes.reduce((str, change, i) => {
      const changeParts = change.split(',');
      return `${str}<text x="40" y="${20 + (i + 1) * 70}" fill="${changeParts[1]}">${changeParts[0]}</text>`;
    }, '');

    fs.writeFileSync(
      path.normalize(`${baseFolder}changes.svg`),
      svgTpl.replace(/{height}/g, changes.length * 70 + 80).replace(/{items}/g, svgTxtStr)
    );
  });
};

diffSVG();
<commit_msg>test(colors): fixes showLog functions in tests<commit_after>const fs = require('fs');
const path = require('path');
const lib = require('./lib.js');
const parseCSVString = lib.parseCSVString;
const findDuplicates = lib.findDuplicates;
const objArrToString = lib.objArrToString;
const args = process.argv;
const isTestRun = !!args.find((arg) => (arg === '--testOnly'));
const exec = require('child_process').exec;

// only hex colors with 6 values
const hexColorValidation = /^#[0-9a-f]{6}$/;
const errors = [];

// spaces regex
const spacesValidation = /^\s+|\s{2,}|\s$/;

// setting
const baseFolder = __dirname + '/../';
const folderSrc = 'src/';
const folderDist = 'dist/';
const fileNameSrc = 'colornames';
const readmeFileName = 'README.md';

const sortBy = 'name';
const csvKeys = ['name', 'hex'];

// reads the CSV file contents
const src = fs.readFileSync(
    path.normalize(`${baseFolder}${folderSrc}${fileNameSrc}.csv`),
    'utf8'
).toString();
const colorsSrc = parseCSVString(src);

// sort by sorting criteria
colorsSrc.entires.sort((a, b) => {
  return a[sortBy].localeCompare(b[sortBy]);
});

csvKeys.forEach((key) => {
  // find duplicates
  const dupes = findDuplicates(colorsSrc.values[key]);
  dupes.forEach((dupe) => {
    log(key, dupe, `found a double ${key}`);
  });
});

// loop hex values
colorsSrc.values['hex'].forEach((hex) => {
  // validate HEX values
  if ( !hexColorValidation.test(hex) ) {
    log('hex', hex, `${hex} is not a valid hex value. (Or to short, we avoid using the hex shorthands, no capital letters)`);
  }
});

// loop names
colorsSrc.values['name'].forEach((name) => {
  // check for spaces
  if (spacesValidation.test(name)) {
    log('name', name, `${name} found either a leading or trailing space (or both)`);
  }
});

showLog();

if (isTestRun) {
  console.log('⇪ See test results above ⇪');
  process.exit();
}

// creates JS related files
const JSONExportString = JSON.stringify(colorsSrc.entires);

fs.writeFileSync(
    path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.json`),
    JSONExportString
);

// creates a more compact JSON file, where the HEX color serves as an id
const miniJSONExportObj = colorsSrc.entires.reduce((obj, entry) => {
  obj[entry.hex.replace('#', '')] = entry.name;
  return obj;
}, {});

fs.writeFileSync(
  path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.min.json`),
  JSON.stringify(miniJSONExportObj)
);

// gets UMD template
const umdTpl = fs.readFileSync(
    path.normalize(__dirname + '/umd.js.tpl'),
    'utf8'
).toString();

// create UMD
fs.writeFileSync(
    path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.umd.js`),
    umdTpl.replace('"{{COLORS}}"', JSONExportString)
);

// create foreign formats
// configuration for the file outputs
const outputFormats = {
  'csv': {
    insertBefore: csvKeys.join(',') + '\r\n',
  },
  'yaml': {
    insertBefore: '-\r\n  ',
    beforeValue: '"',
    afterValue: '"',
    includeKeyPerItem: true,
    rowDelimitor: '\r\n-\r\n  ',
    itemDelimitor: '\r\n  ',
  },
  'scss': {
    insertBefore: '$color-name-list: (',
    beforeValue: '"',
    afterValue: '"',
    insertAfter: ');',
    itemDelimitor: ':',
    rowDelimitor: ',',
  },
  'css': {
    insertBefore: ':root{\r\n--color-',
    beforeValue: '',
    afterValue: '',
    insertAfter: '};',
    itemDelimitor: ':',
    rowDelimitor: ';\r\n--color-',
  },
  'html': {
    insertBefore: `<table><thead><tr><th>${csvKeys.join('</th><th>')}</th></tr><thead><tbody><tr><td>`,
    itemDelimitor: '	',
    rowDelimitor: '

',
    insertAfter: `</td></tr></tbody></table>`,
  },
  'xml': {
    insertBefore: `<?xml version='1.0'?>\r\n<colors>\r\n<color>\r\n<${csvKeys[0]}>`,
    itemDelimitor: `</${csvKeys[0]}>\r\n<${csvKeys[1]}>`,
    rowDelimitor: `</${csvKeys[1]}>\r\n</color>\r\n<color>\r\n<${csvKeys[0]}>`,
    insertAfter: `</${csvKeys[1]}>\r\n</color>\r\n</colors>`,
  },
};

for (const outputFormat in outputFormats) {
  if (outputFormats[outputFormat]) {
    let outputString = objArrToString(
        colorsSrc.entires,
        csvKeys,
        outputFormats[outputFormat]
    );
    if (outputFormat === 'html' || outputFormat === 'xml') {
      outputString = outputString.replace(/&/g, '&');
    }
    if (outputFormat === 'css') {
      outputString = outputString.toLowerCase();
      outputString = outputString.replace(/'/g, '');
      outputString = outputString.replace(/ /g, '-');
      outputString = outputString.replace(/&/g, 'and');
      outputString = outputString.replace(/%/g, 'percent');
    }
    fs.writeFileSync(
        path.normalize(`${baseFolder}${folderDist}${fileNameSrc}.${outputFormat}`),
        outputString
    );
  }
}

// updates the color count in readme file
const readme = fs.readFileSync(
    path.normalize(`${baseFolder}${readmeFileName}`),
    'utf8'
).toString();
fs.writeFileSync(
    path.normalize(`${baseFolder}${readmeFileName}`),
    readme.replace(/__\d+__/g, `__${colorsSrc.entires.length}__`)
        .replace(
            /\d+-colors-orange/,
            `${colorsSrc.entires.length}-colors-orange`
        ).replace(
            /__\d+(\.\d+)?%__/,
            `__${((colorsSrc.entires.length / (256 * 256 * 256)) * 100).toFixed(2)}%__`
        ), 'utf8'
);

/**
 * outputs the collected logs
 */
function showLog() {
  let errorLevel = 0;
  let totalErrors = 0;
  errors.forEach((error, i) => {
    totalErrors = i + 1;
    errorLevel = error.errorLevel || errorLevel;
    console.log(`${error.errorLevel ? '⛔' : '⚠'}  ${error.message}`);
    console.log(JSON.stringify(error.entries));
    console.log('*-------------------------*');
  });
  if (errorLevel) {
    throw `⚠ failed because of the ${totalErrors} error${totalErrors > 1 ? 's' : ''} above ⚠`;
  }
  return totalErrors;
}

/**
 * logs errors and warning
 * @param   {string} key        key to look for in input
 * @param   {string} value      value to look for
 * @param   {string} message    error message
 * @param   {Number} errorLevel if any error is set to 1, the program will exit
 */
function log(key, value, message, errorLevel = 1) {
  const error = {};
  // looks for the original item that caused the error
  error.entries = colorsSrc.entires.filter((entry) => {
    return entry[key] === value;
  });

  error.message = message;
  error.errorLevel = errorLevel;

  errors.push(error);
}

// gets SVG template
const svgTpl = fs.readFileSync(
  path.normalize(__dirname + '/changes.svg.tpl'),
  'utf8'
).toString();

function diffSVG() {
  exec(`git diff HEAD ${baseFolder}${folderSrc}${fileNameSrc}.csv`,
  function (err, stdout, stderr) {
    const diffTxt = stdout;
    if (!/(?<=^[\+])[^\+].*/gm.test(diffTxt)) return;
    const changes = diffTxt.match(/(?<=^[\+])[^\+].*/gm).filter(i => i);
    const svgTxtStr = changes.reduce((str, change, i) => {
      const changeParts = change.split(',');
      return `${str}<text x="40" y="${20 + (i + 1) * 70}" fill="${changeParts[1]}">${changeParts[0]}</text>`;
    }, '');

    fs.writeFileSync(
      path.normalize(`${baseFolder}changes.svg`),
      svgTpl.replace(/{height}/g, changes.length * 70 + 80).replace(/{items}/g, svgTxtStr)
    );
  });
};

diffSVG();
<|endoftext|>


<commit_before>process.chdir(__dirname)

var fs = require('fs')
var sass = require('node-sass')
var CleanCSS = require('clean-css')
var pkg = require('../package.json')

sass.render({
  file: '../source/top-bar.scss'
}, buildCSS)

function buildCSS (err, result) {
  if (err) {
    console.error(err)
    process.exit(1)
  }

  var style = new CleanCSS().minify(result.css).styles
  var banner = '/* ' + pkg.name + ' v' + pkg.version + ' - ' +
    pkg.license + ' License - ' + pkg.homepage + ' */\n'

  fs.writeFile('../top-bar.css', banner + style, function (err) {
    if (err) throw err
    console.log('built top-bar.css')
  })
}

function getDate () {
  var d = new Date()
  var dd = d.getDate()
  var mm = d.getMonth() + 1
  var yyyy = d.getFullYear()

  if (dd < 10) dd = '0' + dd
  if (mm < 10) mm = '0' + mm

  return mm + '/' + dd + '/' + ('' + yyyy).substr(2)
}
<commit_msg>remove unused function<commit_after>process.chdir(__dirname)

var fs = require('fs')
var sass = require('node-sass')
var CleanCSS = require('clean-css')
var pkg = require('../package.json')

sass.render({
  file: '../source/top-bar.scss'
}, buildCSS)

function buildCSS (err, result) {
  if (err) {
    console.error(err)
    process.exit(1)
  }

  var style = new CleanCSS().minify(result.css).styles
  var banner = '/* ' + pkg.name + ' v' + pkg.version + ' - ' +
    pkg.license + ' License - ' + pkg.homepage + ' */\n'

  fs.writeFile('../top-bar.css', banner + style, function (err) {
    if (err) throw err
    console.log('built top-bar.css')
  })
}
<|endoftext|>


<commit_before>var errz = {
  "202":"Accepted",
  "502":"Bad Gateway",
  "400":"Bad Request",
  "409":"Conflict",
  "100":"Continue",
  "201":"Created",
  "417":"Expectation Failed",
  "424":"Failed Dependency",
  "403":"Forbidden",
  "504":"Gateway Timeout",
  "410":"Gone",
  "505":"HTTP Version Not Supported",
  "418":"I'm a teapot",
  "419":"Insufficient Space on Resource",
  "507":"Insufficient Storage",
  "500":"Server Error",
  "411":"Length Required",
  "423":"Locked",
  "420":"Method Failure",
  "405":"Method Not Allowed",
  "301":"Moved Permanently",
  "302":"Moved Temporarily",
  "207":"Multi-Status",
  "300":"Multiple Choices",
  "511":"Network Authentication Required",
  "204":"No Content",
  "203":"Non Authoritative Information",
  "406":"Not Acceptable",
  "404":"Not Found",
  "501":"Not Implemented",
  "304":"Not Modified",
  "200":"OK",
  "206":"Partial Content",
  "402":"Payment Required",
  "308":"Permanent Redirect",
  "412":"Precondition Failed",
  "428":"Precondition Required",
  "102":"Processing",
  "407":"Proxy Authentication Required",
  "431":"Request Header Fields Too Large",
  "408":"Request Timeout",
  "413":"Request Entity Too Large",
  "414":"Request-URI Too Long",
  "416":"Requested Range Not Satisfiable",
  "205":"Reset Content",
  "303":"See Other",
  "503":"Service Unavailable",
  "101":"Switching Protocols",
  "307":"Temporary Redirect",
  "429":"Too Many Requests",
  "401":"Unauthorized",
  "422":"Unprocessable Entity",
  "415":"Unsupported Media Type",
  "305":"Use Proxy"
}

listen(regexFactory.startsWith(["error","err","fail"]), function (match, data, replyTo, from) {
	var str = match[1];
  str = str.trim()
	if (str === 'help') {
		irc.privmsg(replyTo, ' ~> help: http error values');
		return;
	}
  if (!str.length) {
    str = errz[Object.keys(errz)[Math.floor(Math.random() * Object.keys(errz).length)]]
  }
  var found_string = errz[str]
  if (found_string) {
    irc.privmsg(replyTo, found_string);
  } else {
    irc.privmsg(replyTo, ' ~> error ' + msg + ' not found');
  }
});
<commit_msg>error codes script added fixfix<commit_after>var errz = {
  "202":"Accepted",
  "502":"Bad Gateway",
  "400":"Bad Request",
  "409":"Conflict",
  "100":"Continue",
  "201":"Created",
  "417":"Expectation Failed",
  "424":"Failed Dependency",
  "403":"Forbidden",
  "504":"Gateway Timeout",
  "410":"Gone",
  "505":"HTTP Version Not Supported",
  "418":"I'm a teapot",
  "419":"Insufficient Space on Resource",
  "507":"Insufficient Storage",
  "500":"Server Error",
  "411":"Length Required",
  "423":"Locked",
  "420":"Method Failure",
  "405":"Method Not Allowed",
  "301":"Moved Permanently",
  "302":"Moved Temporarily",
  "207":"Multi-Status",
  "300":"Multiple Choices",
  "511":"Network Authentication Required",
  "204":"No Content",
  "203":"Non Authoritative Information",
  "406":"Not Acceptable",
  "404":"Not Found",
  "501":"Not Implemented",
  "304":"Not Modified",
  "200":"OK",
  "206":"Partial Content",
  "402":"Payment Required",
  "308":"Permanent Redirect",
  "412":"Precondition Failed",
  "428":"Precondition Required",
  "102":"Processing",
  "407":"Proxy Authentication Required",
  "431":"Request Header Fields Too Large",
  "408":"Request Timeout",
  "413":"Request Entity Too Large",
  "414":"Request-URI Too Long",
  "416":"Requested Range Not Satisfiable",
  "205":"Reset Content",
  "303":"See Other",
  "503":"Service Unavailable",
  "101":"Switching Protocols",
  "307":"Temporary Redirect",
  "429":"Too Many Requests",
  "401":"Unauthorized",
  "422":"Unprocessable Entity",
  "415":"Unsupported Media Type",
  "305":"Use Proxy"
}

listen(regexFactory.startsWith(["error","err","fail"]), function (match, data, replyTo, from) {
	var str = match[1];
  str = str.trim()
	if (str === 'help') {
		irc.privmsg(replyTo, ' ~> help: http error values');
		return;
	}
  if (!str.length) {
    str = errz[Object.keys(errz)[Math.floor(Math.random() * Object.keys(errz).length)]]
  }
  var found_string = errz[str]
  if (found_string) {
    irc.privmsg(replyTo, found_string);
  } else {
    irc.privmsg(replyTo, ' ~> error ' + str + ' not found');
  }
});
<|endoftext|>


<commit_before>"use strict";function t(t){return t&&t.__esModule?t:{default:t}}function e(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),r=require("crypto"),i=t(r),u=require("path"),a=t(u),s=require("execa"),o=t(s),l=require("glob"),c=t(l),f=require("fs-jetpack"),h=t(f),d=require("listr"),p=t(d),g=require("mkdirp"),v=t(g),m=require("xdg-basedir"),y=t(m),z=a.default.join(y.default.data,"zsh_plugins");(0,v.default)(z),Array.prototype.includes||(Array.prototype.includes=function(t){var e=Object(this),n=parseInt(e.length,10)||0;if(0===n)return!1;var r=parseInt(arguments[1],10)||0,i=void 0;r>=0?i=r:(i=n+r,i<0&&(i=0));for(var u=void 0;i<n;){if(u=e[i],t===u||t!==t&&u!==u)return!0;i++}return!1});var w=["Tarrasch/zsh-colors","zsh-users/zsh-syntax-highlighting","zsh-users/zsh-history-substring-search","zsh-users/zsh-completions","mafredri/zsh-async","sindresorhus/pure"],j=function(){function t(n){e(this,t),this.name=n;var r=i.default.createHash("sha1");r.update(n),this.hash=r.digest("hex")}return n(t,[{key:"clonePath",get:function(){return a.default.join(z,this.hash)}}]),t}(),k=[],b=[],q=new p.default([{title:"Getting Paths for Cloning",task:function(){w=w.map(function(t){return new j(t)})}},{title:"Cleaning up",task:function(){var t=w.map(function(t){return t.hash});t.push("plugins.zsh");var e=h.default.list(z);e&&e.filter(function(e){return!t.includes(e)}).forEach(function(t){return h.default.remove(a.default.join(z,t))})}},{title:"Cloning Plugins",task:function(){return new p.default(w.map(function(t){var e=t.name,n=t.clonePath;return{title:"Cloning "+e+"...",task:function(){switch(h.default.exists(a.default.join(n,".git"))){case!1:return h.default.exists(n)&&h.default.remove(n),(0,o.default)("git",["clone","--recursive","--","https://github.com/"+e+".git",n]);case"dir":return o.default.sync("git",["fetch","--all"],{cwd:n}),(0,o.default)("git",["reset","--hard","origin/master","--"],{cwd:n});default:throw new Error("Invalid clone target!")}}}}),{concurrent:!0})}},{title:"Getting zsh File ready",task:function(){return new p.default(w.map(function(t){return{title:"Getting "+t.name+" ready...",task:function(){var e=t.name.split("/")[1],n=[e+".plugin.zsh","*.plugin.zsh","init.zsh","*.zsh","*.sh"];b.push(t.clonePath);for(var r=0;r<n.length;r++){var i=c.default.sync(a.default.join(t.clonePath,n[r]));if(0!==i.length){k.push(i[0]);break}}}}}),{concurrent:!0})}},{title:"Writing "+a.default.join(z,"plugins.zsh"),task:function(){return h.default.writeAsync(a.default.join(z,"plugins.zsh"),k.map(function(t){return"source "+t}).join("\n")+"\n"+b.map(function(t){return"fpath+="+t}).join("\n"))}}]);q.run().catch(function(t){console.error(t),process.exit(1)});
<commit_msg>rebuild<commit_after>"use strict";function e(e){return e&&e.__esModule?e:{default:e}}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var n=function(){function e(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}(),r=require("crypto"),i=e(r),u=require("path"),a=e(u),s=require("execa"),o=e(s),l=require("glob"),c=e(l),f=require("fs-jetpack"),h=e(f),d=require("lodash.includes"),g=e(d),p=require("listr"),m=e(p),z=require("mkdirp"),v=e(z),y=require("xdg-basedir"),w=e(y),k=a.default.join(w.default.data,"zsh_plugins");(0,v.default)(k);var j=["Tarrasch/zsh-colors","zsh-users/zsh-syntax-highlighting","zsh-users/zsh-history-substring-search","zsh-users/zsh-completions","mafredri/zsh-async","sindresorhus/pure"],b=function(){function e(n){t(this,e),this.name=n;var r=i.default.createHash("sha1");r.update(n),this.hash=r.digest("hex")}return n(e,[{key:"clonePath",get:function(){return a.default.join(k,this.hash)}}]),e}(),q=[],x=[],P=new m.default([{title:"Getting Paths for Cloning",task:function(){j=j.map(function(e){return new b(e)})}},{title:"Cleaning up",task:function(){var e=j.map(function(e){return e.hash});e.push("plugins.zsh");var t=h.default.list(k);t&&t.filter(function(t){return!(0,g.default)(e,t)}).forEach(function(e){return h.default.remove(a.default.join(k,e))})}},{title:"Cloning Plugins",task:function(){return new m.default(j.map(function(e){var t=e.name,n=e.clonePath;return{title:"Cloning "+t+"...",task:function(){switch(h.default.exists(a.default.join(n,".git"))){case!1:return h.default.exists(n)&&h.default.remove(n),(0,o.default)("git",["clone","--recursive","--","https://github.com/"+t+".git",n]);case"dir":return o.default.sync("git",["fetch","--all"],{cwd:n}),(0,o.default)("git",["reset","--hard","origin/master","--"],{cwd:n});default:throw new Error("Invalid clone target!")}}}}),{concurrent:!0})}},{title:"Getting zsh File ready",task:function(){return new m.default(j.map(function(e){return{title:"Getting "+e.name+" ready...",task:function(){var t=e.name.split("/")[1],n=[t+".plugin.zsh","*.plugin.zsh","init.zsh","*.zsh","*.sh"];x.push(e.clonePath);for(var r=0;r<n.length;r++){var i=c.default.sync(a.default.join(e.clonePath,n[r]));if(0!==i.length){q.push(i[0]);break}}}}}),{concurrent:!0})}},{title:"Writing "+a.default.join(k,"plugins.zsh"),task:function(){return h.default.writeAsync(a.default.join(k,"plugins.zsh"),q.map(function(e){return"source "+e}).join("\n")+"\n"+x.map(function(e){return"fpath+="+e}).join("\n"))}}]);P.run().catch(function(e){console.error(e),process.exit(1)});
<|endoftext|>