<commit_before>define([
    'require', // Require is needed for solving circular dependency
    'backbone',
    'views/base_view',
    'views/input_view',
    'views/editable-text',
    'views/editable/rating',
    'views/generic/list',
    'views/activity/container',
], function (require, Backbone, BaseView, Editable,
    EditableText, EditableRating, ListView, ActivityContainer) {
    var OverviewItem = BaseView.extend({
        tagName: "div",
        className: function () {
            var cls = "result-overview";
            // Automatically open results on levels up to open_result_level
            if (this.model.get("level") <= Aptivate.data.conf.open_result_level) {
                cls += " show";
            }
            return cls;
        },
        template_selector: "#result-overview-container",

        events: {
            "click .edit-result, .monitor-result": "followLink",
            "click .toggle-triangle": "toggleDetails"
        },

        followLink: function (e) {
            e.preventDefault();
            Aptivate.status.router.navigate(
                this.$(e.target).attr("href"), {trigger: true});
        },

        setShow: function (target, show) {
            var action = show ? "addClass" : "removeClass";
            this.$(target).parents("table")
                          .parent()
                          .add(target) // Change also on toggle
                          [action]("show");
        },

        toggleDetails: function (e) {
            var level = this.model.get('level'),
                seen = $(e.target).hasClass("show");

            this.show = !seen;
            this.setShow(e.target, this.show);
            if (!this.rerendered && level === Aptivate.data.conf.max_result_level) {
                this.render();
                this.rerendered = true;
                // e.target here points to the wrong element (the one already
                // removed from DOM)
                if (this.show) {
                    this.$(".toggle-triangle:first").addClass("show");
                }
            }
            e.stopPropagation();
        },

        // INIT
        initialize: function () {
            var model_id = this.model.get("id");
            this.model.activities = Aptivate.logframe.activities.subcollection({
                filter: function (activity) {
                    return activity.get("result") === model_id;
                }
            });

            Backbone.Subviews.add(this);
            this.$el.addClass("level-" + this.model.get("level"));
        },

        getTemplateData: function (data) {
            if (this.model.get("level") <= Aptivate.data.conf.open_result_level) {
                data.open_toggle = " show";
            }
            return data;
        },

        subviewCreators: {
            resultName: function () {
                return new Editable({
                    model: this.model,
                    template_selector: "#editable-title",
                    attributes: { class: "ribbon ribbon-result" },
                });
            },
            resultDescription: function () {
                return new EditableText({
                    model: this.model,
                    template_selector: "#editable-description"
                });
            },
            resultRating: function () {
                return new EditableRating({
                    model: this.model,
                    options: Aptivate.data.ratings
                });
            },
            overviewItems: function () {
                var level = this.model.get('level'),
                    logframe = this.model.get('log_frame'),
                    resultId = this.model.get('id');
                if (level < Aptivate.data.conf.max_result_level) {
                    return this.resultOverviewView(logframe, resultId, level);
                } else {
                    return this.show ? this.activityOverviewView(logframe, resultId): null;
                }
            }
        },

        resultOverviewView: function (logframe, result, level){
            var model_id = this.model.get("id"),
                collection = Aptivate.logframe.results.subcollection({
                    filter: function (result) {
                        return result.get("parent") === model_id;
                    }
                });
            var listView = new ListView({
                className: "result-children",
                itemView: OverviewItem,
                collection: collection,
                newModelOptions: {
                    log_frame: logframe,
                    parent: result,
                    level: level + 1
                }
            });
            if (level === 1){
                listView.maxLength = 1;
            }
            return listView;
        },

        activityOverviewView: function (logframe, result) {
            return new ListView({
                className: "activity-container",
                itemView: ActivityContainer,
                collection: this.model.activities,
                newModelOptions: {
                    log_frame: logframe,
                    result: result
                }
            });
        }
    });

    return OverviewItem;
});
<commit_msg>Incremental rendering of overview page<commit_after>define([
    'require', // Require is needed for solving circular dependency
    'backbone',
    'views/base_view',
    'views/input_view',
    'views/editable-text',
    'views/editable/rating',
    'views/generic/list',
    'views/activity/container',
], function (require, Backbone, BaseView, Editable,
    EditableText, EditableRating, ListView, ActivityContainer) {
    var OverviewItem = BaseView.extend({
        tagName: "div",
        className: function () {
            var cls = "result-overview";
            // Automatically open results on levels up to open_result_level
            if (this.model.get("level") <= Aptivate.data.conf.open_result_level) {
                cls += " show";
                this.show = true;
            } else {
                this.show = false;
            }
            return cls;
        },
        template_selector: "#result-overview-container",

        events: {
            "click .edit-result, .monitor-result": "followLink",
            "click .toggle-triangle": "toggleDetails"
        },

        followLink: function (e) {
            e.preventDefault();
            Aptivate.status.router.navigate(
                this.$(e.target).attr("href"), {trigger: true});
        },

        setShow: function (target, show) {
            var action = show ? "addClass" : "removeClass";
            this.$(target).parents("table")
                          .parent()
                          .add(target) // Change also on toggle
                          [action]("show");
        },

        toggleDetails: function (e) {
            var seen = $(e.target).hasClass("show");

            this.show = !seen;
            this.setShow(e.target, this.show);
            if (!this.rerendered) {
                this.render();
                this.rerendered = true;
                // e.target here points to the wrong element (the one already
                // removed from DOM)
                if (this.show) {
                    this.$(".toggle-triangle:first").addClass("show");
                } else {
                    this.$(".toggle-triangle:first").removeClass("show");
                }
            }
            e.stopPropagation();
        },

        // INIT
        initialize: function () {
            var model_id = this.model.get("id");
            this.model.activities = Aptivate.logframe.activities.subcollection({
                filter: function (activity) {
                    return activity.get("result") === model_id;
                }
            });

            Backbone.Subviews.add(this);
            this.$el.addClass("level-" + this.model.get("level"));
        },

        getTemplateData: function (data) {
            if (this.model.get("level") <= Aptivate.data.conf.open_result_level) {
                data.open_toggle = " show";
            }
            return data;
        },

        subviewCreators: {
            resultName: function () {
                return new Editable({
                    model: this.model,
                    template_selector: "#editable-title",
                    attributes: { class: "ribbon ribbon-result" },
                });
            },
            resultDescription: function () {
                return new EditableText({
                    model: this.model,
                    template_selector: "#editable-description"
                });
            },
            resultRating: function () {
                return new EditableRating({
                    model: this.model,
                    options: Aptivate.data.ratings
                });
            },
            overviewItems: function () {
                return this.show ? this.renderSubItems() : null;
            }
        },

        renderSubItems: function () {
            var level = this.model.get('level'),
                logframe = this.model.get('log_frame'),
                resultId = this.model.get('id');
            if (level < Aptivate.data.conf.max_result_level) {
                return this.resultOverviewView(logframe, resultId, level);
            } else {
                return this.show ? this.activityOverviewView(logframe, resultId): null;
            }
        },

        resultOverviewView: function (logframe, result, level){
            var model_id = this.model.get("id"),
                collection = Aptivate.logframe.results.subcollection({
                    filter: function (result) {
                        return result.get("parent") === model_id;
                    }
                });
            var listView = new ListView({
                className: "result-children",
                itemView: OverviewItem,
                collection: collection,
                newModelOptions: {
                    log_frame: logframe,
                    parent: result,
                    level: level + 1
                }
            });
            if (level === 1){
                listView.maxLength = 1;
            }
            return listView;
        },

        activityOverviewView: function (logframe, result) {
            return new ListView({
                className: "activity-container",
                itemView: ActivityContainer,
                collection: this.model.activities,
                newModelOptions: {
                    log_frame: logframe,
                    result: result
                }
            });
        }
    });

    return OverviewItem;
});
<|endoftext|>


