<commit_before>"use strict";

var chalk = require('chalk');
var inquirer = require('inquirer');
var fs = require('fs-extra');
var path = require('path');
var extend = require('extend');
var log = require('loglevel');

var fileTemplater = require('../fileTemplater')();
var promptOptions = require('../promptOptions')();
var pkg = require(path.resolve(__dirname, '..', '..' ,'package.json'));

var _currentWorkingDir = process.cwd();
var _promptAnswers;
var _options;

module.exports = function(appDir) {

    return {
        init: init
    };

    function init(options) {
        _options = options;
        setUpLogLevel();
        checkIfWorkingDirIsEmpty();
    }

    function setUpLogLevel() {
        if(_options.silent) {
            log.setLevel(log.levels.SILENT);
        } else {
            log.setLevel(log.levels.WARN);
        }
    }

    function checkIfWorkingDirIsEmpty() {
        fs.readdir(_currentWorkingDir, function(err, files) {
            if (err) return console.error(err);

            if(files.length > 1) {
                log.warn('');
                log.warn(chalk.underline('Warning: The directory you are currently in is not empty!'));
                log.warn(chalk.underline('Going through the setup will perform a clean slate installation.'));
                log.warn(chalk.underline('This will overwrite any user changes'));
                log.warn('');

                inquirer.prompt(promptOptions.newOptions, inquirerCallback);
            } else {
                log.warn('');
                log.warn(chalk.bold('Running through setup for a new project.'));
                log.warn(chalk.underline('This can be exited out by pressing [Ctrl+C]'));
                log.warn('');

                inquirer.prompt(promptOptions.newOptions, inquirerCallback);
            }
        })
    }

    function getTemplateData() {
        var date = new Date();

        return {
            projectNameFileName: _promptAnswers.projectName.toLowerCase().replace(/ /g,"-"),
            projectGeneratedDate: [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/'),
            slateCurrentVersion: pkg.version
        }
    }

    function inquirerCallback(answers) {
        _promptAnswers = answers;

        if(_promptAnswers.isOkToCopyFiles) {
            var filesDirsToExclude = getExcludeList();

            log.warn('');
            log.warn('> Copying over files...');

            fs.copy(appDir, process.cwd(), {
                filter: function(path) {
                    var needToCopyFile = true;

                    for (var i = 0; i < filesDirsToExclude.length; i++) {
                        //needToCopyFile is still true
                        //Hasn't been flipped during loop
                        if(needToCopyFile) {
                            needToCopyFile = path.indexOf(filesDirsToExclude[i]) === -1;
                        }
                    };

                    return needToCopyFile;
                }
            }, function (err) {
                if (err) return console.error(err);

                templateCopiedFiles();
            })

        } else {
            log.warn('User cancelled - no files copied')
        }
    }

    function getExcludeList() {
        //Default exclude folders / files
        var excludeList = [
            'node_modules'
        ];

        if(_promptAnswers.projectType === "Dot NET") {
            excludeList.push('views');
            excludeList.push('release.js');
        }

        return excludeList;
    }

    function templateCopiedFiles() {
        log.warn('> Templating files...');

        var templateData = extend({}, _promptAnswers, getTemplateData())

        fileTemplater.setTemplateData(templateData);
        fileTemplater.setBasePath(process.cwd());
        fileTemplater.setFileList([
            path.join('_config', 'creds.json'),
            'package.json',
            '.slaterc'
        ]);

        fileTemplater.run(templateFinished);
    }

    function templateFinished() {
        log.warn('> Installation complete!');

        log.warn('');
        log.warn('Slate project "' + chalk.underline(_promptAnswers.projectName) +'" has been installed!');
        log.warn('');
        log.warn(chalk.underline('Next steps:'));
        log.warn('  Run `npm install` to setup all dependencies');
        log.warn('  Run `gulp` for initial setup, `gulp watch` to setup watching of files');
        log.warn('');
    }
}<commit_msg>feat: Change a few logs to be info<commit_after>"use strict";

var chalk = require('chalk');
var inquirer = require('inquirer');
var fs = require('fs-extra');
var path = require('path');
var extend = require('extend');
var log = require('loglevel');

var fileTemplater = require('../fileTemplater')();
var promptOptions = require('../promptOptions')();
var pkg = require(path.resolve(__dirname, '..', '..' ,'package.json'));

var _currentWorkingDir = process.cwd();
var _promptAnswers;
var _options;

module.exports = function(appDir) {

    return {
        init: init
    };

    function init(options) {
        _options = options;
        setUpLogLevel();
        checkIfWorkingDirIsEmpty();
    }

    function setUpLogLevel() {
        if(_options.silent) {
            log.setLevel(log.levels.SILENT);
        } else {
            log.setLevel(log.levels.WARN);
        }
    }

    function checkIfWorkingDirIsEmpty() {
        fs.readdir(_currentWorkingDir, function(err, files) {
            if (err) return console.error(err);

            if(files.length > 1) {
                log.warn('');
                log.warn(chalk.underline('Warning: The directory you are currently in is not empty!'));
                log.warn(chalk.underline('Going through the setup will perform a clean slate installation.'));
                log.warn(chalk.underline('This will overwrite any user changes'));
                log.warn('');

                inquirer.prompt(promptOptions.newOptions, inquirerCallback);
            } else {
                log.warn('');
                log.warn(chalk.bold('Running through setup for a new project.'));
                log.warn(chalk.underline('This can be exited out by pressing [Ctrl+C]'));
                log.warn('');

                inquirer.prompt(promptOptions.newOptions, inquirerCallback);
            }
        })
    }

    function getTemplateData() {
        var date = new Date();

        return {
            projectNameFileName: _promptAnswers.projectName.toLowerCase().replace(/ /g,"-"),
            projectGeneratedDate: [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/'),
            slateCurrentVersion: pkg.version
        }
    }

    function inquirerCallback(answers) {
        _promptAnswers = answers;

        if(_promptAnswers.isOkToCopyFiles) {
            var filesDirsToExclude = getExcludeList();

            log.info('');
            log.info('> Copying over files...');

            fs.copy(appDir, process.cwd(), {
                filter: function(path) {
                    var needToCopyFile = true;

                    for (var i = 0; i < filesDirsToExclude.length; i++) {
                        //needToCopyFile is still true
                        //Hasn't been flipped during loop
                        if(needToCopyFile) {
                            needToCopyFile = path.indexOf(filesDirsToExclude[i]) === -1;
                        }
                    };

                    return needToCopyFile;
                }
            }, function (err) {
                if (err) return console.error(err);

                templateCopiedFiles();
            })

        } else {
            log.info('User cancelled - no files copied')
        }
    }

    function getExcludeList() {
        //Default exclude folders / files
        var excludeList = [
            'node_modules'
        ];

        if(_promptAnswers.projectType === "Dot NET") {
            excludeList.push('views');
            excludeList.push('release.js');
        }

        return excludeList;
    }

    function templateCopiedFiles() {
        log.info('> Templating files...');

        var templateData = extend({}, _promptAnswers, getTemplateData())

        fileTemplater.setTemplateData(templateData);
        fileTemplater.setBasePath(process.cwd());
        fileTemplater.setFileList([
            path.join('_config', 'creds.json'),
            'package.json',
            '.slaterc'
        ]);

        fileTemplater.run(templateFinished);
    }

    function templateFinished() {
        log.info('> Installation complete!');

        log.info('');
        log.info('Slate project "' + chalk.underline(_promptAnswers.projectName) +'" has been installed!');
        log.info('');
        log.info(chalk.underline('Next steps:'));
        log.info('  Run `npm install` to setup all dependencies');
        log.info('  Run `gulp` for initial setup, `gulp watch` to setup watching of files');
        log.info('');
    }
}<|endoftext|>


<commit_before>"use strict";

var should = require("should");
var assertions = require('./custom-assertions');
var mockery = require("mockery");
var path = require("path");
var git = require("gulp-git");
var fs = require("fs");
var mockery = require("mockery");
var gulp = require("gulp");
var extend = require("util")._extend;

var gitOptions = {
  quiet: true
};

var mockOptions = {
  warnOnUnregistered: false,
  warnOnReplace: false,
  useCleanCache: true
};

describe("util.js", function () {
  beforeEach(function(){
    mockery.enable(mockOptions);

    // Default aswers yes for every question
    mockery.registerMock("readline", {
      createInterface: function (obj){
        return {
          question: function(text, callback) {
            return callback("yes");
          }
        };
      }
    });
  });

  afterEach(function(){
    mockery.disable();
  });

  it("should have a default conf", function () {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    should(util.conf.token).equal(null);
    should(util.conf.preset).equal("angular");
    should(util.conf.testTask).equal(null);
    should(util.conf.appDir).equal(process.cwd());
    should(util.conf.versionFiles.length).greaterThan(0);
  });

  it("should createTmpBranch", function (done) {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    util.createTmpBranch(function (err, name) {
      if(err) {
        throw err;
      }

      should(name).match(/^tmp\-\d+$/);
      done();
    }, gitOptions);
  });

  it("should read packageVersion", function () {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    should(util.packageVersion('package.json')).match(/^(\d+\.)?\d+.\d+$/);
  });

  it("should commitChangesStream", function (done) {
    var util = require("../util.js");

    fs.writeFileSync('deleteme.md', 'please, deleteme');
    util.conf.appDir = 'deleteme.md';

    var stream = util.commitChangesStream(gitOptions);
    stream.on('end', function () {
      should(global.sandboxDir).containsGitLog(
        "[Prerelease] Bumped version number",
        done
      );
    });
  });

  describe("calculateVersion", function(){
    beforeEach(function(){
      mockery.disable(); // Gulp do not like mockery :(
      fs.writeFileSync('deleteme.md', 'please, deleteme');
    });

    it("should calculate minor", function(done){
      var util = require("../util.js");
      var stream = gulp.src('deleteme.md')
      .pipe(git.add(gitOptions))
      .pipe(git.commit("feat(docs): New deleteme file", gitOptions));

      stream.on('end', function(){
        util.calculateVersion(function(err, release){
          if (err) {
            throw err;
          }
          should(release).equal('minor');
          done();
        });
      });
    });

    it("should calculate major", function(done){
      var util = require("../util.js");
      var stream = gulp.src('deleteme.md')
      .pipe(git.add(gitOptions))
      .pipe(git.commit("feat(docs): New deleteme file\n\nBREAKING CHANGE: New file on repository must be detected by someone else",
                       gitOptions));

      stream.on('end', function(){
        util.calculateVersion(function(err, release){
          if (err) {
            throw err;
          }
          should(release).equal('major');
          done();
        });
      });
    });
  });

  describe("askContinue", function(){
    it("should continue without must and yes response", function(){
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, false)
        .should.not.throw();
    });
    it("should get an error with must and no response", function(){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, true)
        .should
        .throw("The last question must be answered with a yes YES for this task keeps going");
    });
    it("should continue without must and no response", function(){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, false)
        .should.not.throw();
    });
  });

  describe("askDeleteBranch", function(){
    it("should not delete a branch with no response", function(done){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util.askDeleteBranch("test", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
    it("should callback with false did when yes response", function(done){
      var util = require("../util.js");
      util.askDeleteBranch("test", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
  });

  describe("mergeInto", function(){
    beforeEach(function(done){
      mockery.disable(); // As always gulp pipes don't like mockery
      git.checkout("test", gitOptions, function () {
        fs.writeFileSync('deleteme.md', 'please, deleteme');
        var addCommit = gulp.src('deleteme.md')
        .pipe(git.add(gitOptions))
        .pipe(git.commit("Testing merge", gitOptions));

        addCommit.on('end', function(){
          git.checkout("master", gitOptions, function(){
            mockery.enable(mockOptions); // Re-enabling
            done();
          });
        });
      });
    });
    afterEach(function(done){
      git.checkout("master", gitOptions, done);
    });
    it("should not merge without -b", function () {
      mockery.registerMock('yargs', {
        argv: {}
      });
      var util = require("../util.js");
      util
        .mergeInto
        .bind(null, "test", function(){})
        .should
        .throw("You must set a branch with -b argument");
    });

    it("should merge test branch into master", function (done) {
      mockery.registerMock('yargs', {
        argv: {b: "test"}
      });
      var util = require("../util.js");
      util.mergeInto("test", function (err) {
        if (err) {
          throw err;
        }

        should(global.sandboxDir).containsGitLog(
          "Testing merge",
          done
        );
      }, gitOptions);
    });
  });

  describe("askPushTo", function(){
    it("should callback with false, with an inexistent remote", function(done){
      var util = require("../util.js");
      util.askPushTo("test", "origin", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
  });

});
<commit_msg>feat(tests): Add merge function test<commit_after>"use strict";

var should = require("should");
var assertions = require('./custom-assertions');
var mockery = require("mockery");
var path = require("path");
var git = require("gulp-git");
var fs = require("fs");
var mockery = require("mockery");
var gulp = require("gulp");
var extend = require("util")._extend;

var gitOptions = {
  quiet: true
};

var mockOptions = {
  warnOnUnregistered: false,
  warnOnReplace: false,
  useCleanCache: true
};

describe("util.js", function () {
  beforeEach(function(){
    mockery.enable(mockOptions);

    // Default aswers yes for every question
    mockery.registerMock("readline", {
      createInterface: function (obj){
        return {
          question: function(text, callback) {
            return callback("yes");
          }
        };
      }
    });
  });

  afterEach(function(){
    mockery.disable();
  });

  it("should have a default conf", function () {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    should(util.conf.token).equal(null);
    should(util.conf.preset).equal("angular");
    should(util.conf.testTask).equal(null);
    should(util.conf.appDir).equal(process.cwd());
    should(util.conf.versionFiles.length).greaterThan(0);
  });

  it("should createTmpBranch", function (done) {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    util.createTmpBranch(function (err, name) {
      if(err) {
        throw err;
      }

      should(name).match(/^tmp\-\d+$/);
      done();
    }, gitOptions);
  });

  it("should read packageVersion", function () {
    var util = require("../util.js");
    util.conf.appDir = global.sandboxDir;

    should(util.packageVersion('package.json')).match(/^(\d+\.)?\d+.\d+$/);
  });

  it("should commitChangesStream", function (done) {
    var util = require("../util.js");

    fs.writeFileSync('deleteme.md', 'please, deleteme');
    util.conf.appDir = 'deleteme.md';

    var stream = util.commitChangesStream(gitOptions);
    stream.on('end', function () {
      should(global.sandboxDir).containsGitLog(
        "[Prerelease] Bumped version number",
        done
      );
    });
  });

  it("should merge function merge objects", function(){
    var util = require("../util.js"),
        obj1 = {
          a: "aa",
          b: "bb",
          c: "cc",
          d: {
            aa: "aa",
            bb: "bb",
          }
        },
        obj2 = {
          c: "ccc",
          d: {
            aa: "aaa",
            cc: "cc"
          }
        },
        expected = JSON.stringify({
          a: "aa",
          b: "bb",
          c: "ccc",
          d: {
            aa: "aaa",
            bb: "bb",
            cc: "cc"
          }
        });
    JSON
      .stringify(util.merge(obj1, obj2))
      .should
      .be
      .equal(expected);
  });

  describe("calculateVersion", function(){
    beforeEach(function(){
      mockery.disable(); // Gulp do not like mockery :(
      fs.writeFileSync('deleteme.md', 'please, deleteme');
    });

    it("should calculate minor", function(done){
      var util = require("../util.js");
      var stream = gulp.src('deleteme.md')
      .pipe(git.add(gitOptions))
      .pipe(git.commit("feat(docs): New deleteme file", gitOptions));

      stream.on('end', function(){
        util.calculateVersion(function(err, release){
          if (err) {
            throw err;
          }
          should(release).equal('minor');
          done();
        });
      });
    });

    it("should calculate major", function(done){
      var util = require("../util.js");
      var stream = gulp.src('deleteme.md')
      .pipe(git.add(gitOptions))
      .pipe(git.commit("feat(docs): New deleteme file\n\nBREAKING CHANGE: New file on repository must be detected by someone else",
                       gitOptions));

      stream.on('end', function(){
        util.calculateVersion(function(err, release){
          if (err) {
            throw err;
          }
          should(release).equal('major');
          done();
        });
      });
    });
  });

  describe("askContinue", function(){
    it("should continue without must and yes response", function(){
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, false)
        .should.not.throw();
    });
    it("should get an error with must and no response", function(){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, true)
        .should
        .throw("The last question must be answered with a yes YES for this task keeps going");
    });
    it("should continue without must and no response", function(){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util
        .askContinue
        .bind(null, "Want to continue?", function(){}, false)
        .should.not.throw();
    });
  });

  describe("askDeleteBranch", function(){
    it("should not delete a branch with no response", function(done){
      mockery.registerMock("readline", {
        createInterface: function (obj){
          return {
            question: function(text, callback) {
              return callback("no");
            }
          };
        }
      });
      var util = require("../util.js");
      util.askDeleteBranch("test", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
    it("should callback with false did when yes response", function(done){
      var util = require("../util.js");
      util.askDeleteBranch("test", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
  });

  describe("mergeInto", function(){
    beforeEach(function(done){
      mockery.disable(); // As always gulp pipes don't like mockery
      git.checkout("test", gitOptions, function () {
        fs.writeFileSync('deleteme.md', 'please, deleteme');
        var addCommit = gulp.src('deleteme.md')
        .pipe(git.add(gitOptions))
        .pipe(git.commit("Testing merge", gitOptions));

        addCommit.on('end', function(){
          git.checkout("master", gitOptions, function(){
            mockery.enable(mockOptions); // Re-enabling
            done();
          });
        });
      });
    });
    afterEach(function(done){
      git.checkout("master", gitOptions, done);
    });
    it("should not merge without -b", function () {
      mockery.registerMock('yargs', {
        argv: {}
      });
      var util = require("../util.js");
      util
        .mergeInto
        .bind(null, "test", function(){})
        .should
        .throw("You must set a branch with -b argument");
    });

    it("should merge test branch into master", function (done) {
      mockery.registerMock('yargs', {
        argv: {b: "test"}
      });
      var util = require("../util.js");
      util.mergeInto("test", function (err) {
        if (err) {
          throw err;
        }

        should(global.sandboxDir).containsGitLog(
          "Testing merge",
          done
        );
      }, gitOptions);
    });
  });

  describe("askPushTo", function(){
    it("should callback with false, with an inexistent remote", function(done){
      var util = require("../util.js");
      util.askPushTo("test", "origin", function(did){
        did.should.be.false();
        done();
      }, gitOptions);
    });
  });

});
<|endoftext|>


<commit_before>var Form = function(router, templating, admin, translator)
{
  var self = this;

  var MessageType = {
    Info: 'info',
    Error: 'error',
    Success: 'success'
  };

  this.initDataPicker = function(form)
  {
    $(form).find('input.datetimepicker').datetimepicker({
      timeFormat: 'hh:mm',
      timeText: 'Zeit',
      hourText: 'Std.',
      minuteText: 'Min.',
      currentText: 'Jetzt',
      closeText: 'Fertig',
      dateFormat: 'dd.mm.yy',
      stepMinute: 5,
      firstDay: 1
    });

    $(form).find('input.datepicker').datepicker({
      closeText: 'Fertig',
      dateFormat: 'dd.mm.yy',
      firstDay: 1
    });
  };

  this.initRadioAndCheckbox = function (form) {
    $(form).find('input[type=radio],input[type=checkbox]').iCheck({
      checkboxClass: 'icheckbox-esperanto',
      radioClass: 'icheckbox-esperanto'
    });
  };

  this.initSelect = function (form) {
    $(form).find('select').select2();
  };

  this.destroyWysiwyg = function(content) {
    content.find('.wysiwyg').each(function() {
      tinymce.remove('#'.$(this).attr('id'));
    });
  };

  this.initWysiwyg = function(form)
  {
    var addTinymce = function(element) {

      var options = {
          // Location of TinyMCE script
          script_url : '/js/lib/tinymce/tinymce.min.js',
          //content_css: "/css/editor.css",
          menubar: false,
          // General options
          plugins: ["advlist autolink lists link image charmap print preview anchor",
              "searchreplace visualblocks code fullscreen",
              "insertdatetime media table contextmenu paste"],
          force_br_newlines : false,
          force_p_newlines : true,
          forced_root_block : "p",
          cleanup : false,
          cleanup_on_startup : false,
          font_size_style_values : "xx-small,x-small,small,medium,large,x-large,xx-large",
          convert_fonts_to_spans : true,
          resize: false,
          relative_urls : false,
          oninit: function(ed) {
              $(ed.contentAreaContainer).droppable({
                  accept: ".imgList li.imgContainer",
                  drop: function(event, ui) {
                      var draggedImg = ui.draggable.find("img");
                      var src = '';
                      if(typeof draggedImg.attr("largesrc") == "undefined") {
                          src = draggedImg.attr("src")
                      } else {
                          src = draggedImg.attr("largesrc");
                      }
                      ed.execCommand('mceInsertContent', false, "");
                  }
              });
          }
      };

      var config = $(element).data('config');

      if(config.height) {
          options.height = config.height;
      }

      if(config.style_formats) {
         options.style_formats = config.style_formats;
      }

      if(config.formats) {
          options.formats = config.formats;
      }

      if(config.toolbar1) {
          options.toolbar1 = config.toolbar1
      }

      if(config.toolbar2) {
          options.toolbar2 = config.toolbar2
      }

      if(config.content_css) {
        options.content_css = config.content_css
      }

      $(element).tinymce(options);
    };

    $(form).find('[data-wysiwyg]').each(function(index, element) {
      addTinymce(element);
    });
  };

  this.initSave = function (form) {
    $(form).find('[data-button][data-type=save]').click(function(event) {
      event.preventDefault();
      $(this).trigger('formSaveBefore', form);

      form = $(form);
      var data = form.serialize();
      var action = form.attr('action');
      admin.openLoadingOverlay();
      $.ajax({
        type: 'POST',
        data: data,
        url: action,
        success: function(data) {
          $(form).trigger('formSaveAfter', form);
        },
        error: function(jqXHR) {
          admin.closeLoadingOverlay();
          var data = JSON.parse(jqXHR.responseText);

          if(data.code == 400) {
            var getErrors = function(data, errors) {
              if(typeof errors == 'undefined') {
                errors = [];
              }

              for (var key in data) {
                if(data.hasOwnProperty(key)) {

                  if(key == 'errors') {
                    for (var error in data[key]) {
                      if (data[key].hasOwnProperty(error) && typeof data[key][error] == 'string') {
                        errors.push(data[key][error]);
                      }
                    }
                  }

                  if (typeof data[key] == 'object') {
                    getErrors(data[key], errors);
                  }

                }
              }

              return errors
            };

            var errors = getErrors(data.errors);
            var message = '' + errors.join('

') + '';
            admin.overlayMessage(message, MessageType.Error);
          } else {
            admin.overlayMessage(translator.trans('error.occurred'), MessageType.Error);
          }
        }
      });
    });
  };

  this.initPreviewButton = function(form) {
    $(form).find('[data-button][data-type=preview]').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var route = $(this).data('route');
      var link = router.generate(route);
      admin.iframeOverlay(form,link,{
        submit: true
      });
    });
  };

  this.initDelete = function(form)
  {
    $(form).find('[data-button][data-type=delete]').click(function() {
      var url = $(form).data('delete');
      if(confirm(translator.trans('form.delete.question'))) {
        admin.openLoadingOverlay();
        $.ajax({
          type: 'POST',
          data: {
            _method: 'DELETE'
          },
          url: url,
          success: function() {
            admin.closeLoadingOverlay();
            $(form).trigger('formSaveAfter', form);
          },
          error: function() {
            admin.closeLoadingOverlay();
            alert(translator.trans('error.occurred'));
          }
        });
      }
    });
  };

  this.initSorting = function(form) {
    var setOrder = function() {
      $(form).find('[data-sort-order]').each(function(index, element) {
        $(element).val(index);
      });
    };

    $(form).find('[data-sort-up-button]').click(function() {
      var item = $(this).parents('[data-sort-row]');
      var container = item.parents('[data-sort-container]');
      var index = container.children().index(item);
      if(index > 0) { // is not first element
        $(container.children().get(index - 1)).before(item); //move element before last
      }
      setOrder();
    });

    $(form).find('[data-sort-down-button]').click(function() {
      var item = $(this).parents('[data-sort-row]');
      var container = item.parents('[data-sort-container]');
      var index = container.children().index(item);
      var size = container.children().size();

      if(index < (size - 1)) { // is not last element
        $(container.children().get(index + 1)).after(item); //move element after next
      }
      setOrder();
    });

    $(form).find('[data-sort-container]').sortable({
      update: function() {
        setOrder();
      },
      axis: 'y',
      cursor: "move",
      handle: '[data-sort-handle]'
    });

    setOrder();
  };

  this.initInput = function(form) {
    $('input').keypress(function(e) {
      if(e.which == 13) {
        event.preventDefault();
      }
    });
  };

  this.initList = function(form) {

    var initDeleteButton = function(item) {
      $(item).on('click', '.button-delete', function (e) {
          e.preventDefault();
          $(this).parents('.listElement').remove();
        });
    };

    var initAddButton = function(list, count) {
      list.parent().find('.add-another').click(function(e) {
        e.preventDefault();

        // grab the prototype template
        var item = list.attr('data-prototype');
        // replace the "__name__" used in the id and name of the prototype
        // with a number that's unique to your emails
        // end name attribute looks like name="contact[emails][2]"
        item = item.replace(/__name__/g, count);
        count++;

        item = $.parseHTML(item.trim());
        initItem(item);
        $(document).trigger('formListAddItem', item);
        list.append(item);
        setOrderForContainer(list);
      })
    };

    var initItem = function(item) {
      initButtonUp(item);
      initButtonDown(item);
      initDeleteButton(item);
    };

    var initButtonUp = function(item) {
      $(item).on('click', '.button-up', function() {
        var liElement = $(this).parent();
        while(!liElement.hasClass('listElement')) {
          liElement = liElement.parent();
        }
        var list = liElement.parent();
        var index = list.children().index(liElement);

        if(index > 0) { // is not first element
          if(liElement.find('[data-wysiwyg]').length) {
            var editorId = liElement.find('[data-wysiwyg]').attr('id');
            tinymce.execCommand('mceRemoveEditor', false, editorId);
            $(list.children().get(index - 1)).before(liElement); //move element before last
            tinymce.execCommand('mceAddEditor', false, editorId);
          } else {
            $(list.children().get(index - 1)).before(liElement); //move element before last
          }
        }

        setOrderForContainer(list);
      });
    };

    var initButtonDown = function(item) {
      $(item).on('click', '.button-down', function() {
        var liElement = $(this).parent();
        while(!liElement.hasClass('listElement')) {
          liElement = liElement.parent();
        }
        var list = liElement.parent();
        var index = list.children().index(liElement);
        var size = list.children().size();

        if(index < (size - 1)) { // is not last element
          if(liElement.find('[data-wysiwyg]').length) {
            var editorId = liElement.find('[data-wysiwyg]').attr('id');
            tinymce.execCommand('mceRemoveEditor', false, editorId);
            $(list.children().get(index + 1)).after(liElement); //move element after next
            tinymce.execCommand('mceAddEditor', false, editorId);
          } else {
            $(list.children().get(index + 1)).after(liElement); //move element after next
          }
        }

        setOrderForContainer(list)
      });
    };

    var setOrderForContainer = function(list) {
      var orderby = list.attr('data-order');
      list.find("."+orderby).each(function(index) {
        $(this).val(index+1);
      });
    };

    (function(form) {
      $(form).find('.enhavo_list').each(function() {
        var list = $(this);

        $.each(list.children(), function(index, item) {
          initItem($(item));
        });

        setOrderForContainer(list);

        var count = $(this).children().length;
        initAddButton(list, count);
      });
    })(form);
  };

  var init = function() {
    $(document).on('formOpenAfter', function(event, form) {
      self.initDataPicker(form);
      self.initRadioAndCheckbox(form);
      self.initPreviewButton(form);
      self.initWysiwyg(form);
      self.initSave(form);
      self.initDelete(form);
      self.initSelect(form);
      self.initSorting(form);
      self.initInput(form);
      self.initList(form);
    });

    $(document).on('formListAddItem', function(event, item) {
      self.initSelect(item);
      self.initRadioAndCheckbox(item);
      self.initDataPicker(item);
      self.initInput(item);
      self.initWysiwyg(item);
    });

    $(document).on('formSaveAfter', function() {
      admin.overlayClose();
    });

    $(document).on('formCloseAfter', function(event, content) {
      self.destroyWysiwyg(content);
      admin.closeLoadingOverlay();
    });
  };

  init();
};
<commit_msg>fix checkbox node at add list<commit_after>var Form = function(router, templating, admin, translator)
{
  var self = this;

  var MessageType = {
    Info: 'info',
    Error: 'error',
    Success: 'success'
  };

  this.initDataPicker = function(form)
  {
    $(form).find('input.datetimepicker').datetimepicker({
      timeFormat: 'hh:mm',
      timeText: 'Zeit',
      hourText: 'Std.',
      minuteText: 'Min.',
      currentText: 'Jetzt',
      closeText: 'Fertig',
      dateFormat: 'dd.mm.yy',
      stepMinute: 5,
      firstDay: 1
    });

    $(form).find('input.datepicker').datepicker({
      closeText: 'Fertig',
      dateFormat: 'dd.mm.yy',
      firstDay: 1
    });
  };

  this.initRadioAndCheckbox = function (form) {
    $(form).find('input[type=radio],input[type=checkbox]').iCheck({
      checkboxClass: 'icheckbox-esperanto',
      radioClass: 'icheckbox-esperanto'
    });
  };

  this.initSelect = function (form) {
    $(form).find('select').select2();
  };

  this.destroyWysiwyg = function(content) {
    content.find('.wysiwyg').each(function() {
      tinymce.remove('#'.$(this).attr('id'));
    });
  };

  this.initWysiwyg = function(form)
  {
    var addTinymce = function(element) {

      var options = {
          // Location of TinyMCE script
          script_url : '/js/lib/tinymce/tinymce.min.js',
          //content_css: "/css/editor.css",
          menubar: false,
          // General options
          plugins: ["advlist autolink lists link image charmap print preview anchor",
              "searchreplace visualblocks code fullscreen",
              "insertdatetime media table contextmenu paste"],
          force_br_newlines : false,
          force_p_newlines : true,
          forced_root_block : "p",
          cleanup : false,
          cleanup_on_startup : false,
          font_size_style_values : "xx-small,x-small,small,medium,large,x-large,xx-large",
          convert_fonts_to_spans : true,
          resize: false,
          relative_urls : false,
          oninit: function(ed) {
              $(ed.contentAreaContainer).droppable({
                  accept: ".imgList li.imgContainer",
                  drop: function(event, ui) {
                      var draggedImg = ui.draggable.find("img");
                      var src = '';
                      if(typeof draggedImg.attr("largesrc") == "undefined") {
                          src = draggedImg.attr("src")
                      } else {
                          src = draggedImg.attr("largesrc");
                      }
                      ed.execCommand('mceInsertContent', false, "");
                  }
              });
          }
      };

      var config = $(element).data('config');

      if(config.height) {
          options.height = config.height;
      }

      if(config.style_formats) {
         options.style_formats = config.style_formats;
      }

      if(config.formats) {
          options.formats = config.formats;
      }

      if(config.toolbar1) {
          options.toolbar1 = config.toolbar1
      }

      if(config.toolbar2) {
          options.toolbar2 = config.toolbar2
      }

      if(config.content_css) {
        options.content_css = config.content_css
      }

      $(element).tinymce(options);
    };

    $(form).find('[data-wysiwyg]').each(function(index, element) {
      addTinymce(element);
    });
  };

  this.initSave = function (form) {
    $(form).find('[data-button][data-type=save]').click(function(event) {
      event.preventDefault();
      $(this).trigger('formSaveBefore', form);

      form = $(form);
      var data = form.serialize();
      var action = form.attr('action');
      admin.openLoadingOverlay();
      $.ajax({
        type: 'POST',
        data: data,
        url: action,
        success: function(data) {
          $(form).trigger('formSaveAfter', form);
        },
        error: function(jqXHR) {
          admin.closeLoadingOverlay();
          var data = JSON.parse(jqXHR.responseText);

          if(data.code == 400) {
            var getErrors = function(data, errors) {
              if(typeof errors == 'undefined') {
                errors = [];
              }

              for (var key in data) {
                if(data.hasOwnProperty(key)) {

                  if(key == 'errors') {
                    for (var error in data[key]) {
                      if (data[key].hasOwnProperty(error) && typeof data[key][error] == 'string') {
                        errors.push(data[key][error]);
                      }
                    }
                  }

                  if (typeof data[key] == 'object') {
                    getErrors(data[key], errors);
                  }

                }
              }

              return errors
            };

            var errors = getErrors(data.errors);
            var message = '' + errors.join('

') + '';
            admin.overlayMessage(message, MessageType.Error);
          } else {
            admin.overlayMessage(translator.trans('error.occurred'), MessageType.Error);
          }
        }
      });
    });
  };

  this.initPreviewButton = function(form) {
    $(form).find('[data-button][data-type=preview]').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      var route = $(this).data('route');
      var link = router.generate(route);
      admin.iframeOverlay(form,link,{
        submit: true
      });
    });
  };

  this.initDelete = function(form)
  {
    $(form).find('[data-button][data-type=delete]').click(function() {
      var url = $(form).data('delete');
      if(confirm(translator.trans('form.delete.question'))) {
        admin.openLoadingOverlay();
        $.ajax({
          type: 'POST',
          data: {
            _method: 'DELETE'
          },
          url: url,
          success: function() {
            admin.closeLoadingOverlay();
            $(form).trigger('formSaveAfter', form);
          },
          error: function() {
            admin.closeLoadingOverlay();
            alert(translator.trans('error.occurred'));
          }
        });
      }
    });
  };

  this.initSorting = function(form) {
    var setOrder = function() {
      $(form).find('[data-sort-order]').each(function(index, element) {
        $(element).val(index);
      });
    };

    $(form).find('[data-sort-up-button]').click(function() {
      var item = $(this).parents('[data-sort-row]');
      var container = item.parents('[data-sort-container]');
      var index = container.children().index(item);
      if(index > 0) { // is not first element
        $(container.children().get(index - 1)).before(item); //move element before last
      }
      setOrder();
    });

    $(form).find('[data-sort-down-button]').click(function() {
      var item = $(this).parents('[data-sort-row]');
      var container = item.parents('[data-sort-container]');
      var index = container.children().index(item);
      var size = container.children().size();

      if(index < (size - 1)) { // is not last element
        $(container.children().get(index + 1)).after(item); //move element after next
      }
      setOrder();
    });

    $(form).find('[data-sort-container]').sortable({
      update: function() {
        setOrder();
      },
      axis: 'y',
      cursor: "move",
      handle: '[data-sort-handle]'
    });

    setOrder();
  };

  this.initInput = function(form) {
    $('input').keypress(function(e) {
      if(e.which == 13) {
        event.preventDefault();
      }
    });
  };

  this.initList = function(form) {

    var initDeleteButton = function(item) {
      $(item).on('click', '.button-delete', function (e) {
          e.preventDefault();
          $(this).parents('.listElement').remove();
        });
    };

    var initAddButton = function(list, count) {
      list.parent().find('.add-another').click(function(e) {
        e.preventDefault();

        // grab the prototype template
        var item = list.attr('data-prototype');
        // replace the "__name__" used in the id and name of the prototype
        // with a number that's unique to your emails
        // end name attribute looks like name="contact[emails][2]"
        item = item.replace(/__name__/g, count);
        count++;

        item = $.parseHTML(item.trim());
        list.append(item);
        initItem(item);
        $(document).trigger('formListAddItem', item);
        setOrderForContainer(list);
      })
    };

    var initItem = function(item) {
      initButtonUp(item);
      initButtonDown(item);
      initDeleteButton(item);
    };

    var initButtonUp = function(item) {
      $(item).on('click', '.button-up', function() {
        var liElement = $(this).parent();
        while(!liElement.hasClass('listElement')) {
          liElement = liElement.parent();
        }
        var list = liElement.parent();
        var index = list.children().index(liElement);

        if(index > 0) { // is not first element
          if(liElement.find('[data-wysiwyg]').length) {
            var editorId = liElement.find('[data-wysiwyg]').attr('id');
            tinymce.execCommand('mceRemoveEditor', false, editorId);
            $(list.children().get(index - 1)).before(liElement); //move element before last
            tinymce.execCommand('mceAddEditor', false, editorId);
          } else {
            $(list.children().get(index - 1)).before(liElement); //move element before last
          }
        }

        setOrderForContainer(list);
      });
    };

    var initButtonDown = function(item) {
      $(item).on('click', '.button-down', function() {
        var liElement = $(this).parent();
        while(!liElement.hasClass('listElement')) {
          liElement = liElement.parent();
        }
        var list = liElement.parent();
        var index = list.children().index(liElement);
        var size = list.children().size();

        if(index < (size - 1)) { // is not last element
          if(liElement.find('[data-wysiwyg]').length) {
            var editorId = liElement.find('[data-wysiwyg]').attr('id');
            tinymce.execCommand('mceRemoveEditor', false, editorId);
            $(list.children().get(index + 1)).after(liElement); //move element after next
            tinymce.execCommand('mceAddEditor', false, editorId);
          } else {
            $(list.children().get(index + 1)).after(liElement); //move element after next
          }
        }

        setOrderForContainer(list)
      });
    };

    var setOrderForContainer = function(list) {
      var orderby = list.attr('data-order');
      list.find("."+orderby).each(function(index) {
        $(this).val(index+1);
      });
    };

    (function(form) {
      $(form).find('.enhavo_list').each(function() {
        var list = $(this);

        $.each(list.children(), function(index, item) {
          initItem($(item));
        });

        setOrderForContainer(list);

        var count = $(this).children().length;
        initAddButton(list, count);
      });
    })(form);
  };

  var init = function() {
    $(document).on('formOpenAfter', function(event, form) {
      self.initDataPicker(form);
      self.initRadioAndCheckbox(form);
      self.initPreviewButton(form);
      self.initWysiwyg(form);
      self.initSave(form);
      self.initDelete(form);
      self.initSelect(form);
      self.initSorting(form);
      self.initInput(form);
      self.initList(form);
    });

    $(document).on('formListAddItem', function(event, item) {
      self.initSelect(item);
      self.initRadioAndCheckbox(item);
      self.initDataPicker(item);
      self.initInput(item);
      self.initWysiwyg(item);
    });

    $(document).on('formSaveAfter', function() {
      admin.overlayClose();
    });

    $(document).on('formCloseAfter', function(event, content) {
      self.destroyWysiwyg(content);
      admin.closeLoadingOverlay();
    });
  };

  init();
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var galleryController = function($scope, GalleryService, $mdSidenav, $mdPanel, $mdDialog, $timeout) {
        $scope.currentDir = "";
        $scope.currentFilter = "";
        $scope.loading = false;
        $scope.freshlyStarted = true;

        GalleryService.getAvailableGalleries()
        .then(function(res) {
            $scope.galleries = res.data;
        });

        $scope.toggleNav = function() {
            $mdSidenav('left').toggle();
        }

        // open sidenav on page loading
        $timeout(function() {
            $mdSidenav('left').open();
        });

        function preloadImage(file) {
            if (!file) {
                return;
            }
            $timeout(function() {
                const preloadNextImage = new Image();
                preloadNextImage.src = file.name;
            });
        }

        $scope.getFiles = function(dir) {
            GalleryService.getFiles(dir)
            .then(function(res) {
                $scope.files = res.data;
                $scope.currentDir = dir;
                $scope.loading = false;
                preloadImage($scope.files[0]);
            });

            $scope.files = null;
            $scope.loading = true;
            $mdSidenav('left').toggle();

            if ($scope.freshlyStarted) {
                // enable fullscreen on first click
                document.documentElement.webkitRequestFullscreen();
                $scope.freshlyStarted = false;
            }
        }

        $scope.getBackgroundImage = function(path) {
            return {
                'background-image': 'url(\"' + path + '\")',
                'background-repeat': 'no-repeat',
                'background-size': '100% auto'
            }
        }

        $scope.showPanel = function(file) {
            $mdPanel.open({
                attachTo: angular.element(document.body),
                controller: 'PanelController',
                controllerAs: 'ctrl',
                disableParentScroll: true,
                templateUrl: 'views/panel.html',
                hasBackdrop: true,
                panelClass: 'photo-panel',
                position: $mdPanel.newPanelPosition().absolute().center(),
                trapFocus: true,
                zIndex: 150,
                clickOutsideToClose: true, // will enable it, just have to figure out why sometimes it doesn't work
                escapeToClose: true,
                focusOnOpen: true,
                fileObject: file,
                showPanel: $scope.showPanel
            });
            preloadImage(file.next);
        }

        $scope.toggleFullscreen = function() {
            if (document.webkitIsFullScreen) {
                document.webkitExitFullscreen();
            } else {
                document.documentElement.webkitRequestFullscreen();
            }
        }

        $scope.shutdown = function() {
            const confirmationDialog = $mdDialog.confirm({
                title: 'Ausschalten',
                textContent: 'Soll das Gerät wirklich ausgeschaltet werden?',
                ok: 'Ja',
                cancel: 'Nein'
            })
            $mdDialog.show(confirmationDialog)
                .then(GalleryService.shutdown)
                .catch(() => null);
        }

        $scope.sound = true;
        $scope.volume = 100;

        $scope.soundSwitch = function() {
            if ($scope.sound) {
                GalleryService.soundPlay();
            } else {
                GalleryService.soundPause();
            }
        }

        $scope.soundVolume = () => GalleryService.soundVolume($scope.volume / 100.);
    };

    angular.module('fgallery-controllers').controller(
        'GalleryController',
        [ '$scope', 'GalleryService', '$mdSidenav', '$mdPanel', '$mdDialog', '$timeout', galleryController ]
    );
})();<commit_msg>use regular confirm for better stability<commit_after>(function() {
    'use strict';

    var galleryController = function($scope, GalleryService, $mdSidenav, $mdPanel, $mdDialog, $timeout) {
        $scope.currentDir = "";
        $scope.currentFilter = "";
        $scope.loading = false;
        $scope.freshlyStarted = true;

        GalleryService.getAvailableGalleries()
        .then(function(res) {
            $scope.galleries = res.data;
        });

        $scope.toggleNav = function() {
            $mdSidenav('left').toggle();
        }

        // open sidenav on page loading
        $timeout(function() {
            $mdSidenav('left').open();
        });

        function preloadImage(file) {
            if (!file) {
                return;
            }
            $timeout(function() {
                const preloadNextImage = new Image();
                preloadNextImage.src = file.name;
            });
        }

        $scope.getFiles = function(dir) {
            GalleryService.getFiles(dir)
            .then(function(res) {
                $scope.files = res.data;
                $scope.currentDir = dir;
                $scope.loading = false;
                preloadImage($scope.files[0]);
            });

            $scope.files = null;
            $scope.loading = true;
            $mdSidenav('left').toggle();

            if ($scope.freshlyStarted) {
                // enable fullscreen on first click
                document.documentElement.webkitRequestFullscreen();
                $scope.freshlyStarted = false;
            }
        }

        $scope.getBackgroundImage = function(path) {
            return {
                'background-image': 'url(\"' + path + '\")',
                'background-repeat': 'no-repeat',
                'background-size': '100% auto'
            }
        }

        $scope.showPanel = function(file) {
            $mdPanel.open({
                attachTo: angular.element(document.body),
                controller: 'PanelController',
                controllerAs: 'ctrl',
                disableParentScroll: true,
                templateUrl: 'views/panel.html',
                hasBackdrop: true,
                panelClass: 'photo-panel',
                position: $mdPanel.newPanelPosition().absolute().center(),
                trapFocus: true,
                zIndex: 150,
                clickOutsideToClose: true, // will enable it, just have to figure out why sometimes it doesn't work
                escapeToClose: true,
                focusOnOpen: true,
                fileObject: file,
                showPanel: $scope.showPanel
            });
            preloadImage(file.next);
        }

        $scope.toggleFullscreen = function() {
            if (document.webkitIsFullScreen) {
                document.webkitExitFullscreen();
            } else {
                document.documentElement.webkitRequestFullscreen();
            }
        }

        $scope.shutdown = function() {
            if (confirm('Soll das Gerät wirklich ausgeschaltet werden?')) {
                GalleryService.shutdown();
            }
        }

        $scope.sound = true;
        $scope.volume = 100;

        $scope.soundSwitch = function() {
            if ($scope.sound) {
                GalleryService.soundPlay();
            } else {
                GalleryService.soundPause();
            }
        }

        $scope.soundVolume = () => GalleryService.soundVolume($scope.volume / 100.);
    };

    angular.module('fgallery-controllers').controller(
        'GalleryController',
        [ '$scope', 'GalleryService', '$mdSidenav', '$mdPanel', '$mdDialog', '$timeout', galleryController ]
    );
})();<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
YUI().use('addon-rs-config', 'base', 'oop', 'test', function(Y) {

    var suite = new YUITest.TestSuite('mojito-addon-rs-config-tests'),
        libfs = require('fs'),
        libpath = require('path'),
        mojitoRoot = libpath.join(__dirname, '../../../../../../lib'),
        A = YUITest.Assert,
        OA = YUITest.ObjectAssert,
        AA = YUITest.ArrayAssert;

    function MockRS(config) {
        MockRS.superclass.constructor.apply(this, arguments);
    }
    MockRS.NAME = 'MockResourceStore';
    MockRS.ATTRS = {};
    Y.extend(MockRS, Y.Base, {

        initializer: function(cfg) {
            this._config = cfg || {};
        },

        validateContext: function() {
        },

        cloneObj: function(o) {
            return Y.clone(o);
        },

        getStaticContext: function() {
            return this._config.context || {};
        },

        mergeRecursive: function(dest, src, typeMatch) {
            var p;
            for (p in src) {
                if (src.hasOwnProperty(p)) {
                    // Property in destination object set; update its value.
                    if (src[p] && src[p].constructor === Object) {
                        if (!dest[p]) {
                            dest[p] = {};
                        }
                        dest[p] = this.mergeRecursive(dest[p], src[p]);
                    } else {
                        if (dest[p] && typeMatch) {
                            if (typeof dest[p] === typeof src[p]) {
                                dest[p] = src[p];
                            }
                        } else {
                            dest[p] = src[p];
                        }
                    }
                }
            }
            return dest;
        },

        findResourceVersionByConvention: function(source, mojitType) {
            // no-op
        },

        parseResourceVersion: function(source, type, subtype, mojitType) {
            // no-op
        }

    });

    function readJSON(dir, file) {
        var path = libpath.join(dir, file);
        var contents = libfs.readFileSync(path, 'utf-8');
        return Y.JSON.parse(contents);
    }

    function cmp(x, y, msg, path) {
        if (Y.Lang.isArray(x)) {
            A.isArray(x, msg || 'first arg should be an array');
            A.isArray(y, msg || 'second arg should be an array');
            A.areSame(x.length, y.length, msg || 'arrays are different lengths');
            for (var i = 0; i < x.length; i += 1) {
                cmp(x[i], y[i], msg);
            }
            return;
        }
        if (Y.Lang.isObject(x)) {
            A.isObject(x, msg || 'first arg should be an object');
            A.isObject(y, msg || 'second arg should be an object');
            A.areSame(Object.keys(x).length, Object.keys(y).length, msg || 'object keys are different lengths');
            for (var i in x) {
                if (x.hasOwnProperty(i)) {
                    cmp(x[i], y[i], msg);
                }
            }
            return;
        }
        A.areSame(x, y, msg || 'args should be the same');
    }

    function makeSource(dir, dirType, subdir, file, isFile) {
        var source = {
            fs: {
                fullPath: libpath.join(dir, subdir, file),
                rootDir: dir,
                rootType: dirType,
                subDir: subdir,
                subDirArray: subdir.split('/'),
                isFile: isFile,
                ext: libpath.extname(file)
            },
            pkg: {
                name: 'unittest',
                version: '999.666.999',
                depth: 999
            }
        };
        source.fs.basename = libpath.basename(file, source.fs.ext);
        return source;
    }

    suite.add(new YUITest.TestCase({

        name: 'config rs addon tests',

        'read dimensions': function() {
            // from mojito
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );
            var have = store.config.getDimensions();
            var want = readJSON(mojitoRoot, 'dimensions.json');
            cmp(want, have);

            // app-specified
            fixtures = libpath.join(__dirname, '../../../../../fixtures/ycb');
            store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );
            have = store.config.getDimensions();
            want = readJSON(fixtures, 'dimensions.json');
            cmp(want, have);
        },

        'find config resources': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            // skip non-json files
            var source = makeSource(fixtures, 'app', '.', 'server.js', true);
            var have = store.findResourceVersionByConvention(source, null);
            var want = undefined;
            cmp(have, want, 'skip non-json files');

            // include all json files in the app
            source = makeSource(fixtures, 'app', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = { type: 'config' };
            cmp(have, want, 'include all json files in the app');

            // ... explicitly including package.json
            source = makeSource(fixtures, 'app', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = { type: 'config' };
            cmp(have, want, 'include package.json in the app');

            // exclude all json files in a bundle
            source = makeSource(fixtures, 'bundle', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = undefined;
            cmp(have, want, 'exclude all json files in a bundle');

            // ... explicitly excluding package.json
            source = makeSource(fixtures, 'bundle', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = undefined;
            cmp(have, want, 'exclude package.json in a bundle');

            // include all json files in a mojit
            source = makeSource(fixtures, 'mojit', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, 'foo');
            want = { type: 'config' };
            cmp(have, want, 'include all json files in a mojit');

            // ... except for the 'shared' mojit
            source = makeSource(fixtures, 'mojit', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, 'shared');
            want = undefined;
            cmp(have, want, 'exclude all json files in the "shared" mojit');

            // ... explicitly including package.json
            source = makeSource(fixtures, 'mojit', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, 'shared');
            want = { type: 'config' };
            cmp(have, want, 'include package.json in the "shared" mojit');
        },

        'parse found resource': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var source = makeSource(fixtures, 'app', '.', 'application.json', true);
            var res = store.parseResourceVersion(source, 'config');
            A.isNotUndefined(res);
            cmp(res.source, source);
            A.areSame('config', res.type);
            A.areSame('common', res.affinity);
            A.areSame('*', res.selector);
            A.areSame('application', res.name);
            A.areSame('config--application', res.id);
            A.isUndefined(res.mojit);

            source = makeSource(fixtures, 'mojit', '.', 'defaults.json', true);
            res = store.parseResourceVersion(source, 'config', undefined, 'x');
            A.isNotUndefined(res);
            cmp(res.source, source);
            A.areSame('config', res.type);
            A.areSame('common', res.affinity);
            A.areSame('*', res.selector);
            A.areSame('defaults', res.name);
            A.areSame('config--defaults', res.id);
            A.areSame('x', res.mojit);
        },

        'read JSON files': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'application.json');
            var have = store.config.readConfigSimple(path);
            var want = readJSON(fixtures, 'application.json');
            cmp(have, want);
        },

        'read YCB files': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'application.json');
            var have = store.config.readConfigYCB(path, { runtime: 'server' });
            var want = {
                "mojitDirs": [
                    "soloMojit"
                ],
                "staticHandling": {
                    "useRollups": true
                },
                "testKey1": "testVal1-server",
                "testKey2": "testVal2",
                "testKey3": "testVal3",
                "specs": {
                    "test1": {
                        "type": "test_mojit_1"
                    }
                },
                "selector": "shelves",
                "pathos": "portended"
            };
            cmp(have, want);
        },

        'malformed JSON for config file': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/badfiles2');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'routes.json');
            try {
                store.config.readConfigSimple(path);
            }
            catch (err) {
                A.areSame('Error parsing JSON file:', err.message.substr(0, 24));
            }
        },

        'JSON config file not YCB': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/badfiles3');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'routes.json');
            var have = store.config.readConfigYCB(path, {});
            var want = {};
            cmp(have, want);
        }

    }));

    Y.Test.Runner.add(suite);

});
<commit_msg>Updated test case that was not run locally<commit_after>/*
 * Copyright (c) 2011-2012, Yahoo! Inc.  All rights reserved.
 * Copyrights licensed under the New BSD License.
 * See the accompanying LICENSE file for terms.
 */
YUI().use('addon-rs-config', 'base', 'oop', 'test', function(Y) {

    var suite = new YUITest.TestSuite('mojito-addon-rs-config-tests'),
        libfs = require('fs'),
        libpath = require('path'),
        mojitoRoot = libpath.join(__dirname, '../../../../../../lib'),
        A = YUITest.Assert,
        OA = YUITest.ObjectAssert,
        AA = YUITest.ArrayAssert;

    function MockRS(config) {
        MockRS.superclass.constructor.apply(this, arguments);
    }
    MockRS.NAME = 'MockResourceStore';
    MockRS.ATTRS = {};
    Y.extend(MockRS, Y.Base, {

        initializer: function(cfg) {
            this._config = cfg || {};
        },

        validateContext: function() {
        },

        cloneObj: function(o) {
            return Y.clone(o);
        },

        getStaticContext: function() {
            return this._config.context || {};
        },

        mergeRecursive: function(dest, src, typeMatch) {
            var p;
            for (p in src) {
                if (src.hasOwnProperty(p)) {
                    // Property in destination object set; update its value.
                    if (src[p] && src[p].constructor === Object) {
                        if (!dest[p]) {
                            dest[p] = {};
                        }
                        dest[p] = this.mergeRecursive(dest[p], src[p]);
                    } else {
                        if (dest[p] && typeMatch) {
                            if (typeof dest[p] === typeof src[p]) {
                                dest[p] = src[p];
                            }
                        } else {
                            dest[p] = src[p];
                        }
                    }
                }
            }
            return dest;
        },

        findResourceVersionByConvention: function(source, mojitType) {
            // no-op
        },

        parseResourceVersion: function(source, type, subtype, mojitType) {
            // no-op
        }

    });

    function readJSON(dir, file) {
        var path = libpath.join(dir, file);
        var contents = libfs.readFileSync(path, 'utf-8');
        return Y.JSON.parse(contents);
    }

    function cmp(x, y, msg, path) {
        if (Y.Lang.isArray(x)) {
            A.isArray(x, msg || 'first arg should be an array');
            A.isArray(y, msg || 'second arg should be an array');
            A.areSame(x.length, y.length, msg || 'arrays are different lengths');
            for (var i = 0; i < x.length; i += 1) {
                cmp(x[i], y[i], msg);
            }
            return;
        }
        if (Y.Lang.isObject(x)) {
            A.isObject(x, msg || 'first arg should be an object');
            A.isObject(y, msg || 'second arg should be an object');
            A.areSame(Object.keys(x).length, Object.keys(y).length, msg || 'object keys are different lengths');
            for (var i in x) {
                if (x.hasOwnProperty(i)) {
                    cmp(x[i], y[i], msg);
                }
            }
            return;
        }
        A.areSame(x, y, msg || 'args should be the same');
    }

    function makeSource(dir, dirType, subdir, file, isFile) {
        var source = {
            fs: {
                fullPath: libpath.join(dir, subdir, file),
                rootDir: dir,
                rootType: dirType,
                subDir: subdir,
                subDirArray: subdir.split('/'),
                isFile: isFile,
                ext: libpath.extname(file)
            },
            pkg: {
                name: 'unittest',
                version: '999.666.999',
                depth: 999
            }
        };
        source.fs.basename = libpath.basename(file, source.fs.ext);
        return source;
    }

    suite.add(new YUITest.TestCase({

        name: 'config rs addon tests',

        'read dimensions': function() {
            // from mojito
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );
            var have = store.config.getDimensions();
            var want = readJSON(mojitoRoot, 'dimensions.json');
            cmp(want, have);

            // app-specified
            fixtures = libpath.join(__dirname, '../../../../../fixtures/ycb');
            store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );
            have = store.config.getDimensions();
            want = readJSON(fixtures, 'dimensions.json');
            cmp(want, have);
        },

        'find config resources': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            // skip non-json files
            var source = makeSource(fixtures, 'app', '.', 'server.js', true);
            var have = store.findResourceVersionByConvention(source, null);
            var want = undefined;
            cmp(have, want, 'skip non-json files');

            // include all json files in the app
            source = makeSource(fixtures, 'app', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = { type: 'config' };
            cmp(have, want, 'include all json files in the app');

            // ... explicitly including package.json
            source = makeSource(fixtures, 'app', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = { type: 'config' };
            cmp(have, want, 'include package.json in the app');

            // exclude all json files in a bundle
            source = makeSource(fixtures, 'bundle', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = undefined;
            cmp(have, want, 'exclude all json files in a bundle');

            // ... explicitly excluding package.json
            source = makeSource(fixtures, 'bundle', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, null);
            want = undefined;
            cmp(have, want, 'exclude package.json in a bundle');

            // include all json files in a mojit
            source = makeSource(fixtures, 'mojit', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, 'foo');
            want = { type: 'config' };
            cmp(have, want, 'include all json files in a mojit');

            // ... except for the 'shared' mojit
            source = makeSource(fixtures, 'mojit', '.', 'x.json', true);
            have = store.findResourceVersionByConvention(source, 'shared');
            want = undefined;
            cmp(have, want, 'exclude all json files in the "shared" mojit');

            // ... explicitly including package.json
            source = makeSource(fixtures, 'mojit', '.', 'package.json', true);
            have = store.findResourceVersionByConvention(source, 'shared');
            want = { type: 'config' };
            cmp(have, want, 'include package.json in the "shared" mojit');
        },

        'parse found resource': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var source = makeSource(fixtures, 'app', '.', 'application.json', true);
            var res = store.parseResourceVersion(source, 'config');
            A.isNotUndefined(res);
            cmp(res.source, source);
            A.areSame('config', res.type);
            A.areSame('common', res.affinity);
            A.areSame('*', res.selector);
            A.areSame('application', res.name);
            A.areSame('config--application', res.id);
            A.isUndefined(res.mojit);

            source = makeSource(fixtures, 'mojit', '.', 'defaults.json', true);
            res = store.parseResourceVersion(source, 'config', undefined, 'x');
            A.isNotUndefined(res);
            cmp(res.source, source);
            A.areSame('config', res.type);
            A.areSame('common', res.affinity);
            A.areSame('*', res.selector);
            A.areSame('defaults', res.name);
            A.areSame('config--defaults', res.id);
            A.areSame('x', res.mojit);
        },

        'read JSON files': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'application.json');
            var have = store.config.readConfigSimple(path);
            var want = readJSON(fixtures, 'application.json');
            cmp(have, want);
        },

        'read YCB files': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/store');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'application.json');
            var have = store.config.readConfigYCB(path, { runtime: 'server' });
            var want = {
                "mojitDirs": [
                    "soloMojit"
                ],
                "staticHandling": {
                    "useRollups": true
                },
                "testKey1": "testVal1-server",
                "testKey2": "testVal2",
                "testKey3": "testVal3",
                "specs": {
                    "test1": {
                        "type": "test_mojit_1"
                    }
                },
                "selector": "shelves",
                "pathos": "portended"
            };
            cmp(have, want);
        },

        'malformed JSON for config file': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/badfiles2');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'routes.json');
            try {
                store.config.readConfigSimple(path);
            }
            catch (err) {
                A.areSame('Error parsing file:', err.message.substr(0, 19));
            }
        },

        'JSON config file not YCB': function() {
            var fixtures = libpath.join(__dirname, '../../../../../fixtures/badfiles3');
            var store = new MockRS({ root: fixtures });
            store.plug(Y.mojito.addons.rs.config, { appRoot: fixtures, mojitoRoot: mojitoRoot } );

            var path = libpath.join(fixtures, 'routes.json');
            var have = store.config.readConfigYCB(path, {});
            var want = {};
            cmp(have, want);
        }

    }));

    Y.Test.Runner.add(suite);

});
<|endoftext|>


