<commit_before>import React, { Component } from 'react';
import TestUtils from 'react-dom/test-utils';
import createResa, { Provider, connect } from './..';

const model = {
    namespace: 'model',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield reject(action.payload);
        },
    },
};

describe('Connect', () => {
    class Child extends Component { // eslint-disable-line
        render() {
            return <div />;
        }
    }

    test('should pass state and props to the given component', () => {
        const app = createResa();

        const mapStateToProps = (app, state) => {
            return {
                a: 'a',
            }
        }

        const func = () => {};

        const mapDispatchToProps = (app, dispatch) => ({
            func: func,
        })

        const ConnectedChild = connect(mapStateToProps, mapDispatchToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.a).toEqual('a');
        expect(container.props.func).toEqual(func);
    });

    test('mapStateToProps can get app and state', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });

        const mapStateToProps = (app, state) => {
            return {
                a: state.model.a,
                loading: app.store.getState().model.loading,
            }
        }

        const ConnectedChild = connect(mapStateToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.a).toEqual('a');
        expect(container.props.loading).toEqual(false);
    });

    test('mapDispatchToProps can get app and dispatch', () => {
        const app = createResa();
        const mapDispatchToProps = (app, dispatch) => ({
            func: () => {
                return {
                    app,
                    dispatch,
                };
            },
        })

        const ConnectedChild = connect(null, mapDispatchToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.func()).toEqual({
            app,
            dispatch: app.store.dispatch,
        });
    });
});
<commit_msg>fix lint<commit_after>import React, { Component } from 'react';
import TestUtils from 'react-dom/test-utils';
import createResa, { Provider, connect } from './..';

const model = {
    namespace: 'model',
    reducer: 'model',
    effects: {
        * add(_app, action, { fulfilled, _reject }) {
            yield fulfilled(action.payload);
        },

        * minus(_app, action, { _fulfilled, reject }) {
            yield reject(action.payload);
        },
    },
};

describe('Connect', () => {
    class Child extends Component { // eslint-disable-line
        render() {
            return <div />;
        }
    }

    test('should pass state and props to the given component', () => {
        const app = createResa();

        const mapStateToProps = (_app, _state) => ({
            a: 'a',
        });

        const func = () => { };

        const mapDispatchToProps = (_app, _dispatch) => ({
            func,
        });

        const ConnectedChild = connect(mapStateToProps, mapDispatchToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.a).toEqual('a');
        expect(container.props.func).toEqual(func);
    });

    test('mapStateToProps can get app and state', () => {
        const app = createResa();
        app.registerModel(model);
        app.model.model.effects.add({ a: 'a' });

        const mapStateToProps = (resa, state) => ({
            a: state.model.a,
            loading: resa.model.model.getState().loading,
        });

        const ConnectedChild = connect(mapStateToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.a).toEqual('a');
        expect(container.props.loading).toEqual(false);
    });

    test('mapDispatchToProps can get app and dispatch', () => {
        const app = createResa();
        const mapDispatchToProps = (resa, dispatch) => ({
            func: () => ({
                app: resa,
                dispatch,
            }),
        });

        const ConnectedChild = connect(null, mapDispatchToProps)(Child);

        const tree = TestUtils.renderIntoDocument(
            <Provider store={app.store} resa={app}>
                <ConnectedChild />
            </Provider>
        );

        const container = TestUtils.findRenderedComponentWithType(tree, Child);
        expect(container.props.func()).toEqual({
            app,
            dispatch: app.store.dispatch,
        });
    });
});
<|endoftext|>


<commit_before>define([
    "jquery",
    "base1/cockpit"
], function($, cockpit) {
    var module = { };

    function Machine(machines) {
        var self = this;
        var proxy = null;
        var hostnamed = null;
        var channel = null;

        self.state = null;

        function change_state(value, problem) {
            self.state = value;
            self.problem = problem;
            $(machines).triggerHandler("changed", self);
        }

        function disconnect() {
            $(channel).off();
            channel.close();
            channel = null;

            if (hostnamed) {
                $(hostnamed).off();
                hostnamed.client.close();
                hostnamed = null;
            }
        }

        self.connect = function connect(force) {
            if (channel && force)
                disconnect();
            if (channel)
                return;

            if (!self.address) {
                change_state("failed", "no-host");
                return;
            }

            channel = cockpit.channel({ host: self.address, payload: "echo" });
            $(channel)
                .on("message", function() {
                    change_state("connected", null);
                })
                .on("close", function(options) {
                    var problem = options.problem || "disconnected";
                    change_state("failed", problem);
                    disconnect();
                });

            /* So we get back a message once connected */
            channel.send("x");

            hostnamed = cockpit.dbus("org.freedesktop.hostname1", { host: self.address }).proxy();
            $(hostnamed).on("changed", function() {
                if (calculate_label())
                    $(machines).triggerHandler("changed", self);
            });

            change_state("connecting", null);
        };

        function calculate_label() {
            var label;
            if (proxy)
                label = proxy.Name || proxy.Address;
            if (hostnamed)
                label = hostnamed.PrettyHostname || hostnamed.StaticHostname || label;
            if (!label || label == "localhost" || label == "localhost.localdomain")
                label = window.location.hostname;
            if (self.label === label)
                return false;
            self.label = label;
            return true;
        }

        self.update = function update(prox) {
            proxy = prox;
            self.address = proxy.Address;
            self.color = proxy.Color;
            self.avatar = proxy.Avatar || "images/server-small.png";
            self.visible = proxy.Tags.indexOf("dashboard") !== -1;
            calculate_label();
        };

        self.change = function change(values) {
            var res = [];
            if (values.visible === true)
                res.push(proxy.AddTag("dashboard"));
            else if (values.visible === false)
                res.push(proxy.RemoveTag("dashboard"));
            if (values.avatar)
                res.push(proxy.SetAvatar(values.avatar));
            if (values.color)
                res.push(proxy.SetColor(values.color));
            if (values.label) {
                res.push(proxy.SetName(values.label));
                if (hostnamed && hostnamed.valid) {
                    hostnamed.SetPrettyHostname(values.label, true)
                        .fail(function(ex) {
                            console.warn("couldn't set pretty host name: " + ex);
                        });
                }
            }
            return $.when.apply($, res);
        };

        self.close = function close() {
            if (channel)
                disconnect();
        };
    }

    function Machines() {
        var self = this;
        var flat = null;
        var map = { };
        var ready = false;

        /* TODO: This should be migrated away from cockpitd */

        var client = cockpit.dbus("com.redhat.Cockpit", { bus: "session", track: true });
        var proxies = client.proxies("com.redhat.Cockpit.Machine", "/com/redhat/Cockpit/Machines");

        function color_in_use(color) {
            var key, machine, norm = $.color.parse(color).toString();
            for (key in map) {
                machine = map[key];
                if (machine.color && $.color.parse(machine.color).toString() == norm)
                    return true;
            }
            return false;
        }

        function ensure_machine_color(machine) {
            if (machine.color)
                return;

            var color = "gray";
            var i, length = module.colors.length;
            for (i = 0; i < length; i++) {
                if (!color_in_use(module.colors[i])) {
                    color = module.colors[i];
                    break;
                }
            }

            machine.color = color;
            machine.change({ color: color })
                .fail(function(ex) {
                    console.warn("couldn't set machine color: " + ex);
                });
        }

        proxies.wait(function() {
            var key;
            ready = true;
            for (key in map)
                ensure_machine_color(map[key]);
            for (key in map)
                $(self).triggerHandler("added", map[key]);
        });

        $(proxies).on('added changed', function(ev, proxy) {
            var machine = map[proxy.Address];
            if (!machine)
                machine = new Machine(self);
            machine.update(proxy);
            map[proxy.Address] = machine;
            flat = null;
            if (ready) {
                ensure_machine_color(machine);
                $(self).triggerHandler(ev.type, machine);
            }
        });

        $(proxies).on('removed', function(ev, proxy) {
            var machine = map[proxy.Address];
            delete map[proxy.Address];
            flat = null;
            machine.close();
            $(self).triggerHandler('removed', machine);
        });

        proxies.wait(function() {
            flat = null;
            $(self).triggerHandler('ready');
        });

        Object.defineProperty(self, "list", {
            enumerable: true,
            get: function get() {
                if (!flat) {
                    flat = [];
                    for (var key in map) {
                        if (map[key].visible)
                            flat.push(map[key]);
                    }
                    flat.sort(function(m1, m2) {
                        return m2.label.localeCompare(m2.label);
                    });
                }
                return flat;
            }
        });

        Object.defineProperty(self, "addresses", {
            enumerable: true,
            get: function get() {
                return Object.keys(map);
            }
        });

        self.lookup = function lookup(address) {
            return map[address || "localhost"] || null;
        };

        self.add = function add(address, host_key) {
            var dfd = $.Deferred();
            client.call("/com/redhat/Cockpit/Machines",
                        "com.redhat.Cockpit.Machines",
                        "Add", [address, host_key])
                .done(function(out) {
                    var path = out[0];
                    var proxy = proxies[path];
                    dfd.resolve(map[proxy.Address]);
                })
                .fail(function(ex) {
                    dfd.reject(ex);
                });
            return dfd.promise();
        };

        self.close = function close() {
            if (proxies)
                $(proxies).off();
            if (client)
                client.close();
        };
    }

    module.instance = function instance() {
        return new Machines();
    };

    module.colors = [
        "#0099d3",
        "#67d300",
        "#d39e00",
        "#d3007c",
        "#00d39f",
        "#00d1d3",
        "#00618a",
        "#4c8a00",
        "#8a6600",
        "#9b005b",
        "#008a55",
        "#008a8a",
        "#00b9ff",
        "#7dff00",
        "#ffbe00",
        "#ff0096",
        "#00ffc0",
        "#00fdff",
        "#023448",
        "#264802",
        "#483602",
        "#590034",
        "#024830",
        "#024848"
    ];

    return module;
});
<commit_msg>shell: Use cockpit.file() to write the machines.json file directly<commit_after>define([
    "jquery",
    "base1/cockpit"
], function($, cockpit) {
    var module = { };

    function Machine(key, modify, machines) {
        var self = this;
        var hostnamed = null;
        var channel = null;
        var json_label = null;

        self.key = key;
        self.state = null;
        self.problem = null;

        function change_state(value, problem) {
            self.state = value;
            self.problem = problem;
            $(machines).triggerHandler("changed", self);
        }

        function disconnect() {
            $(channel).off();
            channel.close();
            channel = null;

            if (hostnamed) {
                $(hostnamed).off();
                hostnamed.client.close();
                hostnamed = null;
            }
        }

        self.connect = function connect(force) {
            if (channel && force)
                disconnect();
            if (channel)
                return;

            if (!self.address) {
                change_state("failed", "no-host");
                return;
            }

            channel = cockpit.channel({ host: self.address, payload: "echo" });
            $(channel)
                .on("message", function() {
                    change_state("connected", null);
                })
                .on("close", function(options) {
                    var problem = options.problem || "disconnected";
                    change_state("failed", problem);
                    disconnect();
                });

            /* So we get back a message once connected */
            channel.send("x");

            hostnamed = cockpit.dbus("org.freedesktop.hostname1", { host: self.address }).proxy();
            $(hostnamed).on("changed", function() {
                if (calculate_label())
                    $(machines).triggerHandler("changed", self);
            });

            change_state("connecting", null);
        };

        function calculate_label() {
            var label = json_label || self.address;
            if (hostnamed)
                label = hostnamed.PrettyHostname || hostnamed.StaticHostname || label;
            if (!label || label == "localhost" || label == "localhost.localdomain")
                label = window.location.hostname;
            if (self.label === label)
                return false;
            self.label = label;
            return true;
        }

        self.update = function update(item) {
            self.address = item.address || key;
            json_label = item.label;
            self.color = item.color;
            self.avatar = item.avatar || "images/server-small.png";
            self.visible = item.visible;
            calculate_label();
        };

        self.change = function change(values) {
            if (values.label && hostnamed && hostnamed.valid) {
                hostnamed.SetPrettyHostname(values.label, true)
                    .fail(function(ex) {
                        console.warn("couldn't set pretty host name: " + ex);
                    });
            }
            return modify(key, values);
        };

        self.close = function close() {
            if (channel)
                disconnect();
        };
    }

    function Machines() {
        var self = this;
        var flat = null;
        var map = { };
        var ready = false;

        var content = null;
        var tag = null;

        var defaults = "{ \"localhost\": { \"visible\": true } }";

        var file = cockpit.file("/var/lib/cockpit/machines.json", { syntax: JSON });
        file.watch(function(data, tag, ex) {
            if (ex)
                console.warn("couldn't load machines data: " + ex);
            update(data, tag);
        });

        function color_in_use(color) {
            var key, machine, norm = $.color.parse(color).toString();
            for (key in map) {
                machine = map[key];
                if (machine.color && $.color.parse(machine.color).toString() == norm)
                    return true;
            }
            return false;
        }

        function ensure_machine_color(machine) {
            if (machine.color)
                return;

            var color = "gray";
            var i, length = module.colors.length;
            for (i = 0; i < length; i++) {
                if (!color_in_use(module.colors[i])) {
                    color = module.colors[i];
                    break;
                }
            }

            machine.color = color;
            machine.change({ color: color })
                .fail(function(ex) {
                    console.warn("couldn't set machine color: " + ex);
                });
        }

        function ensure(key, item) {
            var machine = map[key];
            var created = !machine;
            flat = null;
            if (!machine)
                machine = new Machine(key, modify, self);
            machine.update(item);
            map[key] = machine;

            if (ready) {
                ensure_machine_color(machine);
                $(self).triggerHandler(created ? "added" : "changed", machine);
            }

            return machine;
        }

        function update(data, new_tag) {
            content = data || JSON.parse(defaults);
            tag = new_tag;
            flat = null;

            var key;
            var seen = { };
            for (key in map)
                seen[key] = key;

            for (key in content) {
                ensure(key, content[key]);
                delete seen[key];
            }

            var machine;
            for (key in seen) {
                machine = map[key];
                delete map[key];
                machine.close();
                $(self).triggerHandler("removed", machine);
            }

            if (!ready) {
                ready = true;
                for (key in map)
                    ensure_machine_color(map[key]);
                for (key in map)
                    $(self).triggerHandler("added", map[key]);
                $(self).triggerHandler('ready');
            }
        }

        function modify(key, values) {
            function mutate(data) {
                var item = data[key];
                if (!item)
                    item = data[key] = { };
                for (var i in values)
                    item[i] = values[i];
                return data;
            }
            return file.modify(mutate, content, tag);
        }

        Object.defineProperty(self, "list", {
            enumerable: true,
            get: function get() {
                var key;
                if (!flat) {
                    flat = [];
                    for (key in map) {
                        if (map[key].visible)
                            flat.push(map[key]);
                    }
                    flat.sort(function(m1, m2) {
                        return m2.label.localeCompare(m2.label);
                    });
                }
                return flat;
            }
        });

        Object.defineProperty(self, "addresses", {
            enumerable: true,
            get: function get() {
                return Object.keys(map);
            }
        });

        self.lookup = function lookup(address) {
            return map[address || "localhost"] || null;
        };

        self.add = function add(address, host_key) {
            var dfd = $.Deferred();

            var item = { address: address, visible: true };
            var json = modify(address, item);

            var known_hosts = cockpit.file("/var/lib/cockpit/known_hosts");
            var append = known_hosts.modify(function(data) {
                return data + "\n" + host_key;
            });

            append.always(function() {
                known_hosts.close();
            });

            $.when(json, append)
                .done(function() {
                    dfd.resolve(ensure(address, item));
                })
                .fail(function(ex) {
                    dfd.reject(ex);
                });

            return dfd.promise();
        };

        self.close = function close() {
            file.close();
        };
    }

    module.instance = function instance() {
        return new Machines();
    };

    module.colors = [
        "#0099d3",
        "#67d300",
        "#d39e00",
        "#d3007c",
        "#00d39f",
        "#00d1d3",
        "#00618a",
        "#4c8a00",
        "#8a6600",
        "#9b005b",
        "#008a55",
        "#008a8a",
        "#00b9ff",
        "#7dff00",
        "#ffbe00",
        "#ff0096",
        "#00ffc0",
        "#00fdff",
        "#023448",
        "#264802",
        "#483602",
        "#590034",
        "#024830",
        "#024848"
    ];

    return module;
});
<|endoftext|>