<commit_before>var Backbone = require('backbone');

/**
 * Collection of Dataviews
 */
module.exports = Backbone.Collection.extend({
  initialize: function () {
    // If a histogram model applies the histogram sizes, rest should remove/disable
    // the sizes applied before.
    this.bind('change:histogram_sizes', function (m, isSizesApplied) {
      if (isSizesApplied) {
        this.each(function (mdl) {
          if (mdl !== m && mdl.layer.get('layer_name') === m.layer.get('layer_name') && mdl.get('histogram_sizes')) {
            mdl.set('histogram_sizes', false);
          }
        });
      }

    }, this);
  },

  getTemporaryStyles: function () {
    var tempStyles = {};
    this.each(function (mdl) {
      if (mdl.tempStyle) {
        var layers = mdl.layer.collection.filter(function(l){return l.get('type') === 'CartoDB'})
        tempStyles[layers.indexOf(mdl.layer)] = mdl.tempStyle
      }
    });
    return tempStyles
  }
});
<commit_msg>deletes tempstyle of overwritten dataview model<commit_after>var Backbone = require('backbone');

/**
 * Collection of Dataviews
 */
module.exports = Backbone.Collection.extend({
  initialize: function () {
    // If a histogram model applies the histogram sizes, rest should remove/disable
    // the sizes applied before.
    this.bind('change:histogram_sizes', function (m, isSizesApplied) {
      if (isSizesApplied) {
        this.each(function (mdl) {
          if (mdl !== m && mdl.layer.get('layer_name') === m.layer.get('layer_name') && mdl.get('histogram_sizes')) {
            mdl.set('histogram_sizes', false);
            delete mdl.tempStyle
          }
        });
      }

    }, this);
  },

  getTemporaryStyles: function () {
    var tempStyles = {};
    this.each(function (mdl) {
      if (mdl.tempStyle) {
        var layers = mdl.layer.collection.filter(function(l){return l.get('type') === 'CartoDB'})
        tempStyles[layers.indexOf(mdl.layer)] = mdl.tempStyle
      }
    });
    return tempStyles
  }
});
<|endoftext|>


<commit_before>/**
 * Created by JongHyeok Choi on 2017. 5. 23..
 */

"use strict"

const {Analyzer, FSUrlLoader} = require('polymer-analyzer');
const _ = require('underscore');
const fs = require('fs');
const lineColumn = require('line-column');

/**
 * Custom Module
 */
const UTIL = require('./lib/util.js');
const MODE = require('./lib/mode.js');
const CaseMap = require('./lib/case-map.js');

/**
 * (Required) Package Root Path
 */
let analyzer = new Analyzer({
    urlLoader: new FSUrlLoader('./'),
});

/**
 * Generate Data for Template
 */
module.exports = function (path, id) {
    const CONFIG = this;
    return new Promise((resolve, reject) => {
        analyzer.analyze([path]).then((analysis) => {
            const [element,] = analysis.getFeatures(
                {kind: 'element', id: id, externalPackages: true});

            if (element) {
                /**
                 * [Element Object Example]
                 * let eleObj = {
                    is: "element-id",
                    desc: "element-desc",
                    props: [
                        {
                            name: "property-name",
                            desc: "property-desc",
                            type: "property-type",
                            valueList: [
                                {value: "value-1", desc: "desc-1"},
                                {value: "value-2", desc: "desc-2"},
                                {value: "value-3", desc: "desc-3"}
                            ]
                        }
                    ],
                    methods: [
                        {name: "function-name", content: "function-content", desc: "function-desc"},
                        {name: "function-name2", content: "function-content2", desc: "function-desc2"}
                    ]
                }*/

                let eleObj = {
                    is: id, //polymer id
                    props: [],  //property
                    desc: element.description, //description
                    methods: [] //method
                };

                //name : event name, property : event info object
                for(const [name, event] of element.events) {

                    let jsdoc = event.jsdoc;
                    //Event Base Obj
                    let eventObj = {
                        //ex) response -> on-response
                        name: `on-${name}`,

                        //jsdoc Y -> Event , N -> notify
                        desc: stringEscape(
                            (jsdoc &&  jsdoc.description) ?
                                jsdoc.description : element.properties.get(CaseMap.getPropNameByEvent(name)).description
                        ),

                        type: "event",

                        //value : response -> onResponse
                        //desc : response 이벤트가 반생하면 실행되는 콜백함수를 등록하세요.
                        valueList: [{
                            value: `on${name.charAt(0).toUpperCase() + CaseMap.dashToCamelCase(name).slice(1)}`,
                            desc: `'${name}' 이벤트가 발생하면 실행되는 콜백함수를 등록하세요.`
                        }]
                    };

                    eleObj.props.push(eventObj);
                }

                //name : property name, property : property info object
                for (const [name, property] of element.properties) {

                    let jsdoc = property.jsdoc;

                    //Value Input
                    let valueList = [];
                    if(jsdoc.tags && jsdoc.tags.length > 0) {
                        jsdoc.tags.forEach(tag => {
                            //You can custom setting using autocomplete.config.js value_annotation
                            if(tag.title == CONFIG.value_annotation) {
                                let tagSplit = tag.description.split(":");
                                let tagValue = tagSplit[0] || "";
                                let tagDesc  = tagSplit[1] || "";

                                valueList.push({
                                    value: tagValue,
                                    desc: tagDesc
                                });
                            }
                        });
                    }

                    //Property Base Obj
                    let propObj = {
                        name: name,
                        propName: name,
                        desc: stringEscape(property.description) ||  "",
                        valueList: valueList,
                        type: property.type || ""
                    };

                    //If property type is 'Function', and continue next property.
                    if(property.type === "Function") {
                        continue;
                    }

                    //Reference File ->  ./lib/mode.js
                    if (CONFIG.mode === MODE.ALL) {
                        eleObj.props.push(propObj);

                    } else if(property.privacy === "public") {

                        if (CONFIG.mode === MODE.PUBLIC) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.EXIST_ANNOTATION && jsdoc.tags && jsdoc.tags.length > 0) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.EXIST_DESC && property.description) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.CUSTOM_ANNOTATION && jsdoc.tags && jsdoc.tags.length > 0 && (UTIL.containsByValArr(jsdoc.tags, CONFIG.custom_annotations, obj => obj.title))) {
                            eleObj.props.push(propObj)
                        }
                    }
                }

                //name : method name, method : method info object
                for (const [name, method] of element.methods) {
                    let methodObj = {
                        name: name,
                        methodName: name,
                        content: "",
                        desc: "",
                        params: []
                    };

                    //Element own method
                    if(element.inheritedFrom) {

                        eleObj.methods.push(methodObj);
                    }
                    //Inherited Method
                    else {

                        let fileSource = fs.readFileSync(method.sourceRange.file, 'utf8');

                        methodObj.content = getFunctionString(fileSource, method.sourceRange.start, method.sourceRange.end);
                        methodObj.desc = method.description || "";

                        method.params.forEach((param) => {
                            methodObj.params.push({
                                name: param.name,
                                paramName: param.name,
                                type: param.type || "입력",
                                desc: param.description || "입력"
                            });
                        });

                        eleObj.methods.push(methodObj);
                    }
                }

                resolve([eleObj]);

            } else {
                console.warn(`[${id}.html] didn't define.`);
                resolve([]);
            }
        });
    });
};