<commit_before>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;
// get command line argument for commit message
module.exports = (branchName, args, callback) => {
  // remove \n from the end
  let command = 'git push';
  switch (args.length) {
    case 0:
      command += ` origin ${branchName}`;
      break;
    case 1:
      command += ` origin ${args[0]}`;
      break;
    case 2:
      command += ` ${args[0]} ${args[1]}`;
      break;
    default:
      callback(chalk.redBright('Invalid arguments'));
      return;
  }
  shell.exec(command, (code, stdout, stderr) => {
    console.log(code);
    if (stderr) {
      let output = `${chalk.red('Push failed')}`;
      if (code === 128) {
        console.log(1);
        output = `${output}\nUnable to reach git host\nPlease check your internet connection`;
        callback();
        return;
      }
      if (stderr.indexOf('rejected' !== -1)) {
        output = `${output}\n${chalk.redBright('Updates were rejected because the remote contains work that you do not have locally. This is usually caused by another repository pushing to the same ref. You may want to first integrate the remote changes (e.g., \'git pull ...\') before pushing again.')}`;
        callback(output);
        return;
      }
      // get hash
      // example:
      // To https://github.com/ridhamtarpara/short-git.git
      //   9ae2336..9835655  ft/push -> ft/push
      let commitHash = stderr.substr(stderr.indexOf('..') + 2);
      commitHash = commitHash.substr(0, commitHash.indexOf('  '));
      // get git url
      let url = stderr.substr(3, stderr.indexOf('\n') - 7);
      // Generate final url
      url = `${url}/commit/${commitHash}`;
      callback(`${chalk.greenBright('Push Successfull')}\nLink : ${url}`);
      return;
    }
    callback(chalk.greenBright(stdout));
  });
};
<commit_msg>push errorlog formatted<commit_after>#! /usr/bin/env node
const shell = require('shelljs');
const chalk = require('chalk');
// SET SILENT TRUE SO THAT DEFAULT OUTPUT IS NOT PRINTED ON CONSOLE
shell.config.silent = true;
// get command line argument for commit message
module.exports = (branchName, args, callback) => {
  // remove \n from the end
  let command = 'git push';
  switch (args.length) {
    case 0:
      command += ` origin ${branchName}`;
      break;
    case 1:
      command += ` origin ${args[0]}`;
      break;
    case 2:
      command += ` ${args[0]} ${args[1]}`;
      break;
    default:
      callback(chalk.redBright('Invalid arguments'));
      return;
  }
  shell.exec(command, (code, stdout, stderr) => {
    if (stderr) {
      let output = `${chalk.red('Push failed')}`;
      if (code === 128) {
        output = `${output}\nUnable to reach git host\nPlease check your internet connection`;
        callback(output);
        return;
      }
      if (stderr.indexOf('rejected' !== -1)) {
        output = `${output}\n${chalk.redBright('Updates were rejected because the remote contains work that you do not have locally. This is usually caused by another repository pushing to the same ref. You may want to first integrate the remote changes (e.g., \'git pull ...\') before pushing again.')}`;
        callback(output);
        return;
      }
      // get hash
      // example:
      // To https://github.com/ridhamtarpara/short-git.git
      //   9ae2336..9835655  ft/push -> ft/push
      let commitHash = stderr.substr(stderr.indexOf('..') + 2);
      commitHash = commitHash.substr(0, commitHash.indexOf('  '));
      // get git url
      let url = stderr.substr(3, stderr.indexOf('\n') - 7);
      // Generate final url
      url = `${url}/commit/${commitHash}`;
      callback(`${chalk.greenBright('Push Successfull')}\nLink : ${url}`);
      return;
    }
    callback(chalk.greenBright(stdout));
  });
};
<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setUpTestLocale } from '../../helpers/utils';
import { createComponentMock } from '../../helpers/mocks';