<commit_before>/*
 * Create output files and directories
 * @lastmodifiedBy ChengFuLin
 * @lastmodifiedDate 2015-08-31
 */
var fs = require('fs'),
    spawnSync = require('child_process').spawnSync;
var scopeCtrl = require('./scopectrl'),
    modelCtrl = require('./modelctrl'),
    modelGraphConverter = require('./graphics');

/**
 * OutputWriter
 * @constructor
 */
function OutputWriter() {
    "use strict";
    /* start-test-block */
    this._testonly_ = {
        _writeDOTRepresentationFileForGraph: writeDOTRepresentationFileForGraph,
        _writeDOTRepresentationFileForDUpairs: writeDOTRepresentationFileForDUpairs,
        _writeImageFileFromDotFile: writeImageFileFromDotFile
    };
    /* end-test-block */
}

Object.defineProperties(OutputWriter.prototype, {
    /**
     * Directory name of the root directory of the output files
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    ROOT_OUTPUT_DIR: {
        value: 'out-' + (new Date()).toLocaleDateString() + '-' + (new Date()).getHours() + '-' + (new Date()).getMinutes() + '-' + (new Date()).getSeconds(),
        enumerable: true
    },
    /**
     * Heading of the directory name of page outputs
     * @type {string}
     * @memeberof OutputWriter.prototype
     */
    PAGE_OUTPUT_DIR: {
        value: 'page',
        enumerable: true
    },
    /**
     * Directory name of the intra-procedural analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTRA_PROCEDURAL_OUTPUTS_DIR: {
        value: 'intra-procedurals',
        enumeralbe: true
    },
    /**
     * Directory name of the inter-procedural analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTER_PROCEDURAL_OUTPUTS_DIR: {
        value: 'inter-procedurals',
        enumerable: true
    },
    /**
     * Directory name of the intra-page analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTRA_PAGE_OUTPUTS_DIR: {
        value: 'intra-pages',
        enumerable: true
    },
    /**
     * Directory name of the inter-page analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTER_PAGE_OUTPUTS_DIR: {
        value: 'inter-page',
        enumerable: true
    },
    /**
     * Collection of intra-procedural graph image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    intraProceduralGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    intraProceduralDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    interProceduralGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    interProceduralDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    intraPageGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    intraPageDUPairsmageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    interPageGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    interPageDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    }
});

/**
 * Create output directories
 * @param {number} pageIndex
 */
OutputWriter.prototype.createOutputDirectories = function (pageIndex) {
    "use strict";
    var indexOfPageOutput = pageIndex || 0;
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PROCEDURAL_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PROCEDURAL_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTER_PROCEDURAL_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTER_PROCEDURAL_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PAGE_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PAGE_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.INTER_PAGE_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.INTER_PAGE_OUTPUTS_DIR);
    }
};

/**
 * Write the combined JS source files of a page
 * @param {string} content
 * @param {number} indexOfPage
 */
OutputWriter.prototype.writeCombinedJSSource = function (content, indexOfPage) {
    "use strict";
    fs.writeFileSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPage + '/' + 'src.js', content);
};

/**
 * Write the DOT format files representing model graph
 * @param {Model} model
 * @param {string} outputDirPath
 * @param {number} [modelIndex]
 * @returns {string} File path of the graph representation file
 * @memberof OutputWriter.prototype
 * @private
 */
function writeDOTRepresentationFileForGraph(model, outputDirPath, modelIndex) {
    "use strict";
    var graphRepresentation = modelGraphConverter.convertGraphToDot(model);
    var index = modelIndex || 0;
    var graphRepresentationFilePath = outputDirPath + '/' + index + '.graph.dot';
    fs.writeFileSync(graphRepresentationFilePath, graphRepresentation);
    return graphRepresentationFilePath;
}

/**
 * Write the DOT format files representing computed Def-Use pairs
 * @param {Model} model
 * @param {string} outputDirPath
 * @param {number} [modelIndex]
 * @returns {string}
 * @memberof OutputWriter.prototype
 * @private
 */