//String escape
function stringEscape(str) {
    if (typeof str !== "string") {
        return "";
    }

    return str.replace(/&/g, '&') // first!
        .replace(/>/g, '\>')
        .replace(/</g, '\<')
        .replace(/"/g, '\\"')
        .replace(/'/g, '\'')
        .replace(/`/g, '\`');
}

function getFunctionString(str, startObj, endObj) {
    let startIdx = lineColumn(str).toIndex({line: startObj.line + 1 , column: startObj.column + 1});
    let endIdx = lineColumn(str).toIndex({line: endObj.line + 1, column: endObj.column + 1});

    return str.substr(startIdx, endIdx-startIdx);
}<commit_msg>- JSON Description 개행 남아있는 버그 수정<commit_after>/**
 * Created by JongHyeok Choi on 2017. 5. 23..
 */

"use strict"

const {Analyzer, FSUrlLoader} = require('polymer-analyzer');
const _ = require('underscore');
const fs = require('fs');
const lineColumn = require('line-column');

/**
 * Custom Module
 */
const UTIL = require('./lib/util.js');
const MODE = require('./lib/mode.js');
const CaseMap = require('./lib/case-map.js');

/**
 * (Required) Package Root Path
 */
let analyzer = new Analyzer({
    urlLoader: new FSUrlLoader('./'),
});

/**
 * Generate Data for Template
 */
module.exports = function (path, id) {
    const CONFIG = this;
    return new Promise((resolve, reject) => {
        analyzer.analyze([path]).then((analysis) => {
            const [element,] = analysis.getFeatures(
                {kind: 'element', id: id, externalPackages: true});

            if (element) {
                /**
                 * [Element Object Example]
                 * let eleObj = {
                    is: "element-id",
                    desc: "element-desc",
                    props: [
                        {
                            name: "property-name",
                            desc: "property-desc",
                            type: "property-type",
                            valueList: [
                                {value: "value-1", desc: "desc-1"},
                                {value: "value-2", desc: "desc-2"},
                                {value: "value-3", desc: "desc-3"}
                            ]
                        }
                    ],
                    methods: [
                        {name: "function-name", content: "function-content", desc: "function-desc"},
                        {name: "function-name2", content: "function-content2", desc: "function-desc2"}
                    ]
                }*/

                let eleObj = {
                    is: id, //polymer id
                    props: [],  //property
                    desc: element.description, //description
                    methods: [] //method
                };

                //name : event name, property : event info object
                for(const [name, event] of element.events) {

                    let jsdoc = event.jsdoc;
                    //Event Base Obj
                    let eventObj = {
                        //ex) response -> on-response
                        name: `on-${name}`,

                        //jsdoc Y -> Event , N -> notify
                        desc: stringEscape(
                            (jsdoc &&  jsdoc.description) ?
                                jsdoc.description : element.properties.get(CaseMap.getPropNameByEvent(name)).description
                        ),

                        type: "event",

                        //value : response -> onResponse
                        //desc : response 이벤트가 반생하면 실행되는 콜백함수를 등록하세요.
                        valueList: [{
                            value: `on${name.charAt(0).toUpperCase() + CaseMap.dashToCamelCase(name).slice(1)}`,
                            desc: `'${name}' 이벤트가 발생하면 실행되는 콜백함수를 등록하세요.`
                        }]
                    };

                    eleObj.props.push(eventObj);
                }

                //name : property name, property : property info object
                for (const [name, property] of element.properties) {

                    let jsdoc = property.jsdoc;

                    //Value Input
                    let valueList = [];
                    if(jsdoc.tags && jsdoc.tags.length > 0) {
                        jsdoc.tags.forEach(tag => {
                            //You can custom setting using autocomplete.config.js value_annotation
                            if(tag.title == CONFIG.value_annotation) {
                                let tagSplit = tag.description.split(":");
                                let tagValue = tagSplit[0] || "";
                                let tagDesc  = tagSplit[1] || "";

                                valueList.push({
                                    value: tagValue,
                                    desc: tagDesc
                                });
                            }
                        });
                    }

                    //Property Base Obj
                    let propObj = {
                        name: name,
                        propName: name,
                        desc: stringEscape(property.description) ||  "",
                        valueList: valueList,
                        type: property.type || ""
                    };

                    //If property type is 'Function', and continue next property.
                    if(property.type === "Function") {
                        continue;
                    }

                    //Reference File ->  ./lib/mode.js
                    if (CONFIG.mode === MODE.ALL) {
                        eleObj.props.push(propObj);

                    } else if(property.privacy === "public") {

                        if (CONFIG.mode === MODE.PUBLIC) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.EXIST_ANNOTATION && jsdoc.tags && jsdoc.tags.length > 0) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.EXIST_DESC && property.description) {
                            eleObj.props.push(propObj)
                        } else if (CONFIG.mode === MODE.CUSTOM_ANNOTATION && jsdoc.tags && jsdoc.tags.length > 0 && (UTIL.containsByValArr(jsdoc.tags, CONFIG.custom_annotations, obj => obj.title))) {
                            eleObj.props.push(propObj)
                        }
                    }
                }

                //name : method name, method : method info object
                for (const [name, method] of element.methods) {
                    let methodObj = {
                        name: name,
                        methodName: name,
                        content: "",
                        desc: "",
                        params: []
                    };

                    //Element own method
                    if(element.inheritedFrom) {

                        eleObj.methods.push(methodObj);
                    }
                    //Inherited Method
                    else {

                        let fileSource = fs.readFileSync(method.sourceRange.file, 'utf8');

                        methodObj.content = getFunctionString(fileSource, method.sourceRange.start, method.sourceRange.end);
                        methodObj.desc = method.description || "";

                        method.params.forEach((param) => {
                            methodObj.params.push({
                                name: param.name,
                                paramName: param.name,
                                type: param.type || "입력",
                                desc: param.description || "입력"
                            });
                        });

                        eleObj.methods.push(methodObj);
                    }
                }

                resolve([eleObj]);

            } else {
                console.warn(`[${id}.html] didn't define.`);
                resolve([]);
            }
        });
    });
};