module('Unit | Service | challenge-expectations', function (hooks) {
  setupTest(hooks);
  setUpTestLocale(hooks)

  var challengeExpectations
  const decompositionKey = 'decomposition'
  const expectationStringMock = 'ExpectationMock'
  const expectationsName = 'expectations'
  const expectationsConfig = {
    decomposition: true,
    simpleRepetition: true
  }
  const expectationMock = (e) => expectationStringMock // jshint ignore: line
  const idsToExpectationsMock = (/* intl */) => ({
    decomposition: expectationMock,
    simpleRepetition: expectationMock,
    conditionalAlternative: expectationMock
  })

  let challengeMock

  hooks.beforeEach(function () {
    challengeExpectations = this.owner.lookup('service:challenge-expectations');
    challengeExpectations.set('idsToExpectations', idsToExpectationsMock)
    challengeMock = createComponentMock({
      expectations: expectationsConfig
    })
  });

  test('an expectation id should not be applied if its value is falsy', function (assert) {
    assert.notOk(challengeExpectations.shouldBeApplied([decompositionKey, false]))
  })

  test('an invalid expectation id should not be applied, regardless of its value', function (assert) {
    assert.notOk(challengeExpectations.shouldBeApplied(['randomID', true]))
  })

  test('an expectation id should be applied if it is valid and its value is truthy', function (assert) {
    assert.ok(challengeExpectations.shouldBeApplied([decompositionKey, true]))
  })

  test('merged expectations for a single expectation configuration', function (assert) {
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig]), expectationsConfig)
  })

  test('merged expectations for no expectations configuration should be an empty object', function (assert) {
    assert.propEqual(challengeExpectations.mergeConfigurations([]), {})
  })

  test('merged expectations for multiple configurations without keys in common', function (assert) {
    const conditionalAlternativeConfig = {
      conditionalAlternative: true
    }
    const mergedConfig = {
      decomposition: true,
      simpleRepetition: true,
      conditionalAlternative: true
    }
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig, conditionalAlternativeConfig]), mergedConfig)
  })

  test('merged expectations for multiple configurations with keys in common should prioritize values with higher priority', function (assert) {
    const configWithHigherPriority = {
      decomposition: false
    }
    const mergedConfig = {
      decomposition: false,
      simpleRepetition: true
    }
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig, configWithHigherPriority]), mergedConfig)
  })

  test('domain expectations to mulang expectations', function (assert) {
    assert.equal(challengeExpectations.configToExpectation(expectationsConfig)(), 'ExpectationMock\nExpectationMock')
  })

  test('multiple nonexistent expectations ids are transformed to a noExpectation', function (assert) {

    const nonexistenteEpectations = {
      foo: true,
      bar: false,
      baz: true
    }
    assert.equal(challengeExpectations.configToExpectation(nonexistenteEpectations)(), '')
  })

  test('if a challenge does not define expectations, noExpectation is applied', function (assert) {
    assert.equal(challengeExpectations.expectationFor(createComponentMock({}))(), '')
  })

  test('if a challenge defines expectations but does not belong to a group, chapter or book, its expectations should be applied', function (assert) {
    assert.equal(challengeExpectations.expectationFor(challengeMock)(), 'ExpectationMock\nExpectationMock')
  })

  test('expectations from book, chapter, group and challenge should be combined', function (assert) {
    const book = createComponentMock({
      expectations: {
        decomposition: true
      }
    })
    const chapter = createComponentMock({
      libro: book,
      expectations: {
        simpleRepetition: true
      }
    })
    const group = createComponentMock({
      capitulo: chapter
    })
    const challenge = createComponentMock({
      grupo: group,
      expectations: {
        decomposition: false
      }
    })
    assert.equal(challengeExpectations.expectationFor(challenge)(), 'ExpectationMock')
  })

});<commit_msg>fix tests(again)<commit_after>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { setUpTestLocale } from '../../helpers/utils';
import { createComponentMock } from '../../helpers/mocks';