function writeDOTRepresentationFileForDUpairs(model, outputDirPath, modelIndex) {
    "use strict";
    var dupairsRepresentation = modelGraphConverter.convertDUPairsToDot(model.dupairs);
    var index = modelIndex || 0;
    var dupairsRepresentationFilePath = outputDirPath + '/' + index + '.dupairs.dot';
    fs.writeFileSync(dupairsRepresentationFilePath, dupairsRepresentation);
    return dupairsRepresentationFilePath;
}

/**
 * Write image files from DOT formatted file with Graphviz tool
 * @param {string} dotFilePath
 */
function writeImageFileFromDotFile(dotFilePath) {
    "use strict";
    var imageFilePath = dotFilePath.replace('.dot', '.png');
    var graphvizDotToolCmd = 'dot';
    spawnSync(graphvizDotToolCmd, [dotFilePath, '-Tpng', '-o', imageFilePath]);
    return imageFilePath;
}

/**
 * Write the result files of intra-procedural analysis
 */
OutputWriter.prototype.writeIntraProceduralAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var intraProceduralModels = pageModels.intraProceduralModels;
        theOutputWriter.intraProceduralGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.intraProceduralDUPairsImageFilePaths[pageIndex] = [];

        intraProceduralModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.intraProceduralGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.intraProceduralDUPairsImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of inter-procedural analysis
 */
OutputWriter.prototype.writeInterProceduralAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var interProceduralModels = pageModels.interProceduralModels;
        theOutputWriter.interProceduralGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.interProceduralDUPairsImageFilePaths[pageIndex] = [];

        interProceduralModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTER_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTER_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.interProceduralGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.interProceduralDUPairsImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of intra-page analysis
 */
OutputWriter.prototype.writeIntraPageAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var intraPageModels = pageModels.intraPageModels;
        theOutputWriter.intraPageGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.intraPageDUPairsmageFilePaths[pageIndex] = [];

        intraPageModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PAGE_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PAGE_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.intraPageGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.intraPageDUPairsmageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of inter-page analysis
 */
OutputWriter.prototype.writeInterPageAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var interPageModel = modelCtrl.interPageModel;
    var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
        interPageModel,
        theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.INTER_PAGE_OUTPUTS_DIR
    );
    var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
        interPageModel,
        theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.INTER_PAGE_OUTPUTS_DIR
    );
    theOutputWriter.interPageGraphImageFilePaths.push(writeImageFileFromDotFile(modelGraphOutputFilePath));
    theOutputWriter.interPageDUPairsImageFilePaths.push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
};

var writer = new OutputWriter();
module.exports = writer;<commit_msg>Add comments and record the file path of JS source<commit_after>/*
 * Create output files and directories
 * @lastmodifiedBy ChengFuLin
 * @lastmodifiedDate 2015-09-01
 */
var fs = require('fs'),
    spawnSync = require('child_process').spawnSync;
var scopeCtrl = require('./scopectrl'),
    modelCtrl = require('./modelctrl'),
    modelGraphConverter = require('./graphics');

/**
 * OutputWriter
 * @constructor
 */
function OutputWriter() {
    "use strict";
    /* start-test-block */
    this._testonly_ = {
        _writeDOTRepresentationFileForGraph: writeDOTRepresentationFileForGraph,
        _writeDOTRepresentationFileForDUpairs: writeDOTRepresentationFileForDUpairs,
        _writeImageFileFromDotFile: writeImageFileFromDotFile
    };
    /* end-test-block */
}

Object.defineProperties(OutputWriter.prototype, {
    /**
     * Directory name of the root directory of the output files
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    ROOT_OUTPUT_DIR: {
        value: 'out-' + (new Date()).toLocaleDateString() + '-' + (new Date()).getHours() + '-' + (new Date()).getMinutes() + '-' + (new Date()).getSeconds(),
        enumerable: true
    },
    /**
     * Heading of the directory name of page outputs
     * @type {string}
     * @memeberof OutputWriter.prototype
     */
    PAGE_OUTPUT_DIR: {
        value: 'page',
        enumerable: true
    },
    /**
     * Directory name of the intra-procedural analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTRA_PROCEDURAL_OUTPUTS_DIR: {
        value: 'intra-procedurals',
        enumeralbe: true
    },
    /**
     * Directory name of the inter-procedural analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTER_PROCEDURAL_OUTPUTS_DIR: {
        value: 'inter-procedurals',
        enumerable: true
    },
    /**
     * Directory name of the intra-page analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTRA_PAGE_OUTPUTS_DIR: {
        value: 'intra-pages',
        enumerable: true
    },
    /**
     * Directory name of the inter-page analysis outputs
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    INTER_PAGE_OUTPUTS_DIR: {
        value: 'inter-page',
        enumerable: true
    },
    /**
     * Collection of intra-procedural graph image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    intraProceduralGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of intra-procedural def-use pairs table image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    intraProceduralDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of inter-procedural graph image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    interProceduralGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of inter-procedural def-use pairs table image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    interProceduralDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of intra-page graph image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    intraPageGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of intra-page def-use pairs table image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    intraPageDUPairsmageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of inter-page graph image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    interPageGraphImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * Collection of inter-page def-use pairs table image file paths of each page
     * @type {Array}
     * @memberof OutputWriter.prototype
     */
    interPageDUPairsImageFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    },
    /**
     * File paths for JS source of each page
     * @type {string}
     * @memberof OutputWriter.prototype
     */
    pageJSSourFilePaths: {
        value: [],
        writable: true,
        enumerable: true
    }
});

/**
 * Create output directories
 * @param {number} pageIndex
 */
OutputWriter.prototype.createOutputDirectories = function (pageIndex) {
    "use strict";
    var indexOfPageOutput = pageIndex || 0;
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PROCEDURAL_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PROCEDURAL_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTER_PROCEDURAL_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTER_PROCEDURAL_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PAGE_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPageOutput + '/' + this.INTRA_PAGE_OUTPUTS_DIR);
    }
    if (!fs.existsSync(this.ROOT_OUTPUT_DIR + '/' + this.INTER_PAGE_OUTPUTS_DIR)) {
        fs.mkdirSync(this.ROOT_OUTPUT_DIR + '/' + this.INTER_PAGE_OUTPUTS_DIR);
    }
};

/**
 * Write the combined JS source files of a page
 * @param {string} content
 * @param {number} indexOfPage
 */
OutputWriter.prototype.writeCombinedJSSource = function (content, indexOfPage) {
    "use strict";
    var path = this.ROOT_OUTPUT_DIR + '/' + this.PAGE_OUTPUT_DIR + indexOfPage + '/' + 'src.js';
    fs.writeFileSync(path, content);
    this.pageJSSourFilePaths[indexOfPage] = path;
};

/**
 * Write the DOT format files representing model graph
 * @param {Model} model
 * @param {string} outputDirPath
 * @param {number} [modelIndex]
 * @returns {string} File path of the graph representation file
 * @memberof OutputWriter.prototype
 * @private
 */
function writeDOTRepresentationFileForGraph(model, outputDirPath, modelIndex) {
    "use strict";
    var graphRepresentation = modelGraphConverter.convertGraphToDot(model);
    var index = modelIndex || 0;
    var graphRepresentationFilePath = outputDirPath + '/' + index + '.graph.dot';
    fs.writeFileSync(graphRepresentationFilePath, graphRepresentation);
    return graphRepresentationFilePath;
}

/**
 * Write the DOT format files representing computed Def-Use pairs
 * @param {Model} model
 * @param {string} outputDirPath
 * @param {number} [modelIndex]
 * @returns {string}
 * @memberof OutputWriter.prototype
 * @private
 */
function writeDOTRepresentationFileForDUpairs(model, outputDirPath, modelIndex) {
    "use strict";
    var dupairsRepresentation = modelGraphConverter.convertDUPairsToDot(model.dupairs);
    var index = modelIndex || 0;
    var dupairsRepresentationFilePath = outputDirPath + '/' + index + '.dupairs.dot';
    fs.writeFileSync(dupairsRepresentationFilePath, dupairsRepresentation);
    return dupairsRepresentationFilePath;
}

/**
 * Write image files from DOT formatted file with Graphviz tool
 * @param {string} dotFilePath
 */
function writeImageFileFromDotFile(dotFilePath) {
    "use strict";
    var imageFilePath = dotFilePath.replace('.dot', '.png');
    var graphvizDotToolCmd = 'dot';
    spawnSync(graphvizDotToolCmd, [dotFilePath, '-Tpng', '-o', imageFilePath]);
    return imageFilePath;
}

/**
 * Write the result files of intra-procedural analysis
 */
OutputWriter.prototype.writeIntraProceduralAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var intraProceduralModels = pageModels.intraProceduralModels;
        theOutputWriter.intraProceduralGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.intraProceduralDUPairsImageFilePaths[pageIndex] = [];

        intraProceduralModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.intraProceduralGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.intraProceduralDUPairsImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of inter-procedural analysis
 */
OutputWriter.prototype.writeInterProceduralAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var interProceduralModels = pageModels.interProceduralModels;
        theOutputWriter.interProceduralGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.interProceduralDUPairsImageFilePaths[pageIndex] = [];

        interProceduralModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTER_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTER_PROCEDURAL_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.interProceduralGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.interProceduralDUPairsImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of intra-page analysis
 */
OutputWriter.prototype.writeIntraPageAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var pageScopeTrees = scopeCtrl.pageScopeTrees;
    pageScopeTrees.forEach(function (scopeTree, pageIndex) {
        var pageModels = modelCtrl.getPageModels(scopeTree);
        var intraPageModels = pageModels.intraPageModels;
        theOutputWriter.intraPageGraphImageFilePaths[pageIndex] = [];
        theOutputWriter.intraPageDUPairsmageFilePaths[pageIndex] = [];

        intraPageModels.forEach(function (model, modelIndex) {
            var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PAGE_OUTPUTS_DIR,
                modelIndex
            );
            var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
                model,
                theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.PAGE_OUTPUT_DIR + pageIndex + '/' + theOutputWriter.INTRA_PAGE_OUTPUTS_DIR,
                modelIndex
            );
            theOutputWriter.intraPageGraphImageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelGraphOutputFilePath));
            theOutputWriter.intraPageDUPairsmageFilePaths[pageIndex].push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
        });
    });
};