//String escape
function stringEscape(str) {
    if (typeof str !== "string") {
        return "";
    }

    return str.replace(/&/g, '&') // first!
        .replace(/>/g, '\>')
        .replace(/</g, '\<')
        .replace(/"/g, '\\"')
        .replace(/'/g, '\'')
        .replace(/\n/g, '')
        .replace(/`/g, '\`');
}

function getFunctionString(str, startObj, endObj) {
    let startIdx = lineColumn(str).toIndex({line: startObj.line + 1 , column: startObj.column + 1});
    let endIdx = lineColumn(str).toIndex({line: endObj.line + 1, column: endObj.column + 1});

    return str.substr(startIdx, endIdx-startIdx);
}<|endoftext|>


<commit_before>/*!
 * jquery-toCurrency Plugin for jQuery
 *
 * Version 0.1.1
 *
 * Copyright 2012, Luca Ongaro
 * Licensed under the MIT license.
 */
(function( $ ){
  "use strict";
  $.extend({
    toCurrency: function( val, opts ) {
      var val_str, reverse_whole_part, decimals, i,
          sign = "",
          whole_part = "",
          default_options = {
            precision: 2,
            delimiter: ",",
            separator: ".",
            unit: "€",
            format: "%u %n",
            negativeFormat: false
          };
      opts = $.extend( default_options, opts );

      val = parseFloat(val);
      if( isNaN(val) ) {
        throw new Error( "toCurrency error: invalid number format " + val );
      }
      if ( val < 0 ) {
        sign = "-";
      }

      val_str = val.toFixed( opts.precision ).replace( "-", "" );
      reverse_whole_part = val_str.split(".")[0].split("").reverse().join("");
      decimals = ( opts.precision > 0 ? opts.separator : "" ) + ( val_str.split(".")[1] || "" );

      for ( i = 0; i < reverse_whole_part.length; i++ ) {
        if ( i % 3 === 0 && i !== 0 ) {
          whole_part += opts.delimiter;
        }
        whole_part += reverse_whole_part.charAt(i);
      }
      whole_part = whole_part.split("").reverse().join("");

      if ( sign === "-" && opts.negativeFormat ) {
        return opts.negativeFormat.replace( "%n", whole_part + decimals ).replace( "%u", opts.unit );
      } else {
        return opts.format.replace( "%n", sign + whole_part + decimals ).replace( "%u", opts.unit );
      }
    }
  });

  $.fn.toCurrency = function( options ) {
    return this.each(function() {
      $(this).html( $.toCurrency( $(this).text(), options ) );
    });
  };
})( jQuery );<commit_msg>DRY code<commit_after>/*!
 * jquery-toCurrency Plugin for jQuery
 *
 * Version 0.1.1
 *
 * Copyright 2012, Luca Ongaro
 * Licensed under the MIT license.
 */
(function( $ ){
  "use strict";
  var reverseString = function(str) {
    return str.split("").reverse().join("");
  };

  $.extend({
    toCurrency: function( val, opts ) {
      var val_str, reverse_whole_part, decimals, i,
          sign = "",
          whole_part = "",
          default_options = {
            precision: 2,
            delimiter: ",",
            separator: ".",
            unit: "€",
            format: "%u %n",
            negativeFormat: false
          };
      opts = $.extend( default_options, opts );

      val = parseFloat(val);
      if( isNaN(val) ) {
        throw new Error( "toCurrency error: invalid number format " + val );
      }
      if ( val < 0 ) {
        sign = "-";
      }

      val_str = val.toFixed( opts.precision ).replace( "-", "" );
      reverse_whole_part = reverseString(val_str.split(".")[0]);
      decimals = ( opts.precision > 0 ? opts.separator : "" ) + ( val_str.split(".")[1] || "" );

      for ( i = 0; i < reverse_whole_part.length; i++ ) {
        if ( i % 3 === 0 && i !== 0 ) {
          whole_part += opts.delimiter;
        }
        whole_part += reverse_whole_part.charAt(i);
      }
      whole_part = reverseString(whole_part);

      if ( sign === "-" && opts.negativeFormat ) {
        return opts.negativeFormat.replace( "%n", whole_part + decimals ).replace( "%u", opts.unit );
      } else {
        return opts.format.replace( "%n", sign + whole_part + decimals ).replace( "%u", opts.unit );
      }
    }
  });

  $.fn.toCurrency = function( options ) {
    return this.each(function() {
      $(this).html( $.toCurrency( $(this).text(), options ) );
    });
  };
})( jQuery );<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var questionsCollection = require('./questions');
var util = require('./util');
var _ = require('lodash');
var asciiArt = fs.readFileSync(path.join(__dirname, 'asciiArt.txt'),'utf8');

module.exports = yeoman.Base.extend({
  constructor: function(){
    yeoman.Base.apply(this, arguments);
    this.props = {};
    this.argument('appName', { type: String, required: false, desc: 'Project Name', defaults: null});
    this.props.appName = this.appName;
    this.log(chalk.blue(asciiArt));
  },
  prompting: function () {
    var done = this.async();
    var that = this;
    function askInitQuestions(){
      var questions = _.map(questionsCollection.initQuestions, function(question){
        var defaultValue = question.default;
        if(_.isString(defaultValue) && defaultValue.indexOf('appName') != -1){
          defaultValue = question.default.replace('appName', that.props.appName);
        }
        return _.extend(question, { default:defaultValue });
      });
      that.prompt(questions).then(function(answers){
        that.props = _.extend(that.props, answers);
        done();
      });
    }
    if(this.props.appName){
      askInitQuestions();
    }else{
      this.prompt(questionsCollection.appNameQuestion).then(function(answers){
        that.props.appName = answers.appName;
        askInitQuestions();
      });
    }
  },

  writing: function () {
    var templateFiles = ['*/app/views/index.scala.html', '*/build.sbt', '*/project/Config.scala', '*/conf/application.conf'];
    var globPattern = "+(" + templateFiles.join('|') + ")";
    var db = this.props.DatabaseType;
    var dbName = this.props.DatabaseName;
    this.fs.copy(this.sourceRoot(), this.destinationRoot(), { ignore:globPattern });
    //copy build.sbt
    var appName = this.props.appName;
    this.fs.copyTpl(this.templatePath('build.sbt'), this.destinationPath('build.sbt'), { appName: appName });
    //copy package.json and bower.json
    this.fs.copyTpl(this.templatePath('package.json'), this.destinationPath('package.json'), { appName: appName });
    this.fs.copyTpl(this.templatePath('bower.json'), this.destinationPath('bower.json'), { appName: appName });
    //copy index.html
    this.fs.copyTpl(this.templatePath('app/views/index.scala.html'), this.destinationPath('app/views/index.scala.html'), { appName: appName });
    //copy Config.scala
    var organization = this.props.OrganizationName;
    var SBTDBDriverDependency = util.getSBTDBDriverDependency(db);
    this.fs.copyTpl(this.templatePath('project/Config.scala'), this.destinationPath('project/Config.scala'), { organization: organization, SBTDBDriverDependency: SBTDBDriverDependency });
    //copy app.conf
    var slickDBDriver = util.getSlickDBDriver(db);
    var DBDriver = util.getDBDriver(db);
    var DBConnectionUrl = util.generateDBConnectionString(db, dbName);
    this.fs.copyTpl(this.templatePath('conf/application.conf'), this.destinationPath('conf/application.conf'), { slickDBDriver: slickDBDriver, DBDriver: DBDriver, DBConnectionUrl: DBConnectionUrl });
  },

  install: function () {
  },

  end: function(){
    this.log("it was good seeing you, have a nice day!");
  }
});
<commit_msg>copying ignored files<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var questionsCollection = require('./questions');
var util = require('./util');
var _ = require('lodash');
var asciiArt = fs.readFileSync(path.join(__dirname, 'asciiArt.txt'),'utf8');

module.exports = yeoman.Base.extend({
  constructor: function(){
    yeoman.Base.apply(this, arguments);
    this.props = {};
    this.argument('appName', { type: String, required: false, desc: 'Project Name', defaults: null});
    this.props.appName = this.appName;
    this.log(chalk.blue(asciiArt));
  },
  prompting: function () {
    var done = this.async();
    var that = this;
    function askInitQuestions(){
      var questions = _.map(questionsCollection.initQuestions, function(question){
        var defaultValue = question.default;
        if(_.isString(defaultValue) && defaultValue.indexOf('appName') != -1){
          defaultValue = question.default.replace('appName', that.props.appName);
        }
        return _.extend(question, { default:defaultValue });
      });
      that.prompt(questions).then(function(answers){
        that.props = _.extend(that.props, answers);
        done();
      });
    }
    if(this.props.appName){
      askInitQuestions();
    }else{
      this.prompt(questionsCollection.appNameQuestion).then(function(answers){
        that.props.appName = answers.appName;
        askInitQuestions();
      });
    }
  },

  writing: function () {
    var templateFiles = ['*/app/views/index.scala.html', '*/build.sbt', '*/project/Config.scala', '*/conf/application.conf'];
    var globPattern = "+(" + templateFiles.join('|') + ")";
    var db = this.props.DatabaseType;
    var dbName = this.props.DatabaseName;
    this.fs.copy(this.sourceRoot(), this.destinationRoot(), { ignore:globPattern });
    this.fs.copy(this.templatePath('.*'), this.destinationRoot());
    //copy build.sbt
    var appName = this.props.appName;
    this.fs.copyTpl(this.templatePath('build.sbt'), this.destinationPath('build.sbt'), { appName: appName });
    //copy package.json and bower.json
    this.fs.copyTpl(this.templatePath('package.json'), this.destinationPath('package.json'), { appName: appName });
    this.fs.copyTpl(this.templatePath('bower.json'), this.destinationPath('bower.json'), { appName: appName });
    //copy index.html
    this.fs.copyTpl(this.templatePath('app/views/index.scala.html'), this.destinationPath('app/views/index.scala.html'), { appName: appName });
    //copy Config.scala
    var organization = this.props.OrganizationName;
    var SBTDBDriverDependency = util.getSBTDBDriverDependency(db);
    this.fs.copyTpl(this.templatePath('project/Config.scala'), this.destinationPath('project/Config.scala'), { organization: organization, SBTDBDriverDependency: SBTDBDriverDependency });
    //copy app.conf
    var slickDBDriver = util.getSlickDBDriver(db);
    var DBDriver = util.getDBDriver(db);
    var DBConnectionUrl = util.generateDBConnectionString(db, dbName);
    this.fs.copyTpl(this.templatePath('conf/application.conf'), this.destinationPath('conf/application.conf'), { slickDBDriver: slickDBDriver, DBDriver: DBDriver, DBConnectionUrl: DBConnectionUrl });
  },

  install: function () {
  },

  end: function(){
    this.log("it was good seeing you, have a nice day!");
  }
});
<|endoftext|>


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

// generate itch package for various platforms

const ospath = require("path");
const $ = require("./common");
const bluebird = require("bluebird");

async function ciPackage(args) {
  if (args.length !== 2) {
    const got = args.join(" ::: ");
    const msg = `ci-package expects two arguments, got ${got}`;
    throw new Error(msg);
  }
  const [os, arch] = args;

  if (!$.OSES[os]) {
    const msg = `invalid os ${os}, must be in ${Object.keys($.OSES).join(
      " ::: "
    )}`;
    throw new Error(msg);
  }

  const archInfo = $.ARCHES[arch];
  if (!archInfo) {
    const msg = `invalid arch ${arch}, must be in ${Object.keys($.ARCHES).join(
      " ::: "
    )}`;
    throw new Error(msg);
  }

  $.say(`Packaging ${$.appName()} for ${os}-${arch}`);

  $.say("Installing dependencies...");
  $(await $.npm(`install`));

  $.say("Decompressing dist...");
  $(await $.sh("rm -rf dist"));
  $(await $.sh("tar xf dist.tar"));

  $.say("Installing production modules...");
  await $.showVersions(["npm", "node"]);
  await $.cd("dist", async () => {
    $(await $.npm("install --production"));
  });

  const electronVersion = JSON.parse(
    await $.readFile("package.json")
  ).devDependencies.electron.replace(/^\^/, "");
  $.say(`Using electron ${electronVersion}`);

  const appName = $.appName();
  const appVersion = $.buildVersion();
  const outDir = ospath.join("build", "v" + appVersion);
  const companyName = "itch corp.";

  var iconsPath = ospath.join("release", "images", appName + "-icons");
  var icoPath = ospath.join(iconsPath, "itch.ico");
  var icnsPath = ospath.join(iconsPath, "itch.icns");
  var installerGifPath = "release/images/installer.gif";

  const electronSharedOptions = {
    dir: "dist",
    name: appName,
    electronVersion,
    appVersion,
    asar: true,
    prune: false, // we do it ourselves
    overwrite: true,
    out: outDir,
  };

  const electronWindowsOptions = Object.assign({}, electronSharedOptions, {
    platform: "win32",
    icon: icoPath,
    win32metadata: {
      CompanyName: companyName,
      LegalCopyright: "MIT license, (c) itch corp.",
      FileDescription: "the itch.io desktop app",
      OriginalFileName: appName + ".exe",
      FileVersion: appVersion,
      AppVersion: appVersion,
      ProductName: appName,
      InternalName: appName + ".exe",
    },
  });

  const electronOptions = {
    "windows-ia32": Object.assign({ arch: "ia32" }, electronWindowsOptions),
    "windows-x64": Object.assign({ arch: "x64" }, electronWindowsOptions),
    "darwin-x64": Object.assign({}, electronSharedOptions, {
      platform: "darwin",
      arch: "x64",
      icon: icnsPath,
      appBundleId: "io." + appName + ".mac",
      appCategoryType: "public.app-category.games",
      protocols: [
        {
          name: appName + ".io",
          schemes: [appName + "io"]
        },
        {
          name: appName,
          schemes: [appName]
        }
      ],
    }),
    "linux-ia32": Object.assign({}, electronSharedOptions, {
      platform: "linux",
      arch: "ia32",
    }),
    "linux-x64": Object.assign({}, electronSharedOptions, {
      platform: "linux",
      arch: "x64",
    }),
  };

  $(await $.sh("mkdir -p packages"));

  $.say("Installing electron packaging tools...");
  packages = [
    "electron-packager@9.0.0"
  ];
  $(await $.npm(`install --no-save ${packages.join(" ")}`));

  const darwin = require("./package/darwin");
  const windows = require("./package/windows");

  const electronPackager = bluebird.promisify(require("electron-packager"));
  const electronRebuild = require("electron-rebuild-ftl").default;

  $.say("Packaging with binary release...");
  let wd = process.cwd();
  const toUnixPath = s => {
    if (process.platform === "win32") {
      return s.replace(/\\/g, "/");
    } else {
      return s;
    }
  };

  const electronConfigKey = `${os}-${archInfo.electronArch}`;
  const electronFinalOptions = Object.assign(
    {},
    electronOptions[electronConfigKey],
    {
      afterCopy: [
        async (buildPath, electronVersion, platform, arch, callback) => {
          $.say("Rebuilding native dependencies...");
          try {
            await electronRebuild(buildPath, electronVersion, arch, [], true);
          } catch (err) {
            $.say(`While building native deps:\n${err.stack}`);
            callback(err);
          }

          $.say("Cleaning modules...");
          try {
            await $.cd(buildPath, async function() {
              await $.sh(
                `${toUnixPath(ospath.join(wd, "release", "modclean.js"))} .`
              );
            })
          } catch (err) {
            $.say(`While cleaning:\n${err.stack}`);
            callback(err);
          }

          callback();
        },
      ],
    }
  );
  $.say(`electron-packager options: ${JSON.stringify(electronFinalOptions, null, 2)}`);
  const appPaths = await $.measure("electron package + rebuild", async () => {
    return await electronPackager(electronFinalOptions);
  });
  let buildPath = appPaths[0].replace(/\\/g, "/");

  $.say(`Built app is in ${buildPath}`);

  if (!process.env.CI) {
    $.say(`Not on CI, stopping there`);
    return;
  }

  switch (os) {
    case "windows":
      await windows.sign(arch, buildPath);
      break;
    case "darwin":
      await darwin.sign(arch, buildPath);
      break;
    case "linux":
      // tl;dr code-signing on Linux isn't a thing
      break;
  }

  $(await $.sh(`mkdir -p packages/${os}-${arch}`));
  if (os === "darwin") {
    $(await $.sh(`ditto ${buildPath} packages/${os}-${arch}/`));
  } else {
    $(await $.sh(`mv ${buildPath} packages/${os}-${arch}/`));
  }
}

ciPackage(process.argv.slice(2));
<commit_msg>Don't nest packaged app in another folder<commit_after>#!/usr/bin/env node

// generate itch package for various platforms

const ospath = require("path");
const $ = require("./common");
const bluebird = require("bluebird");

async function ciPackage(args) {
  if (args.length !== 2) {
    const got = args.join(" ::: ");
    const msg = `ci-package expects two arguments, got ${got}`;
    throw new Error(msg);
  }
  const [os, arch] = args;

  if (!$.OSES[os]) {
    const msg = `invalid os ${os}, must be in ${Object.keys($.OSES).join(
      " ::: "
    )}`;
    throw new Error(msg);
  }

  const archInfo = $.ARCHES[arch];
  if (!archInfo) {
    const msg = `invalid arch ${arch}, must be in ${Object.keys($.ARCHES).join(
      " ::: "
    )}`;
    throw new Error(msg);
  }

  $.say(`Packaging ${$.appName()} for ${os}-${arch}`);

  $.say("Installing dependencies...");
  $(await $.npm(`install`));

  $.say("Decompressing dist...");
  $(await $.sh("rm -rf dist"));
  $(await $.sh("tar xf dist.tar"));

  $.say("Installing production modules...");
  await $.showVersions(["npm", "node"]);
  await $.cd("dist", async () => {
    $(await $.npm("install --production"));
  });

  const electronVersion = JSON.parse(
    await $.readFile("package.json")
  ).devDependencies.electron.replace(/^\^/, "");
  $.say(`Using electron ${electronVersion}`);

  const appName = $.appName();
  const appVersion = $.buildVersion();
  const outDir = ospath.join("build", "v" + appVersion);
  const companyName = "itch corp.";

  var iconsPath = ospath.join("release", "images", appName + "-icons");
  var icoPath = ospath.join(iconsPath, "itch.ico");
  var icnsPath = ospath.join(iconsPath, "itch.icns");
  var installerGifPath = "release/images/installer.gif";

  const electronSharedOptions = {
    dir: "dist",
    name: appName,
    electronVersion,
    appVersion,
    asar: true,
    prune: false, // we do it ourselves
    overwrite: true,
    out: outDir,
  };

  const electronWindowsOptions = Object.assign({}, electronSharedOptions, {
    platform: "win32",
    icon: icoPath,
    win32metadata: {
      CompanyName: companyName,
      LegalCopyright: "MIT license, (c) itch corp.",
      FileDescription: "the itch.io desktop app",
      OriginalFileName: appName + ".exe",
      FileVersion: appVersion,
      AppVersion: appVersion,
      ProductName: appName,
      InternalName: appName + ".exe",
    },
  });

  const electronOptions = {
    "windows-ia32": Object.assign({ arch: "ia32" }, electronWindowsOptions),
    "windows-x64": Object.assign({ arch: "x64" }, electronWindowsOptions),
    "darwin-x64": Object.assign({}, electronSharedOptions, {
      platform: "darwin",
      arch: "x64",
      icon: icnsPath,
      appBundleId: "io." + appName + ".mac",
      appCategoryType: "public.app-category.games",
      protocols: [
        {
          name: appName + ".io",
          schemes: [appName + "io"]
        },
        {
          name: appName,
          schemes: [appName]
        }
      ],
    }),
    "linux-ia32": Object.assign({}, electronSharedOptions, {
      platform: "linux",
      arch: "ia32",
    }),
    "linux-x64": Object.assign({}, electronSharedOptions, {
      platform: "linux",
      arch: "x64",
    }),
  };

  $(await $.sh("mkdir -p packages"));

  $.say("Installing electron packaging tools...");
  packages = [
    "electron-packager@9.0.0"
  ];
  $(await $.npm(`install --no-save ${packages.join(" ")}`));

  const darwin = require("./package/darwin");
  const windows = require("./package/windows");

  const electronPackager = bluebird.promisify(require("electron-packager"));
  const electronRebuild = require("electron-rebuild-ftl").default;

  $.say("Packaging with binary release...");
  let wd = process.cwd();
  const toUnixPath = s => {
    if (process.platform === "win32") {
      return s.replace(/\\/g, "/");
    } else {
      return s;
    }
  };

  const electronConfigKey = `${os}-${archInfo.electronArch}`;
  const electronFinalOptions = Object.assign(
    {},
    electronOptions[electronConfigKey],
    {
      afterCopy: [
        async (buildPath, electronVersion, platform, arch, callback) => {
          $.say("Rebuilding native dependencies...");
          try {
            await electronRebuild(buildPath, electronVersion, arch, [], true);
          } catch (err) {
            $.say(`While building native deps:\n${err.stack}`);
            callback(err);
          }

          $.say("Cleaning modules...");
          try {
            await $.cd(buildPath, async function() {
              await $.sh(
                `${toUnixPath(ospath.join(wd, "release", "modclean.js"))} .`
              );
            })
          } catch (err) {
            $.say(`While cleaning:\n${err.stack}`);
            callback(err);
          }

          callback();
        },
      ],
    }
  );
  $.say(`electron-packager options: ${JSON.stringify(electronFinalOptions, null, 2)}`);
  const appPaths = await $.measure("electron package + rebuild", async () => {
    return await electronPackager(electronFinalOptions);
  });
  let buildPath = appPaths[0].replace(/\\/g, "/");

  $.say(`Built app is in ${buildPath}`);

  if (!process.env.CI) {
    $.say(`Not on CI, stopping there`);
    return;
  }

  switch (os) {
    case "windows":
      await windows.sign(arch, buildPath);
      break;
    case "darwin":
      await darwin.sign(arch, buildPath);
      break;
    case "linux":
      // tl;dr code-signing on Linux isn't a thing
      break;
  }

  $(await $.sh(`mkdir -p packages`));
  if (os === "darwin") {
    $(await $.sh(`ditto ${buildPath} packages/${os}-${arch}`));
  } else {
    $(await $.sh(`mv ${buildPath} packages/${os}-${arch}`));
  }
}

ciPackage(process.argv.slice(2));
<|endoftext|>


<commit_before>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc'),
        );

        // Config.js
        this.fs.copyTpl(
            this.templatePath('config.js'),
            this.destinationPath('config.js'),
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/index.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'default.twig',
            dest + 'default.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }
        if (this.appStore) {
            apps.push('store');
        }
        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build', 'theme-config']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<commit_msg>Fixed issue where the wrong css file was referenced<commit_after>'use strict';
const Generator = require('yeoman-generator');
const chalk = require('chalk');
const commandExists = require('command-exists').sync;
const cowsay = require('cowsay');
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const stripIndent = require('strip-indent');
const yosay = require('yosay');

module.exports = class extends Generator {
    /**
     * Constructor
     * @param {String|Array} args
     * @param {Object} opts
     */
    constructor(args, opts) {
        // Noinspection JSAnnotator
        super(args, opts);

        // Check for newer versions of this generator and notify
        updateNotifier({pkg}).notify();

        this.argument('name', {
            type: String,
            required: false,
            description: 'The name of the project. If not set then you will be prompted.'
        });
    }

    /**
     * Sets the app name
     * @param {string} name
     * @private
     */
    _setAppName(name) {
        this.appName = name.replace(/\s+/g, '-').toLowerCase();
    }

    /**
     * Initialization
     */
    initializing() {
        // Initialize configuration
        this.appName = 'Website';

        // If the app name was passed as an argument then set it here
        if (typeof this.options.name !== 'undefined') {
            this._setAppName(this.options.name);
        }
    }

    /**
     * Questions
     * @returns {Promise.<TResult>|Promise}
     */
    prompting() {
        // Have Yeoman greet the user.
        this.log(yosay('Starting the ' + chalk.red('Cacao BranchCMS') + ' website generator!'));

        var prompts = [];

        // Ask for the website project name if it's not already set
        if (typeof this.options.name === 'undefined') {
            prompts.push({
                type: 'input',
                name: 'name',
                message: 'What is the name of the website project?'
            });
        }

        // Is this a theme website for BranchCMS?
        prompts.push({
            type: 'list',
            name: 'istheme',
            message: 'Is this a new theme website?',
            choices: ['Yes', 'No'],
            default: 'No'
        });

        // Front-end libraries to include
        prompts.push({
            type: 'checkbox',
            name: 'libraries',
            message: 'Check which libraries to include',
            choices: [
                {name: 'Magnific Popup', value: 'magnific', checked: true},
                {name: 'Slick slider', value: 'slick', checked: true},
                {name: 'Drift image zoom', value: 'driftzoom'}
            ]
        });

        // BranchCMS App templates to include
        prompts.push({
            type: 'checkbox',
            name: 'apps',
            message: 'Check which BranchCMS apps you will use for this website',
            choices: [
                {name: 'Blog', value: 'blog'},
                {name: 'Store', value: 'store'}
            ]
        });

        return this.prompt(prompts).then(answers => {
            // Set the app name if it was asked
            if (typeof answers.name !== 'undefined') {
                this._setAppName(answers.name);
            }

            // Tests to see if a value was selected in an answer
            const hasAnswer = (val, test) => val && val.indexOf(test) !== -1;

            this.isThemeWebsite = answers.istheme.toLowerCase() === 'yes';

            this.includeMagnific = hasAnswer(answers.libraries, 'magnific');
            this.includeSlick = hasAnswer(answers.libraries, 'slick');
            this.includeDrift = hasAnswer(answers.libraries, 'driftzoom');

            this.appBlog = hasAnswer(answers.apps, 'blog');
            this.appStore = hasAnswer(answers.apps, 'store');
        });
    }

    /**
     * Create the source files
     */
    writing() {
        this.log('\n' + chalk.bold('Writing files') + '\n');

        this._setupConfigFiles();
        this._copySourceFiles();
        this._copyTemplateFiles();
    }

    /**
     * Sets up the package.json and other config files
     * @private
     */
    _setupConfigFiles() {
        // Editor Config
        this.fs.copy(
            this.templatePath('_editorconfig'),
            this.destinationPath('.editorconfig')
        );

        // Gitignore
        this.fs.copy(
            this.templatePath('_gitignore'),
            this.destinationPath('.gitignore')
        );

        // Package.json
        this.fs.copyTpl(
            this.templatePath('_package.json'),
            this.destinationPath('package.json'),
            {
                name: this.appName,
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick
            }
        );

        // Stylelint
        this.fs.copy(
            this.templatePath('_stylelintrc'),
            this.destinationPath('.stylelintrc'),
        );

        // Config.js
        this.fs.copyTpl(
            this.templatePath('config.js'),
            this.destinationPath('config.js'),
            {
                includeDriftZoom: this.includeDrift,
                includeMagnific: this.includeMagnific,
                includeSlick: this.includeSlick,
                isThemeWebsite: this.isThemeWebsite
            }
        );

        // Gulpfile.js
        this.fs.copyTpl(
            this.templatePath('gulpfile.js'),
            this.destinationPath('gulpfile.js'),
            {
                isThemeWebsite: this.isThemeWebsite
            }
        );
    }

    /**
     * Copies the boilerplate images, CSS and Javascript files
     */
    _copySourceFiles() {
        this.fs.copy(
            this.templatePath() + '/src/**/*',
            this.destinationPath() + '/src'
        );

        if (this.isThemeWebsite) {
            // Include the theme files in the main css file
            let themeInclude = `
                    /**
                     * Theme configuration
                     */

                    @import './theme';`;
            this.fs.append(this.destinationPath() + '/src/css/main.css', stripIndent(themeInclude));

            // Include the theme config files
            this.fs.copy(
                this.templatePath() + '/theme-starter/css/**/*',
                this.destinationPath() + '/src/css'
            );
        }
    }

    /**
     * Copy the BranchCMS template files
     * @private
     */
    _copyTemplateFiles() {
        const src = this.templatePath() + '/theme/';
        const dest = this.destinationPath() + '/src/theme/';

        // Copy the theme.json file
        this.fs.copy(
            src + 'theme.json',
            this.destinationPath() + '/src/theme.json'
        );

        // Copy the default site template
        this.fs.copy(
            src + 'default.twig',
            dest + 'default.twig'
        );

        // Copy the app templates
        let apps = [
            'content-builder',
            'forms',
            'navigation',
            'search',
            'snippets'
        ];
        if (this.appBlog) {
            apps.push('blog');
        }
        if (this.appStore) {
            apps.push('store');
        }
        for (let app of apps) {
            this.fs.copy(
                src + app + '/**/*',
                dest + app
            );
        }
    }

    /**
     * Installation via yarn or npm
     */
    install() {
        this.log('\n');
        if (commandExists('yarn')) {
            this.yarnInstall();
        } else {
            this.npmInstall();
        }
    }

    /**
     * Finish
     */
    end() {
        this._build();
    }

    /**
     * Runs the gulp build
     * @private
     */
    _build() {
        this.log('\n\n' + chalk.bold('Running ' + chalk.yellow('gulp `build`') + ' task'));
        this.spawnCommand('gulp', ['build', 'theme-config']).on('close', () => {
            this._done();
        });
    }

    /**
     * Output the closing message
     * @private
     */
    _done() {
        const cows = [
            'default',
            'cheese',
            'dragon-and-cow',
            'dragon',
            'elephant',
            'eyes',
            'ghostbusters',
            'goat',
            'hedgehog',
            'kitty',
            'koala',
            'luke-koala',
            'mech-and-cow',
            'meow',
            'milk',
            'moofasa',
            'moose',
            'sheep',
            'small',
            'squirrel',
            'stegosaurus',
            'turtle',
            'tux',
            'vader-koala',
            'vader',
            'whale',
            'www'
        ];
        const cow = cows[Math.floor(Math.random() * cows.length)];
        this.log(cowsay.say({
            text: '\nAll Done! Now go and build something great!\n',
            f: cow
        }) + '\n');
    }
};
<|endoftext|>


<commit_before>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the prime ' + chalk.bold.red('Dnn ') + chalk.bold.blue('theme') + ' generator!'
    ));

    var prompts = [{
      type: 'input',
      name: 'themeName',
      message: 'Tell me how your theme should be named',
      validate: function (string) {
        return string.replace(/\s+/, '').length > 0;
      }
    }];

    this.prompt(prompts, function (props) {
      this.props = props;
      this.props.themeName = _s.camelize(props.themeName);
      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      var config = {
        themeName: this.props.themeName
      };
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        config
      );
      this.fs.copyTpl(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json'),
        config
      );
      this.fs.copy(
        this.templatePath('_skin.ascx'),
        this.destinationPath(_s.dasherize(this.props.themeName) +'.ascx')
      );
      this.fs.copy(
        this.templatePath('images'),
        this.destinationPath('images')
      );
      this.fs.copy(
        this.templatePath('js'),
        this.destinationPath('js')
      );
      this.fs.copy(
        this.templatePath('nav-primary'),
        this.destinationPath('nav-primary')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.installDependencies();
  }
});
<commit_msg>fixed<commit_after>'use strict';
var yeoman = require('yeoman-generator');
var chalk = require('chalk');
var yosay = require('yosay');
var _s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({
  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the prime ' + chalk.bold.red('Dnn ') + chalk.bold.blue('theme') + ' generator!'
    ));

    var prompts = [{
      type: 'input',
      name: 'themeName',
      message: 'Tell me how your theme should be named',
      validate: function (string) {
        return string.replace(/\s+/, '').length > 0;
      }
    }];

    this.prompt(prompts, function (props) {
      this.props = props;
      this.props.themeName = _s.camelize(props.themeName);
      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      var config = {
        themeName: this.props.themeName
      };
      this.fs.copyTpl(
        this.templatePath('_package.json'),
        this.destinationPath('package.json'),
        config
      );
      this.fs.copyTpl(
        this.templatePath('_bower.json'),
        this.destinationPath('bower.json'),
        config
      );
      this.fs.copy(
        this.templatePath('_skin.ascx'),
        this.destinationPath(_s.dasherize(this.props.themeName) +'.ascx')
      );
      this.fs.copy(
        this.templatePath('js'),
        this.destinationPath('js')
      );
      this.fs.copy(
        this.templatePath('nav-primary'),
        this.destinationPath('nav-primary')
      );
    },

    projectfiles: function () {
      this.fs.copy(
        this.templatePath('editorconfig'),
        this.destinationPath('.editorconfig')
      );
      this.fs.copy(
        this.templatePath('jshintrc'),
        this.destinationPath('.jshintrc')
      );
    }
  },

  install: function () {
    this.installDependencies();
  }
});
<|endoftext|>