module('Unit | Service | challenge-expectations', function (hooks) {
  setupTest(hooks);
  setUpTestLocale(hooks)

  var challengeExpectations
  const decompositionKey = 'decomposition'
  const expectationStringMock = 'ExpectationMock'
  const expectationsConfig = {
    decomposition: true,
    simpleRepetition: true
  }
  const expectationMock = (e) => expectationStringMock // jshint ignore: line
  const idsToExpectationsMock = (/* intl */) => ({
    decomposition: expectationMock,
    simpleRepetition: expectationMock,
    conditionalAlternative: expectationMock
  })

  let challengeMock

  hooks.beforeEach(function () {
    challengeExpectations = this.owner.lookup('service:challenge-expectations');
    challengeExpectations.set('idsToExpectations', idsToExpectationsMock)
    challengeMock = createComponentMock({
      expectations: expectationsConfig
    })
  });

  test('an expectation id should not be applied if its value is falsy', function (assert) {
    assert.notOk(challengeExpectations.shouldBeApplied([decompositionKey, false]))
  })

  test('an invalid expectation id should not be applied, regardless of its value', function (assert) {
    assert.notOk(challengeExpectations.shouldBeApplied(['randomID', true]))
  })

  test('an expectation id should be applied if it is valid and its value is truthy', function (assert) {
    assert.ok(challengeExpectations.shouldBeApplied([decompositionKey, true]))
  })

  test('merged expectations for a single expectation configuration', function (assert) {
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig]), expectationsConfig)
  })

  test('merged expectations for no expectations configuration should be an empty object', function (assert) {
    assert.propEqual(challengeExpectations.mergeConfigurations([]), {})
  })

  test('merged expectations for multiple configurations without keys in common', function (assert) {
    const conditionalAlternativeConfig = {
      conditionalAlternative: true
    }
    const mergedConfig = {
      decomposition: true,
      simpleRepetition: true,
      conditionalAlternative: true
    }
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig, conditionalAlternativeConfig]), mergedConfig)
  })

  test('merged expectations for multiple configurations with keys in common should prioritize values with higher priority', function (assert) {
    const configWithHigherPriority = {
      decomposition: false
    }
    const mergedConfig = {
      decomposition: false,
      simpleRepetition: true
    }
    assert.propEqual(challengeExpectations.mergeConfigurations([expectationsConfig, configWithHigherPriority]), mergedConfig)
  })

  test('domain expectations to mulang expectations', function (assert) {
    assert.equal(challengeExpectations.configToExpectation(expectationsConfig)(), 'ExpectationMock\nExpectationMock')
  })

  test('multiple nonexistent expectations ids are transformed to a noExpectation', function (assert) {

    const nonexistenteEpectations = {
      foo: true,
      bar: false,
      baz: true
    }
    assert.equal(challengeExpectations.configToExpectation(nonexistenteEpectations)(), '')
  })

  test('if a challenge does not define expectations, noExpectation is applied', function (assert) {
    assert.equal(challengeExpectations.expectationFor(createComponentMock({}))(), '')
  })

  test('if a challenge defines expectations but does not belong to a group, chapter or book, its expectations should be applied', function (assert) {
    assert.equal(challengeExpectations.expectationFor(challengeMock)(), 'ExpectationMock\nExpectationMock')
  })

  test('expectations from book, chapter, group and challenge should be combined', function (assert) {
    const book = createComponentMock({
      expectations: {
        decomposition: true
      }
    })
    const chapter = createComponentMock({
      libro: book,
      expectations: {
        simpleRepetition: true
      }
    })
    const group = createComponentMock({
      capitulo: chapter
    })
    const challenge = createComponentMock({
      grupo: group,
      expectations: {
        decomposition: false
      }
    })
    assert.equal(challengeExpectations.expectationFor(challenge)(), 'ExpectationMock')
  })

});<|endoftext|>