/**
 * Write the result files of inter-page analysis
 */
OutputWriter.prototype.writeInterPageAnalysisResultFiles = function () {
    "use strict";
    var theOutputWriter = this;
    var interPageModel = modelCtrl.interPageModel;
    var modelGraphOutputFilePath = writeDOTRepresentationFileForGraph(
        interPageModel,
        theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.INTER_PAGE_OUTPUTS_DIR
    );
    var modelDUPairsOutputFilePath = writeDOTRepresentationFileForDUpairs(
        interPageModel,
        theOutputWriter.ROOT_OUTPUT_DIR + '/' + theOutputWriter.INTER_PAGE_OUTPUTS_DIR
    );
    theOutputWriter.interPageGraphImageFilePaths.push(writeImageFileFromDotFile(modelGraphOutputFilePath));
    theOutputWriter.interPageDUPairsImageFilePaths.push(writeImageFileFromDotFile(modelDUPairsOutputFilePath));
};

var writer = new OutputWriter();
module.exports = writer;<|endoftext|>


<commit_before>import { CompositeDisposable } from "atom";
import { TableEditor, options, Alignment } from "@susisu/mte-kernel";

import TextEditorInterface from "./text-editor-interface.js";

const NAMESPACE = "markdown-table-editor";
const ACTIVE_CLASS = "markdown-table-editor-active";