<commit_before>import { module, test } from 'qunit';
import EmberObject, { computed } from '@ember/object';

import bindDataTestAttributes from 'ember-test-selectors/utils/bind-data-test-attributes';

module('Unit | Utility | bind data test attributes');

test('it adds missing attributeBindings array', function(assert) {
  let Fixture = EmberObject.extend({
    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['data-test-from-invocation', 'data-test-from-factory']);
});

test('it adds to existing attributeBindings array', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: ['foo', 'bar'],

    foo: 1,
    bar: 2,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), ['foo', 'bar']);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['foo', 'bar', 'data-test-from-invocation', 'data-test-from-factory']);
});

test('it converts existing attributeBindings string to array', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: 'foo',

    foo: 1,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), 'foo');

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['foo', 'data-test-from-invocation', 'data-test-from-factory']);
});

test('it only adds data-test-* properties', function(assert) {
  let Fixture = EmberObject.extend({
    foo: 1,
    bar: 2,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    baz: 3,

    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['data-test-from-invocation', 'data-test-from-factory']);
});

test('it does not add a data-test property', function(assert) {
  let Fixture = EmberObject.extend({
    'data-test': 'foo',
  });
  let instance = Fixture.create();

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'), undefined);
});

test('it breaks if attributeBindings is a computed property', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: computed('prop', function() {
      return [this.get('prop')];
    }).readOnly(),

    foo: 5,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    prop: 'foo',

    'data-test-from-invocation': 'bar',
  });

  assert.throws(() => bindDataTestAttributes(instance));
});

test('it breaks if tagName is empty', function(assert) {
  let Fixture = EmberObject.extend({
    tagName: '',
    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.throws(() => bindDataTestAttributes(instance));
});
<commit_msg>Add test for #106<commit_after>import { module, test } from 'qunit';
import EmberObject, { computed } from '@ember/object';
import EmberMixin from '@ember/object/mixin';
import { dasherize } from '@ember/string';

import bindDataTestAttributes from 'ember-test-selectors/utils/bind-data-test-attributes';

module('Unit | Utility | bind data test attributes');

test('it adds missing attributeBindings array', function(assert) {
  let Fixture = EmberObject.extend({
    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['data-test-from-invocation', 'data-test-from-factory']);
});

test('it adds to existing attributeBindings array', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: ['foo', 'bar'],

    foo: 1,
    bar: 2,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), ['foo', 'bar']);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['foo', 'bar', 'data-test-from-invocation', 'data-test-from-factory']);
});

test('it converts existing attributeBindings string to array', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: 'foo',

    foo: 1,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), 'foo');

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['foo', 'data-test-from-invocation', 'data-test-from-factory']);
});

test('it only adds data-test-* properties', function(assert) {
  let Fixture = EmberObject.extend({
    foo: 1,
    bar: 2,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    baz: 3,

    'data-test-from-invocation': 'bar',
  });

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'),
    ['data-test-from-invocation', 'data-test-from-factory']);
});