export default class EditorController {
  constructor(editor) {
    this.editor = editor;
    this.editorIntf = new TextEditorInterface(this.editor, atom.config.get(`${NAMESPACE}.scopes`));
    this.tableEditor = new TableEditor(this.editorIntf);

    this.updateActiveState();

    // event subscriptions
    this.subscriptions = new CompositeDisposable();

    // editor
    this.subscriptions.add(this.editor.onDidChangeGrammar(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidAddCursor(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidRemoveCursor(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidChangeCursorPosition(event => {
      if (!this.editorIntf.transaction
        && event.newBufferPosition.row !== event.oldBufferPosition.row) {
        this.updateActiveState();
      }
    }));
    this.subscriptions.add(this.editor.onDidStopChanging(() => {
      if (!this.editorIntf.transaction) {
        this.updateActiveState();
      }
    }));
    this.subscriptions.add(this.editorIntf.onDidFinishTransaction(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.getBuffer().onWillSave(() => {
      if (atom.config.get(`${NAMESPACE}.formatOnSave`)) {
        this.formatAll();
      }
    }));

    // config
    this.subscriptions.add(atom.config.observe(`${NAMESPACE}.scopes`, scopes => {
      this.editorIntf.scopes = scopes;
      this.updateActiveState();
    }));
  }

  updateActiveState() {
    const isActive = !this.editor.hasMultipleCursors()
      && this.tableEditor.cursorIsInTable(this.getOptions());
    if (isActive) {
      this.editor.element.classList.add(ACTIVE_CLASS);
    }
    else {
      this.editor.element.classList.remove(ACTIVE_CLASS);
      this.tableEditor.resetSmartCursor();
    }
  }

  getOptions() {
    const scope = this.editor.scopeDescriptorForBufferPosition(
      this.editor.getCursorBufferPosition()
    );
    return options({
      leftMarginChars  : new Set(atom.config.get(`${NAMESPACE}.leftMarginChars`, { scope })),
      formatType       : atom.config.get(`${NAMESPACE}.formatType`, { scope }),
      minDelimiterWidth: atom.config.get(`${NAMESPACE}.minDelimiterWidth`, { scope }),
      defaultAlignment : atom.config.get(`${NAMESPACE}.defaultAlignment`, { scope }),
      headerAlignment  : atom.config.get(`${NAMESPACE}.headerAlignment`, { scope }),
      smartCursor      : atom.config.get(`${NAMESPACE}.smartCursor`, { scope }),
      textWidthOptions : {
        normalize      : atom.config.get(`${NAMESPACE}.normalize`, { scope }),
        wideChars      : new Set(atom.config.get(`${NAMESPACE}.wideChars`, { scope })),
        narrowChars    : new Set(atom.config.get(`${NAMESPACE}.narrowChars`, { scope })),
        ambiguousAsWide: atom.config.get(`${NAMESPACE}.ambiguousAsWide`, { scope })
      }
    });
  }

  format() {
    this.tableEditor.format(this.getOptions());
  }

  formatAll() {
    this.tableEditor.formatAll(this.getOptions());
  }

  escape() {
    this.tableEditor.escape(this.getOptions());
  }

  alignLeft() {
    this.tableEditor.alignColumn(Alignment.LEFT, this.getOptions());
  }

  alignRight() {
    this.tableEditor.alignColumn(Alignment.RIGHT, this.getOptions());
  }

  alignCenter() {
    this.tableEditor.alignColumn(Alignment.CENTER, this.getOptions());
  }

  alignNone() {
    this.tableEditor.alignColumn(Alignment.NONE, this.getOptions());
  }

  selectCell() {
    this.tableEditor.selectCell(this.getOptions());
  }

  moveLeft() {
    this.tableEditor.moveFocus(0, -1, this.getOptions());
  }

  moveRight() {
    this.tableEditor.moveFocus(0, 1, this.getOptions());
  }

  moveUp() {
    this.tableEditor.moveFocus(-1, 0, this.getOptions());
  }

  moveDown() {
    this.tableEditor.moveFocus(1, 0, this.getOptions());
  }

  nextCell() {
    this.tableEditor.nextCell(this.getOptions());
  }

  previousCell() {
    this.tableEditor.previousCell(this.getOptions());
  }

  nextRow() {
    this.tableEditor.nextRow(this.getOptions());
  }

  insertRow() {
    this.tableEditor.insertRow(this.getOptions());
  }

  deleteRow() {
    this.tableEditor.deleteRow(this.getOptions());
  }

  moveRowUp() {
    this.tableEditor.moveRow(-1, this.getOptions());
  }

  moveRowDown() {
    this.tableEditor.moveRow(1, this.getOptions());
  }

  insertColumn() {
    this.tableEditor.insertColumn(this.getOptions());
  }

  deleteColumn() {
    this.tableEditor.deleteColumn(this.getOptions());
  }

  moveColumnLeft() {
    this.tableEditor.moveColumn(-1, this.getOptions());
  }

  moveColumnRight() {
    this.tableEditor.moveColumn(1, this.getOptions());
  }

  destroy() {
    this.subscriptions.dispose();
    this.editorIntf.destroy();
  }
}
<commit_msg>Reuse options for `config.get`<commit_after>import { CompositeDisposable } from "atom";
import { TableEditor, options, Alignment } from "@susisu/mte-kernel";

import TextEditorInterface from "./text-editor-interface.js";

const NAMESPACE = "markdown-table-editor";
const ACTIVE_CLASS = "markdown-table-editor-active";

export default class EditorController {
  constructor(editor) {
    this.editor = editor;
    this.editorIntf = new TextEditorInterface(this.editor, atom.config.get(`${NAMESPACE}.scopes`));
    this.tableEditor = new TableEditor(this.editorIntf);

    this.updateActiveState();

    // event subscriptions
    this.subscriptions = new CompositeDisposable();

    // editor
    this.subscriptions.add(this.editor.onDidChangeGrammar(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidAddCursor(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidRemoveCursor(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.onDidChangeCursorPosition(event => {
      if (!this.editorIntf.transaction
        && event.newBufferPosition.row !== event.oldBufferPosition.row) {
        this.updateActiveState();
      }
    }));
    this.subscriptions.add(this.editor.onDidStopChanging(() => {
      if (!this.editorIntf.transaction) {
        this.updateActiveState();
      }
    }));
    this.subscriptions.add(this.editorIntf.onDidFinishTransaction(() => {
      this.updateActiveState();
    }));
    this.subscriptions.add(this.editor.getBuffer().onWillSave(() => {
      if (atom.config.get(`${NAMESPACE}.formatOnSave`)) {
        this.formatAll();
      }
    }));

    // config
    this.subscriptions.add(atom.config.observe(`${NAMESPACE}.scopes`, scopes => {
      this.editorIntf.scopes = scopes;
      this.updateActiveState();
    }));
  }

  updateActiveState() {
    const isActive = !this.editor.hasMultipleCursors()
      && this.tableEditor.cursorIsInTable(this.getOptions());
    if (isActive) {
      this.editor.element.classList.add(ACTIVE_CLASS);
    }
    else {
      this.editor.element.classList.remove(ACTIVE_CLASS);
      this.tableEditor.resetSmartCursor();
    }
  }

  getOptions() {
    const configOpt = {
      scope: this.editor.scopeDescriptorForBufferPosition(this.editor.getCursorBufferPosition())
    };
    return options({
      leftMarginChars  : new Set(atom.config.get(`${NAMESPACE}.leftMarginChars`, configOpt)),
      formatType       : atom.config.get(`${NAMESPACE}.formatType`, configOpt),
      minDelimiterWidth: atom.config.get(`${NAMESPACE}.minDelimiterWidth`, configOpt),
      defaultAlignment : atom.config.get(`${NAMESPACE}.defaultAlignment`, configOpt),
      headerAlignment  : atom.config.get(`${NAMESPACE}.headerAlignment`, configOpt),
      smartCursor      : atom.config.get(`${NAMESPACE}.smartCursor`, configOpt),
      textWidthOptions : {
        normalize      : atom.config.get(`${NAMESPACE}.normalize`, configOpt),
        wideChars      : new Set(atom.config.get(`${NAMESPACE}.wideChars`, configOpt)),
        narrowChars    : new Set(atom.config.get(`${NAMESPACE}.narrowChars`, configOpt)),
        ambiguousAsWide: atom.config.get(`${NAMESPACE}.ambiguousAsWide`, configOpt)
      }
    });
  }

  format() {
    this.tableEditor.format(this.getOptions());
  }

  formatAll() {
    this.tableEditor.formatAll(this.getOptions());
  }

  escape() {
    this.tableEditor.escape(this.getOptions());
  }

  alignLeft() {
    this.tableEditor.alignColumn(Alignment.LEFT, this.getOptions());
  }

  alignRight() {
    this.tableEditor.alignColumn(Alignment.RIGHT, this.getOptions());
  }

  alignCenter() {
    this.tableEditor.alignColumn(Alignment.CENTER, this.getOptions());
  }

  alignNone() {
    this.tableEditor.alignColumn(Alignment.NONE, this.getOptions());
  }

  selectCell() {
    this.tableEditor.selectCell(this.getOptions());
  }

  moveLeft() {
    this.tableEditor.moveFocus(0, -1, this.getOptions());
  }

  moveRight() {
    this.tableEditor.moveFocus(0, 1, this.getOptions());
  }

  moveUp() {
    this.tableEditor.moveFocus(-1, 0, this.getOptions());
  }

  moveDown() {
    this.tableEditor.moveFocus(1, 0, this.getOptions());
  }

  nextCell() {
    this.tableEditor.nextCell(this.getOptions());
  }

  previousCell() {
    this.tableEditor.previousCell(this.getOptions());
  }

  nextRow() {
    this.tableEditor.nextRow(this.getOptions());
  }

  insertRow() {
    this.tableEditor.insertRow(this.getOptions());
  }

  deleteRow() {
    this.tableEditor.deleteRow(this.getOptions());
  }

  moveRowUp() {
    this.tableEditor.moveRow(-1, this.getOptions());
  }

  moveRowDown() {
    this.tableEditor.moveRow(1, this.getOptions());
  }

  insertColumn() {
    this.tableEditor.insertColumn(this.getOptions());
  }

  deleteColumn() {
    this.tableEditor.deleteColumn(this.getOptions());
  }

  moveColumnLeft() {
    this.tableEditor.moveColumn(-1, this.getOptions());
  }

  moveColumnRight() {
    this.tableEditor.moveColumn(1, this.getOptions());
  }

  destroy() {
    this.subscriptions.dispose();
    this.editorIntf.destroy();
  }
}
<|endoftext|>


<commit_before>var Endpoint = require('../entities/endpoint'),
    Exporter = require('./exporter'),
    SwaggerParser = require('swagger-parser'),
    jsonHelper = require('../utils/json.js'),
    SwaggerDefinition = require('../entities/swagger/definition'),
    _ = require('lodash'),
    url = require('url');

function Swagger() {
  this.metadata = null;
}

function mapResponseTypes(slResponses) {
  var result = [];
  for(var i in slResponses) {
    var res = slResponses[i];
    if (res.mimeType) {
      result.push(res.mimeType);
    }
  }
  return _.uniq(result);
}

function validateParameters(parameters) {
  parameters = jsonHelper.orderByKeys(parameters, ['$ref', 'name', 'in', 'description', 'required', 'schema']);
  var validTypes = ['string', 'number', 'integer', 'boolean', 'array', 'file'], defaultType = 'string';
  for(var i in parameters) {
    if (parameters[i].in != 'body') {
      if (Array.isArray(parameters[i].type)) {
        if(parameters[i].type.length > 0) {
          parameters[i].type = parameters[i].type[0];
        } else {
          parameters[i].type = defaultType;
        }
      }

      if(validTypes.indexOf(parameters[i].type) < 0) {
        //type not valid
        parameters[i].type = defaultType;
      }
    }
  }
  return parameters;
}

function constructSwaggerMethod(endpoint, parameters, responses, env) {
  var resultSwaggerMethod = {
    description: endpoint.Description,
    operationId: endpoint.Name,
    consumes: [endpoint.Body.mimeType || env.DefaultRequestType],
    produces: mapResponseTypes(endpoint.Responses),
    parameters: parameters,
    responses: responses,
    summary: endpoint.Summary
  };
  if (resultSwaggerMethod.operationId.length === 0) {
    //don't keep empty operationId in exported definition
    delete resultSwaggerMethod.operationId;
  }
  return resultSwaggerMethod;
}

Swagger.prototype = new Exporter();

Swagger.prototype._mapEndpointSecurity = function(securedByTypes, securityDefinitions) {
  var security = [];
  for (var type in securedByTypes) {
    var scheme = securityDefinitions[type];
    if (!scheme) {
      //definition error
    }
    switch (type) {
      case 'apiKey':
      case 'basic':
        var result = {};
        if (scheme.header) {
          result[scheme.header.name] = [];
        }
        if (scheme.query) {
          result[scheme.query.name] = [];
        }
        security.push(result);
        break;
      case 'oauth2':
        var result = {};
        result[scheme.name] = securedByTypes[type];
        security.push(result);
        break;
    }
  }
  return security;
};

Swagger.prototype._mapSecurityDefinitions = function(securityDefinitions) {
  var result = {};
  for(var type in securityDefinitions) {
    var sd = securityDefinitions[type];
    switch(type) {
      case 'apiKey':
        if (sd.hasOwnProperty('header')) {
          result[sd.header.name] = {
            name: sd.header.name,
            type: type,
            in: 'header'
          };
        }
        if (sd.hasOwnProperty('query')) {
          result[sd.query.name] = {
            name: sd.query.name,
            type: type,
            in: 'query'
          };
        }
        break;
      case 'oauth2':

        result[sd.name] = {
          authorizationUrl: sd.authorizationUrl || '',
          tokenUrl: sd.tokenUrl || '',
          type: type
        };

        var slScopes = sd.scopes, swaggerScopes = {};
        for (var i in slScopes) {
          var scope = slScopes[i];
          swaggerScopes[scope.name] = scope.value;
        }
        if (Object.keys(swaggerScopes).length > 0) {
          result[sd.name]['scopes'] = swaggerScopes;
        }

        if (sd.flow) {
          result[sd.name]['flow'] = sd.flow;
        }
        //TODO
        break;
      case 'basic':
        result[type] = {
          type: type
        };
        break;
    }
  }
  return result;
};

Swagger.prototype._mapURIParams = function(pathParams) {
  var parameters = [];
  if (!pathParams.properties || Object.keys(pathParams).length == 0) {
    return parameters;
  }

  for (var paramName in pathParams.properties) {
    var prop = pathParams.properties[paramName];
    var param = {};
    param.name = paramName;
    param.in = 'path';
    param.required = true;
    param.type = 'string';
    if (prop.description) {
      param.description = prop.description;
    }
    parameters.push(param);
  }
  return parameters;
};

Swagger.prototype._mapQueryString = function(queryStringParams) {
  var parameters = [];
  if (!queryStringParams.properties) {
    return parameters;
  }
  for (var paramName in queryStringParams.properties) {
    var param = queryStringParams.properties[paramName];
    param.name = paramName;
    param.in = 'query';
    if (queryStringParams.required &&
        queryStringParams.required.indexOf(param.name) >= 0) {
      param.required = true;
    }
    parameters.push(param);
  }
  return parameters;
};

Swagger.prototype._mapResponseBody = function(slResponses) {
  var result = {};
  for(var i in slResponses) {
    var res = slResponses[i], item = {description: res.description || ''};
    if (res.body && res.body !== '{}' && res.body.length > 2) {
      item.schema = jsonHelper.parse(res.body);
    }
    if (res.example && res.example !== '{}' && res.example.length > 2) {
      item.examples = {};
      item.examples[res.mimeType] = jsonHelper.parse(res.example);
    }
    result[((res.codes && res.codes.length > 0)?res.codes[0]:'default')] = item;
  }
  if (Object.keys(result).length == 0) {
    //empty schema for swagger spec validation
    result['default'] = {
      schema: {}
    };
  }
  return result;
};

Swagger.prototype._mapRequestBody = function(slRequestBody) {
  if (!slRequestBody.body) {
    return [];
  }
  var result = [], body = jsonHelper.parse(slRequestBody.body);

  if (slRequestBody.mimeType === 'application/json') {
    if (body.properties && Object.keys(body.properties).length > 0 ||
        body.hasOwnProperty('$ref')) {
      //make sure body isn't empty
      var param = {};
      param = {
        name: 'body',
        in: 'body',
        schema: body
      };
      result.push(param);
    }
  } else if (body.properties) {
    for (var property in body.properties) {
      var param = {};
      var param = {
        name: property,
        in: 'formData',
        type: body.properties[property].type || 'string'
      };
      param.required = (body.required !== undefined) && (body.required instanceof Array) && (body.required.indexOf(property) >= 0);

      if (body.properties[property].hasOwnProperty('description')) {
        param.description = body.properties[property].description || '';
      }
      result.push(param);
    }
  } else {
    //TODO any other case?
  }

  return result;
};

Swagger.prototype._mapRequestHeaders = function(slHeaders) {
  var result = [];

  for(var property in slHeaders.properties) {
    var param = slHeaders.properties[property];
    param.name = property;
    param.in = 'header';
    param.required = slHeaders.required && (slHeaders.required.indexOf(property) >= 0);
    param.description = slHeaders.properties[property].description || '';
    result.push(param);
  }
  return result;
};

Swagger.prototype._mapSchema = function(slSchemas) {
  var result = {};
  for (var i in slSchemas) {
    var schema = slSchemas[i];
    result[schema.NameSpace] = jsonHelper.parse(schema.Definition);
  }
  return result;
};

Swagger.prototype._mapEndpoints = function (swaggerDef, env) {
  var endpoints = this.project.Endpoints;
  for(var i in endpoints) {

    var endpoint = endpoints[i], parameters = [];

    if (!swaggerDef.paths[endpoint.Path]) {
      swaggerDef.paths[endpoint.Path] = {
         parameters: validateParameters(this._mapURIParams(endpoint.PathParams))
      };
    }
    swaggerDef.securityDefinitions = this._mapSecurityDefinitions(this.project.Environment.SecuritySchemes);
    parameters = parameters.concat(this._mapQueryString(endpoint.QueryString));
    parameters = parameters.concat(this._mapRequestBody(endpoint.Body));
    parameters = parameters.concat(this._mapRequestHeaders(endpoint.Headers));
    parameters = validateParameters(parameters);

    var responses = this._mapResponseBody(endpoint.Responses);
    swaggerDef.paths[endpoint.Path][endpoint.Method] = constructSwaggerMethod(endpoint, parameters, responses, env);
    //Is it OK to include produces/consumes in all cases?

    var security = [];
    if (endpoint.SecuredBy && !endpoint.SecuredBy.none) {
      swaggerDef.paths[endpoint.Path][endpoint.Method]['security'] = this._mapEndpointSecurity(endpoint.SecuredBy, this.project.Environment.SecuritySchemes);
    }
  }
};

Swagger.prototype._mapHostAndProtocol = function (env, swaggerDef) {
  var hostUrl = url.parse(env.Host);
  var swaggerHost = hostUrl.hostname || '';
  if (swaggerHost && hostUrl.port) {
    swaggerHost = swaggerHost + ':' + hostUrl.port;
  }
  swaggerDef.Host = swaggerHost;

  if(env.Protocols && env.Protocols.length>0) {
    swaggerDef.schemes = env.Protocols.map(function(p){
      return p.toLowerCase();
    });
  } else if(hostUrl.protocol) {
    swaggerDef.schemes = [hostUrl.protocol.split(':')[0]];
  }
};

Swagger.prototype._export = function () {
  //TODO
  var swaggerDef = new SwaggerDefinition(this.project.Name, this.project.Description);
  var env = this.project.Environment;
  swaggerDef.info.version = env.Version;
  swaggerDef.BasePath = env.BasePath || '';

  this._mapHostAndProtocol(env, swaggerDef);

  if(env.DefaultResponseType) {
    swaggerDef.produces = [env.DefaultResponseType];
  }

  if(env.DefaultRequestType) {
    swaggerDef.consumes = [env.DefaultRequestType];
  }

  this._mapEndpoints(swaggerDef, env);

  swaggerDef.definitions = this._mapSchema(this.project.Schemas);

  //if not security definition added, then don't keep the field anymore
  if (swaggerDef.securityDefinitions && Object.keys(swaggerDef.securityDefinitions).length <= 0) {
    delete swaggerDef['securityDefinitions'];
  }
  this.data = jsonHelper.toJSON(swaggerDef);
};

module.exports = Swagger;
<commit_msg>- swagger linter insists for schema description<commit_after>var Endpoint = require('../entities/endpoint'),
    Exporter = require('./exporter'),
    SwaggerParser = require('swagger-parser'),
    jsonHelper = require('../utils/json.js'),
    SwaggerDefinition = require('../entities/swagger/definition'),
    _ = require('lodash'),
    url = require('url');

function Swagger() {
  this.metadata = null;
}

function mapResponseTypes(slResponses) {
  var result = [];
  for(var i in slResponses) {
    var res = slResponses[i];
    if (res.mimeType) {
      result.push(res.mimeType);
    }
  }
  return _.uniq(result);
}

function validateParameters(parameters) {
  parameters = jsonHelper.orderByKeys(parameters, ['$ref', 'name', 'in', 'description', 'required', 'schema']);
  var validTypes = ['string', 'number', 'integer', 'boolean', 'array', 'file'], defaultType = 'string';
  for(var i in parameters) {
    if (parameters[i].in != 'body') {
      if (Array.isArray(parameters[i].type)) {
        if(parameters[i].type.length > 0) {
          parameters[i].type = parameters[i].type[0];
        } else {
          parameters[i].type = defaultType;
        }
      }

      if(validTypes.indexOf(parameters[i].type) < 0) {
        //type not valid
        parameters[i].type = defaultType;
      }
    }
  }
  return parameters;
}

function constructSwaggerMethod(endpoint, parameters, responses, env) {
  var resultSwaggerMethod = {
    description: endpoint.Description,
    operationId: endpoint.Name,
    consumes: [endpoint.Body.mimeType || env.DefaultRequestType],
    produces: mapResponseTypes(endpoint.Responses),
    parameters: parameters,
    responses: responses,
    summary: endpoint.Summary
  };
  if (resultSwaggerMethod.operationId.length === 0) {
    //don't keep empty operationId in exported definition
    delete resultSwaggerMethod.operationId;
  }
  return resultSwaggerMethod;
}

Swagger.prototype = new Exporter();

Swagger.prototype._mapEndpointSecurity = function(securedByTypes, securityDefinitions) {
  var security = [];
  for (var type in securedByTypes) {
    var scheme = securityDefinitions[type];
    if (!scheme) {
      //definition error
    }
    switch (type) {
      case 'apiKey':
      case 'basic':
        var result = {};
        if (scheme.header) {
          result[scheme.header.name] = [];
        }
        if (scheme.query) {
          result[scheme.query.name] = [];
        }
        security.push(result);
        break;
      case 'oauth2':
        var result = {};
        result[scheme.name] = securedByTypes[type];
        security.push(result);
        break;
    }
  }
  return security;
};

Swagger.prototype._mapSecurityDefinitions = function(securityDefinitions) {
  var result = {};
  for(var type in securityDefinitions) {
    var sd = securityDefinitions[type];
    switch(type) {
      case 'apiKey':
        if (sd.hasOwnProperty('header')) {
          result[sd.header.name] = {
            name: sd.header.name,
            type: type,
            in: 'header'
          };
        }
        if (sd.hasOwnProperty('query')) {
          result[sd.query.name] = {
            name: sd.query.name,
            type: type,
            in: 'query'
          };
        }
        break;
      case 'oauth2':

        result[sd.name] = {
          authorizationUrl: sd.authorizationUrl || '',
          tokenUrl: sd.tokenUrl || '',
          type: type
        };

        var slScopes = sd.scopes, swaggerScopes = {};
        for (var i in slScopes) {
          var scope = slScopes[i];
          swaggerScopes[scope.name] = scope.value;
        }
        if (Object.keys(swaggerScopes).length > 0) {
          result[sd.name]['scopes'] = swaggerScopes;
        }

        if (sd.flow) {
          result[sd.name]['flow'] = sd.flow;
        }
        //TODO
        break;
      case 'basic':
        result[type] = {
          type: type
        };
        break;
    }
  }
  return result;
};

Swagger.prototype._mapURIParams = function(pathParams) {
  var parameters = [];
  if (!pathParams.properties || Object.keys(pathParams).length == 0) {
    return parameters;
  }

  for (var paramName in pathParams.properties) {
    var prop = pathParams.properties[paramName];
    var param = {};
    param.name = paramName;
    param.in = 'path';
    param.required = true;
    param.type = 'string';
    if (prop.description) {
      param.description = prop.description;
    }
    parameters.push(param);
  }
  return parameters;
};

Swagger.prototype._mapQueryString = function(queryStringParams) {
  var parameters = [];
  if (!queryStringParams.properties) {
    return parameters;
  }
  for (var paramName in queryStringParams.properties) {
    var param = queryStringParams.properties[paramName];
    param.name = paramName;
    param.in = 'query';
    if (queryStringParams.required &&
        queryStringParams.required.indexOf(param.name) >= 0) {
      param.required = true;
    }
    parameters.push(param);
  }
  return parameters;
};

Swagger.prototype._mapResponseBody = function(slResponses) {
  var result = {};
  for(var i in slResponses) {
    var res = slResponses[i], item = {description: res.description || ''};
    if (res.body && res.body !== '{}' && res.body.length > 2) {
      item.schema = jsonHelper.parse(res.body);
    }
    if (res.example && res.example !== '{}' && res.example.length > 2) {
      item.examples = {};
      item.examples[res.mimeType] = jsonHelper.parse(res.example);
    }
    result[((res.codes && res.codes.length > 0)?res.codes[0]:'default')] = item;
  }
  if (Object.keys(result).length == 0) {
    //empty schema for swagger spec validation
    result['default'] = {
      description: '',
      schema: {}
    };
  }
  return result;
};

Swagger.prototype._mapRequestBody = function(slRequestBody) {
  if (!slRequestBody.body) {
    return [];
  }
  var result = [], body = jsonHelper.parse(slRequestBody.body);

  if (slRequestBody.mimeType === 'application/json') {
    if (body.properties && Object.keys(body.properties).length > 0 ||
        body.hasOwnProperty('$ref')) {
      //make sure body isn't empty
      var param = {};
      param = {
        name: 'body',
        in: 'body',
        schema: body
      };
      result.push(param);
    }
  } else if (body.properties) {
    for (var property in body.properties) {
      var param = {};
      var param = {
        name: property,
        in: 'formData',
        type: body.properties[property].type || 'string'
      };
      param.required = (body.required !== undefined) && (body.required instanceof Array) && (body.required.indexOf(property) >= 0);

      if (body.properties[property].hasOwnProperty('description')) {
        param.description = body.properties[property].description || '';
      }
      result.push(param);
    }
  } else {
    //TODO any other case?
  }

  return result;
};

Swagger.prototype._mapRequestHeaders = function(slHeaders) {
  var result = [];

  for(var property in slHeaders.properties) {
    var param = slHeaders.properties[property];
    param.name = property;
    param.in = 'header';
    param.required = slHeaders.required && (slHeaders.required.indexOf(property) >= 0);
    param.description = slHeaders.properties[property].description || '';
    result.push(param);
  }
  return result;
};

Swagger.prototype._mapSchema = function(slSchemas) {
  var result = {};
  for (var i in slSchemas) {
    var schema = slSchemas[i];
    result[schema.NameSpace] = jsonHelper.parse(schema.Definition);
  }
  return result;
};

Swagger.prototype._mapEndpoints = function (swaggerDef, env) {
  var endpoints = this.project.Endpoints;
  for(var i in endpoints) {

    var endpoint = endpoints[i], parameters = [];

    if (!swaggerDef.paths[endpoint.Path]) {
      swaggerDef.paths[endpoint.Path] = {
         parameters: validateParameters(this._mapURIParams(endpoint.PathParams))
      };
    }
    swaggerDef.securityDefinitions = this._mapSecurityDefinitions(this.project.Environment.SecuritySchemes);
    parameters = parameters.concat(this._mapQueryString(endpoint.QueryString));
    parameters = parameters.concat(this._mapRequestBody(endpoint.Body));
    parameters = parameters.concat(this._mapRequestHeaders(endpoint.Headers));
    parameters = validateParameters(parameters);

    var responses = this._mapResponseBody(endpoint.Responses);
    swaggerDef.paths[endpoint.Path][endpoint.Method] = constructSwaggerMethod(endpoint, parameters, responses, env);
    //Is it OK to include produces/consumes in all cases?

    var security = [];
    if (endpoint.SecuredBy && !endpoint.SecuredBy.none) {
      swaggerDef.paths[endpoint.Path][endpoint.Method]['security'] = this._mapEndpointSecurity(endpoint.SecuredBy, this.project.Environment.SecuritySchemes);
    }
  }
};

Swagger.prototype._mapHostAndProtocol = function (env, swaggerDef) {
  var hostUrl = url.parse(env.Host);
  var swaggerHost = hostUrl.hostname || '';
  if (swaggerHost && hostUrl.port) {
    swaggerHost = swaggerHost + ':' + hostUrl.port;
  }
  swaggerDef.Host = swaggerHost;

  if(env.Protocols && env.Protocols.length>0) {
    swaggerDef.schemes = env.Protocols.map(function(p){
      return p.toLowerCase();
    });
  } else if(hostUrl.protocol) {
    swaggerDef.schemes = [hostUrl.protocol.split(':')[0]];
  }
};

Swagger.prototype._export = function () {
  //TODO
  var swaggerDef = new SwaggerDefinition(this.project.Name, this.project.Description);
  var env = this.project.Environment;
  swaggerDef.info.version = env.Version;
  swaggerDef.BasePath = env.BasePath || '';

  this._mapHostAndProtocol(env, swaggerDef);

  if(env.DefaultResponseType) {
    swaggerDef.produces = [env.DefaultResponseType];
  }

  if(env.DefaultRequestType) {
    swaggerDef.consumes = [env.DefaultRequestType];
  }

  this._mapEndpoints(swaggerDef, env);

  swaggerDef.definitions = this._mapSchema(this.project.Schemas);

  //if not security definition added, then don't keep the field anymore
  if (swaggerDef.securityDefinitions && Object.keys(swaggerDef.securityDefinitions).length <= 0) {
    delete swaggerDef['securityDefinitions'];
  }
  this.data = jsonHelper.toJSON(swaggerDef);
};

module.exports = Swagger;
<|endoftext|>


<commit_before>var exec = require( 'child_process' ).exec
  , path = require( 'path' )
  , fs = require( 'fs' )
  , mime = require( 'mime' )
  , os = require( 'os' )
  , outDir = path.join( os.tmpdir(), "textract" );

var extractText = function( filePath, options, cb ) {
  var fileTempOutPath = path.join(outDir, path.basename(filePath, path.extname(filePath)))
    , execOptions = {};

  if (options.images && options.images.exec) {
    execOptions = options.images.exec;
  } else {
    if (options.images) {
      execOptions = options.images;
    }
  }

  // escape the paths for the tesseract command
  var escapedFilePath = filePath.replace(/\s/g, '\\ ');
  var escapedFileTempOutPath = fileTempOutPath.replace(/\s/g, '\\ ');

  var tesseractCmd = "tesseract " + escapedFilePath + " " + escapedFileTempOutPath;
  if ( options.tesseract && options.tesseract.lang ) {
    tesseractCmd += " -l " + options.tesseract.lang;
  }
  tesseractCmd += " quiet";

  console.log(tesseractCmd)

  exec( tesseractCmd, execOptions,
    function ( error, stdout, stderr ) {
      if ( error !== null ) {
        error = new Error( "Error extracting [[ " + filePath + " ]], exec error: " + error );
        cb( error, null );
        return;
      }

      fs.exists(fileTempOutPath + ".txt", function( exists ) {
        if ( exists ) {
          fs.readFile(fileTempOutPath + ".txt", "utf8", function( error, text ) {
            if (error) {
              error = new Error( "Error reading tesseract output at [[ " + fileTempOutPath + " ]], error: " + error );
              cb( error, null );
            } else {
              fs.unlink(fileTempOutPath + ".txt", function(error) {
                if (error) {
                  error = new Error( "Error, tesseract, cleaning up temp file [[ " + fileTempOutPath + " ]], error: " + error );
                  cb( error, null );
                } else {
                  cb( null, text.toString() )
                }
              })
            }
          });
        } else {
          error = new Error( "Error reading tesseract output at [[ " + fileTempOutPath + " ]], file does not exist" );
          cb( error, null );
        }
      });
    }
  );
};

var testForBinary = function( cb ) {
  exec('tesseract',
    function (error, stdout, stderr) {
      if (error && error.toString().indexOf("tesseract") > -1 || stderr && stderr.toString().indexOf("tesseract") > -1) {
        cb( true );
      } else {
        console.error( "textract: 'tesseract' does not appear to be installed, so it will be unable to extract images." );
        cb( false );
      }
    }
  );
};

if (!fs.existsSync(outDir)) {
  fs.mkdirSync(outDir);
}

module.exports = {
  types: ["image/png", "image/jpeg", "image/gif"],
  extract: extractText,
  test: testForBinary
};<commit_msg>stray console<commit_after>var exec = require( 'child_process' ).exec
  , path = require( 'path' )
  , fs = require( 'fs' )
  , mime = require( 'mime' )
  , os = require( 'os' )
  , outDir = path.join( os.tmpdir(), "textract" );

var extractText = function( filePath, options, cb ) {
  var fileTempOutPath = path.join(outDir, path.basename(filePath, path.extname(filePath)))
    , execOptions = {};

  if (options.images && options.images.exec) {
    execOptions = options.images.exec;
  } else {
    if (options.images) {
      execOptions = options.images;
    }
  }

  // escape the paths for the tesseract command
  var escapedFilePath = filePath.replace(/\s/g, '\\ ');
  var escapedFileTempOutPath = fileTempOutPath.replace(/\s/g, '\\ ');

  var tesseractCmd = "tesseract " + escapedFilePath + " " + escapedFileTempOutPath;
  if ( options.tesseract && options.tesseract.lang ) {
    tesseractCmd += " -l " + options.tesseract.lang;
  }
  tesseractCmd += " quiet";

  exec( tesseractCmd, execOptions,
    function ( error, stdout, stderr ) {
      if ( error !== null ) {
        error = new Error( "Error extracting [[ " + filePath + " ]], exec error: " + error );
        cb( error, null );
        return;
      }

      fs.exists(fileTempOutPath + ".txt", function( exists ) {
        if ( exists ) {
          fs.readFile(fileTempOutPath + ".txt", "utf8", function( error, text ) {
            if (error) {
              error = new Error( "Error reading tesseract output at [[ " + fileTempOutPath + " ]], error: " + error );
              cb( error, null );
            } else {
              fs.unlink(fileTempOutPath + ".txt", function(error) {
                if (error) {
                  error = new Error( "Error, tesseract, cleaning up temp file [[ " + fileTempOutPath + " ]], error: " + error );
                  cb( error, null );
                } else {
                  cb( null, text.toString() )
                }
              })
            }
          });
        } else {
          error = new Error( "Error reading tesseract output at [[ " + fileTempOutPath + " ]], file does not exist" );
          cb( error, null );
        }
      });
    }
  );
};

var testForBinary = function( cb ) {
  exec('tesseract',
    function (error, stdout, stderr) {
      if (error && error.toString().indexOf("tesseract") > -1 || stderr && stderr.toString().indexOf("tesseract") > -1) {
        cb( true );
      } else {
        console.error( "textract: 'tesseract' does not appear to be installed, so it will be unable to extract images." );
        cb( false );
      }
    }
  );
};

if (!fs.existsSync(outDir)) {
  fs.mkdirSync(outDir);
}

module.exports = {
  types: ["image/png", "image/jpeg", "image/gif"],
  extract: extractText,
  test: testForBinary
};<|endoftext|>


<commit_before>// String \\

TypeFactory.proto.makeList = function(env) {
  var object = new GenericObject(env, env.proto['object']);

/*
- sort(func) -> this
- slice(???) -> list
*/

  // count
  object.properties['count'] = env.set( TypeFactory.makeNativeFunction(env, function PrimalList_count(precScope) {
    return env.set(TypeFactory.makeInteger(env, this.length));
  }));

  // push
  object.properties['push'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope /* , obj...*/) {
    var thisobj = this;
    var args = Array.prototype.slice.call(arguments);
    args.shift();

    var index = this.length;
    args.forEach(function(obj) {
      thisobj.setPropertyPointer(index++, obj);
    });
    this.length += args.length;
    return env.set(this);
  }));

  // pop
  object.properties['pop'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope) {
    var last = (this.length > 0) ? this.length-1 : 0;
    var addr = this.getPropertyPointer(last);
    delete this.properties[last];
    this.length--;
    return addr;
  }));

  // shift
  object.properties['shift'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope) {
    var addr = this.getPropertyPointer(0);
    for(var prop in this.properties) {
      if(!isInt(prop)) continue;
      if(parseInt(prop) == 0) continue;
      this.setPropertyPointer(parseInt(prop)-1, this.getPropertyPointer(prop));
      delete this.properties[prop];
    }
    this.length--;
    return addr;
  }));

  // unshift
  object.properties['unshift'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope /*, objects */) {
    var thisobj = this;
    var args = Array.prototype.slice.call(arguments);
    args.shift();

    // shift current properties
    for(var prop=this.length-1; prop >= 0; prop--) {
      this.setPropertyPointer(parseInt(prop)+args.length, this.getPropertyPointer(prop));
    }

    args.forEach(function(addr, i) {
      thisobj.setPropertyPointer(i, addr);
    });
    this.length += args.length;
    return env.set(this);
  }));

  // join
  object.properties['join'] = env.set( TypeFactory.makeNativeFunction(env, function PrimalList_count(precScope, seperator) {
    seperator = (seperator !== 0 && seperator !== undefined) ? env.resolve(seperator) : '';
    var joined = '';
    for(var prop in this.properties) {
      if(!isInt(prop)) continue;
      joined += env.cast('string', env.resolve(this.getPropertyPointer(prop))).getVal() + seperator;
    }
    if(joined.length > seperator.length) joined = joined.substr(0, joined.length - seperator.length);
    return env.set(TypeFactory.makeString(env, joined));
  }));

  // map
  object.properties['map'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope, iteratorfunc) {
      var thisaddr = env.set(this);
      var newlist = TypeFactory.makeList(env);
      var i = 0;
      for(var prop in this.properties) {
        if(!isInt(prop)) continue;
        var bool = iteratorfunc.invoke(thisaddr, [ this.properties[prop], env.set(TypeFactory.makeInteger(prop)) ], precScope);
        if(env.cast('bool', env.resolve(bool)).getVal() !== true) newlist[i++] = this.properties[prop];
      }
      return env.set(newlist);
  }));

  return object;
};

TypeFactory.makeList = function makeList(env, list) {
  var object = new GenericObject(env, env.proto['list']);
  object.isPrimal = true;
  object.length = list.length;

  list.forEach(function(addr, i) {
    object.setPropertyPointer(i, addr);
  });

  object.dump = function(level, cyclic) {
    if(this.isPrimal) {
      level = (level) ? level : 1;
      cyclic = (cyclic) ? cyclic : [];
      cyclic.push(this);

      var padding = repeatString('\t', level);

      var dump = [];
      for(var prop in this.properties) {
        if(isInt(prop)) {
          var obj = this.env.resolve(this.properties[prop]);
          if(cyclic.indexOf(obj) !== -1) {
            dump.push('Cyclic');
            continue;
          }
          dump.push(obj.dump(level+1, copyObject(cyclic)));
        }
      }
      return '<\r\n'+padding+dump.join(', \r\n'+padding)+'\r\n'+repeatString('\t', level-1)+'>';
    }
    return GenericObject.prototype.dump.call(this, level, cyclic);
  };

  object.setPropertyPointer = function(property, addr) {
    if(this.isPrimal && property == 'each') this.isPrimal = false; // Deprive primal status if the read property is modified
    return GenericObject.prototype.setPropertyPointer.call(this, property, addr);
  };

  // each
  object.properties['each'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope, iteratorfunc) {
      var thisaddr = env.set(this);
      for(var prop in this.properties) if(isInt(prop)) iteratorfunc.invoke(thisaddr, [this.properties[prop], env.set(TypeFactory.makeInteger(prop))], precScope);
      return thisaddr;
  }));

  return object;
};<commit_msg>fix List.each<commit_after>// String \\