test('it does not add a data-test property', function(assert) {
  let Fixture = EmberObject.extend({
    'data-test': 'foo',
  });
  let instance = Fixture.create();

  assert.deepEqual(instance.get('attributeBindings'), undefined);

  bindDataTestAttributes(instance);

  assert.deepEqual(instance.get('attributeBindings'), undefined);
});

test('it breaks if attributeBindings is a computed property', function(assert) {
  let Fixture = EmberObject.extend({
    attributeBindings: computed('prop', function() {
      return [this.get('prop')];
    }).readOnly(),

    foo: 5,

    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    prop: 'foo',

    'data-test-from-invocation': 'bar',
  });

  assert.throws(() => bindDataTestAttributes(instance));
});

test('it breaks if tagName is empty', function(assert) {
  let Fixture = EmberObject.extend({
    tagName: '',
    'data-test-from-factory': 'foo',
  });
  let instance = Fixture.create({
    'data-test-from-invocation': 'bar',
  });

  assert.throws(() => bindDataTestAttributes(instance));
});

test('issue #106', function(assert) {
  let Component = EmberObject.extend({});

  Component.reopen({
    init() {
      this._super(...arguments);
      bindDataTestAttributes(this);
    },
  });

  let Mixin = EmberMixin.create({
    init() {
      this._super(...arguments);

      if (this.tagName !== '') {
        let componentName = dasherize(this._XXXdebugContainerKey.replace(/\//g, '-').split(':')[1]);
        this.set('data-test-component', componentName);

        let dataTestAttr = ['data-test-component'];
        this.attributeBindings = this.attributeBindings ? this.attributeBindings.concat(dataTestAttr) : dataTestAttr;
      }
    },
  });

  Component.reopen(Mixin);

  let Fixture1 = Component.extend({
    _XXXdebugContainerKey: 'component:fixture1',
    tagName: 'span',
  });

  let fixture1 = Fixture1.create();

  assert.strictEqual(fixture1.get('data-test-component'), 'fixture1');

  let Fixture2 = Component.extend({
    _XXXdebugContainerKey: 'component:fixture2',
    tagName: '',
  });

  let fixture2 = Fixture2.create();

  assert.strictEqual(fixture2.get('data-test-component'), undefined);
});

<|endoftext|>