TypeFactory.proto.makeList = function(env) {
  var object = new GenericObject(env, env.proto['object']);

/*
- sort(func) -> this
- slice(???) -> list
*/

  // count
  object.properties['count'] = env.set( TypeFactory.makeNativeFunction(env, function PrimalList_count(precScope) {
    return env.set(TypeFactory.makeInteger(env, this.length));
  }));

  // push
  object.properties['push'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope /* , obj...*/) {
    var thisobj = this;
    var args = Array.prototype.slice.call(arguments);
    args.shift();

    var index = this.length;
    args.forEach(function(obj) {
      thisobj.setPropertyPointer(index++, obj);
    });
    this.length += args.length;
    return env.set(this);
  }));

  // pop
  object.properties['pop'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope) {
    var last = (this.length > 0) ? this.length-1 : 0;
    var addr = this.getPropertyPointer(last);
    delete this.properties[last];
    this.length--;
    return addr;
  }));

  // shift
  object.properties['shift'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope) {
    var addr = this.getPropertyPointer(0);
    for(var prop in this.properties) {
      if(!isInt(prop)) continue;
      if(parseInt(prop) == 0) continue;
      this.setPropertyPointer(parseInt(prop)-1, this.getPropertyPointer(prop));
      delete this.properties[prop];
    }
    this.length--;
    return addr;
  }));

  // unshift
  object.properties['unshift'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope /*, objects */) {
    var thisobj = this;
    var args = Array.prototype.slice.call(arguments);
    args.shift();

    // shift current properties
    for(var prop=this.length-1; prop >= 0; prop--) {
      this.setPropertyPointer(parseInt(prop)+args.length, this.getPropertyPointer(prop));
    }

    args.forEach(function(addr, i) {
      thisobj.setPropertyPointer(i, addr);
    });
    this.length += args.length;
    return env.set(this);
  }));

  // join
  object.properties['join'] = env.set( TypeFactory.makeNativeFunction(env, function PrimalList_count(precScope, seperator) {
    seperator = (seperator !== 0 && seperator !== undefined) ? env.resolve(seperator) : '';
    var joined = '';
    for(var prop in this.properties) {
      if(!isInt(prop)) continue;
      joined += env.cast('string', env.resolve(this.getPropertyPointer(prop))).getVal() + seperator;
    }
    if(joined.length > seperator.length) joined = joined.substr(0, joined.length - seperator.length);
    return env.set(TypeFactory.makeString(env, joined));
  }));

  // map
  object.properties['map'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope, iteratorfunc) {
      var thisaddr = env.set(this);
      var newlist = TypeFactory.makeList(env);
      var i = 0;
      for(var prop in this.properties) {
        if(!isInt(prop)) continue;
        var bool = iteratorfunc.invoke(thisaddr, [ this.properties[prop], env.set(TypeFactory.makeInteger(prop)) ], precScope);
        if(env.cast('bool', env.resolve(bool)).getVal() !== true) newlist[i++] = this.properties[prop];
      }
      return env.set(newlist);
  }));

  return object;
};

TypeFactory.makeList = function makeList(env, list) {
  var object = new GenericObject(env, env.proto['list']);
  object.isPrimal = true;
  object.length = list.length;

  list.forEach(function(addr, i) {
    object.setPropertyPointer(i, addr);
  });

  object.dump = function(level, cyclic) {
    if(this.isPrimal) {
      level = (level) ? level : 1;
      cyclic = (cyclic) ? cyclic : [];
      cyclic.push(this);

      var padding = repeatString('\t', level);

      var dump = [];
      for(var prop in this.properties) {
        if(isInt(prop)) {
          var obj = this.env.resolve(this.properties[prop]);
          if(cyclic.indexOf(obj) !== -1) {
            dump.push('Cyclic');
            continue;
          }
          dump.push(obj.dump(level+1, copyObject(cyclic)));
        }
      }
      return '<\r\n'+padding+dump.join(', \r\n'+padding)+'\r\n'+repeatString('\t', level-1)+'>';
    }
    return GenericObject.prototype.dump.call(this, level, cyclic);
  };

  object.setPropertyPointer = function(property, addr) {
    if(this.isPrimal && property == 'each') this.isPrimal = false; // Deprive primal status if the read property is modified
    return GenericObject.prototype.setPropertyPointer.call(this, property, addr);
  };

  // each
  object.properties['each'] = env.set( TypeFactory.makeNativeFunction(env, function(precScope, iteratorfunc) {
      var thisaddr = env.set(this);
      iteratorfunc = env.resolve(iteratorfunc);
      for(var prop in this.properties) {
        if(!isInt(prop)) continue;
        iteratorfunc.invoke(thisaddr, [this.properties[prop], env.set(TypeFactory.makeInteger(env, prop))], precScope);
      }
      return thisaddr;
  }));

  return object;
};<|endoftext|>


<commit_before>// For given path returns root package path.
// If given path doesn't point to package content then null is returned.

'use strict';

var stat       = require('fs').stat
  , dirname    = require('path').dirname
  , contains   = require('es5-ext/lib/Array/prototype/contains')
  , dirExists  = require('./fs/dir-exists')
  , fileExists = require('./fs/file-exists')
  , normalize  = require('./path/normalize')
  , separator  = require('./path/separator')

  , isPackageRoot, cache = [];

cache.contains = contains;

isPackageRoot = function (path, callback) {
	if (cache.contains(path)) {
		callback(null, path);
		return;
	}
	fileExists(path + '/package.json', function (exists) {
		if (exists) {
			cache.push(path);
			callback(null, path);
			return;
		}
		dirExists(path + '/node_modules', function (exists) {
			var parentpath;
			if (exists) {
				cache.push(path);
				callback(null, path);
			} else {
				parentpath = dirname(path);
				if (parentpath === path) {
					callback(null, null);
				} else if (parentpath.slice(parentpath.lastIndexOf(separator) + 1)
						=== 'node_modules') {
					cache.push(path);
					callback(null, path);
				} else {
					isPackageRoot(parentpath, callback);
				}
			}
		});
	});
};

module.exports = function find(path, callback) {
	path = normalize(path);
	stat(path, function (err, stats) {
		if (err) {
			if (dirname(path) !== path) {
				find(dirname(path), callback);
			} else {
				callback(null, null);
			}
			return;
		}
		if (stats.isDirectory()) {
			isPackageRoot(path, callback);
		} else {
			isPackageRoot(dirname(path), callback);
		}
	});
};
<commit_msg>Fixed path resolution logic in findPackageRoot (so it's bulletproof for *nix and windows systems)<commit_after>// For given path returns root package path.
// If given path doesn't point to package content then null is returned.

'use strict';

var stat       = require('fs').stat
  , path       = require('path')
  , basename   = path.basename
  , dirname    = path.dirname
  , resolve    = path.resolve
  , contains   = require('es5-ext/lib/Array/prototype/contains')
  , dirExists  = require('./fs/dir-exists')
  , fileExists = require('./fs/file-exists')

  , isPackageRoot, cache = [];

cache.contains = contains;

isPackageRoot = function (path, callback) {
	if (cache.contains(path)) {
		callback(null, path);
		return;
	}
	fileExists(path + '/package.json', function (exists) {
		if (exists) {
			cache.push(path);
			callback(null, path);
			return;
		}
		dirExists(path + '/node_modules', function (exists) {
			var parentpath;
			if (exists) {
				cache.push(path);
				callback(null, path);
			} else {
				parentpath = dirname(path);
				if (parentpath === path) {
					callback(null, null);
				} else if (basename(parentpath) === 'node_modules') {
					cache.push(path);
					callback(null, path);
				} else {
					isPackageRoot(parentpath, callback);
				}
			}
		});
	});
};

module.exports = function find(path, callback) {
	path = resolve(String(path));
	stat(path, function (err, stats) {
		if (err) {
			if (dirname(path) !== path) {
				find(dirname(path), callback);
			} else {
				callback(null, null);
			}
			return;
		}
		if (stats.isDirectory()) {
			isPackageRoot(path, callback);
		} else {
			isPackageRoot(dirname(path), callback);
		}
	});
};
<|endoftext|>