<commit_before>'use strict';

var chai = require('chai')
var expect = chai.expect;
var sinon = require('sinon'); chai.use(require('sinon-chai'));
var Class = require('../../lib/util/class');

describe('Class', function() {

  it('is an object', function() {
    expect(Class).to.be.instanceOf(Object);
  });

  it('is a function', function() {
    expect(Class).to.be.instanceOf(Function);
  });

  it('can be instantiated without being extended', function() {
    expect(Class.create()).to.exist;
  });

  it('creates classes that are themselves functions', function() {
    expect(Class.extend()).to.be.instanceOf(Function);
  });

  it('can be extended 1 time', function() {
    var Animal = Class.extend();
    var animal = Animal.create();
    expect(animal).to.be.instanceOf(Animal.__class__);
    expect(animal).to.be.instanceOf(Class.__class__);
  });

  it('can be extended 2 times', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var dog = Dog.create();
    expect(dog).to.be.instanceOf(Dog.__class__);
    expect(dog).to.be.instanceOf(Animal.__class__);
    expect(dog).to.be.instanceOf(Class.__class__);
  });

  it('can be extended 3 times', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var Havanese = Dog.extend();
    var milo = Havanese.create();
    expect(milo).to.be.instanceOf(Havanese.__class__);
    expect(milo).to.be.instanceOf(Dog.__class__);
    expect(milo).to.be.instanceOf(Animal.__class__);
    expect(milo).to.be.instanceOf(Class.__class__);
  });

  it('can call super', function() {
    var speak = sinon.stub().returns('speaking');
    var sup = function() { return this._super(); }
    var Animal = Class.extend({ speak: speak });
    var Dog = Animal.extend({ speak: sup });
    var Havanese = Dog.extend({ speak: sup });
    var milo = Havanese.create();
    expect(speak).to.not.have.been.called;
    expect(milo.speak()).to.eql('speaking');
    expect(speak).to.have.been.calledOnce;
  });

  it('can call super in class methods', function() {
    var species = sinon.stub().returns('animal');
    var sup = function() { return this._super(); }
    var Animal = Class.extend({}, { species: species });
    var Dog = Animal.extend({}, { species: sup });
    var Havanese = Dog.extend({}, { species: sup });
    expect(species).to.not.have.been.called;
    expect(Havanese.species()).to.eql('animal');
    expect(species).to.have.been.calledOnce;
  });

  it('can specify methods', function() {
    var Animal = Class.extend({
      speak: function() { return 'hi'; }
    });
    expect(Animal.create().speak()).to.eql('hi');
  });

  it('can specify an init method', function() {
    var Subclass = Class.extend({
      init: function() { this.initialized = true; }
    });
    var obj = Subclass.create();
    expect(obj.initialized).to.be.true;
  });

  it('calls init methods in proper sequence', function() {
    var sequence = 0;
    var Animal = Class.extend({
      init: function() { this.animal = sequence++; }
    });
    var Dog = Animal.extend({
      init: function() { this.dog = sequence++; }
    });
    var dog = Dog.create();
    expect(dog.animal).to.eql(0);
    expect(dog.dog).to.eql(1);
  });

  it('allows static methods to be accessed via sublcasses', function() {
    var Animal = Class.extend();
    var staticMember = {};
    Animal.reopenClass({
      staticMember: staticMember
    });
    expect(Animal.staticMember).to.eql(staticMember);
  });

  it('allows static methods to be accessed via sublcasses', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var staticMember = {};
    Animal.reopenClass({ staticMember: staticMember });
    expect(Dog.staticMember).to.eql(staticMember);
    expect(Animal.staticMember).to.eql(staticMember);
  });

  it('creates instances that know their identity (class)', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog.__identity__).to.eql(Dog);
  });

  it('creates instances that are an instance of its class', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog).to.be.an.instanceOf(Dog.__class__);
  });

  it('creates instances that know their metaclass', function() {
    // this will likely never be useful for external use, but is important
    // internally.
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog.__metaclass__).to.eql(Dog.__metaclass__);
  });

  it('knows its identity (class)', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    expect(Dog.__identity__).to.eql(Dog);
  });

  it('creates valid metaclass prototype chain', function() {
    // this will likely never be useful for external use, but is important
    // internally.
    var Animal = Class.extend({}, { __name__: 'Animal' });
    var Dog = Animal.extend({}, { __name__: 'Dog' });
    expect(Dog.__metaclass__.prototype).to.be.instanceOf(Animal.__metaclass__);
    expect(Dog.__metaclass__.prototype).to.be.instanceOf(Class.__metaclass__);
  });

  it('has descriptive instances', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({}, {
      __name__: 'Dog'
    });
    var dog = Dog.create();
    expect(dog.inspect()).to.eql('[Dog]');
    expect(dog.toString()).to.eql('[Dog]');
  });

  it('has descriptive classes', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({}, {
      __name__: 'Dog'
    });
    expect(Dog.inspect()).to.eql('[Dog Class]');
    expect(Dog.toString()).to.eql('[Dog Class]');
  });
});
<commit_msg>Whitespace.<commit_after>'use strict';

var chai = require('chai')
var expect = chai.expect;
var sinon = require('sinon'); chai.use(require('sinon-chai'));
var Class = require('../../lib/util/class');

describe('Class', function() {

  it('is an object', function() {
    expect(Class).to.be.instanceOf(Object);
  });

  it('is a function', function() {
    expect(Class).to.be.instanceOf(Function);
  });

  it('can be instantiated without being extended', function() {
    expect(Class.create()).to.exist;
  });

  it('creates classes that are themselves functions', function() {
    expect(Class.extend()).to.be.instanceOf(Function);
  });

  it('can be extended 1 time', function() {
    var Animal = Class.extend();
    var animal = Animal.create();
    expect(animal).to.be.instanceOf(Animal.__class__);
    expect(animal).to.be.instanceOf(Class.__class__);
  });

  it('can be extended 2 times', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var dog = Dog.create();
    expect(dog).to.be.instanceOf(Dog.__class__);
    expect(dog).to.be.instanceOf(Animal.__class__);
    expect(dog).to.be.instanceOf(Class.__class__);
  });

  it('can be extended 3 times', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var Havanese = Dog.extend();
    var milo = Havanese.create();
    expect(milo).to.be.instanceOf(Havanese.__class__);
    expect(milo).to.be.instanceOf(Dog.__class__);
    expect(milo).to.be.instanceOf(Animal.__class__);
    expect(milo).to.be.instanceOf(Class.__class__);
  });

  it('can call super', function() {
    var speak = sinon.stub().returns('speaking');
    var sup = function() { return this._super(); }
    var Animal = Class.extend({ speak: speak });
    var Dog = Animal.extend({ speak: sup });
    var Havanese = Dog.extend({ speak: sup });
    var milo = Havanese.create();
    expect(speak).to.not.have.been.called;
    expect(milo.speak()).to.eql('speaking');
    expect(speak).to.have.been.calledOnce;
  });

  it('can call super in class methods', function() {
    var species = sinon.stub().returns('animal');
    var sup = function() { return this._super(); }
    var Animal = Class.extend({}, { species: species });
    var Dog = Animal.extend({}, { species: sup });
    var Havanese = Dog.extend({}, { species: sup });
    expect(species).to.not.have.been.called;
    expect(Havanese.species()).to.eql('animal');
    expect(species).to.have.been.calledOnce;
  });

  it('can specify methods', function() {
    var Animal = Class.extend({
      speak: function() { return 'hi'; }
    });
    expect(Animal.create().speak()).to.eql('hi');
  });

  it('can specify an init method', function() {
    var Subclass = Class.extend({
      init: function() { this.initialized = true; }
    });
    var obj = Subclass.create();
    expect(obj.initialized).to.be.true;
  });

  it('calls init methods in proper sequence', function() {
    var sequence = 0;
    var Animal = Class.extend({
      init: function() { this.animal = sequence++; }
    });
    var Dog = Animal.extend({
      init: function() { this.dog = sequence++; }
    });
    var dog = Dog.create();
    expect(dog.animal).to.eql(0);
    expect(dog.dog).to.eql(1);
  });

  it('allows static methods to be accessed via sublcasses', function() {
    var Animal = Class.extend();
    var staticMember = {};
    Animal.reopenClass({
      staticMember: staticMember
    });
    expect(Animal.staticMember).to.eql(staticMember);
  });

  it('allows static methods to be accessed via sublcasses', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend();
    var staticMember = {};
    Animal.reopenClass({ staticMember: staticMember });
    expect(Dog.staticMember).to.eql(staticMember);
    expect(Animal.staticMember).to.eql(staticMember);
  });

  it('creates instances that know their identity (class)', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog.__identity__).to.eql(Dog);
  });

  it('creates instances that are an instance of its class', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog).to.be.an.instanceOf(Dog.__class__);
  });

  it('creates instances that know their metaclass', function() {
    // this will likely never be useful for external use, but is important
    // internally.
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    var dog = Dog.create();
    expect(dog.__metaclass__).to.eql(Dog.__metaclass__);
  });

  it('knows its identity (class)', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({});
    expect(Dog.__identity__).to.eql(Dog);
  });

  it('creates valid metaclass prototype chain', function() {
    // this will likely never be useful for external use, but is important
    // internally.
    var Animal = Class.extend({}, { __name__: 'Animal' });
    var Dog = Animal.extend({}, { __name__: 'Dog' });
    expect(Dog.__metaclass__.prototype).to.be.instanceOf(Animal.__metaclass__);
    expect(Dog.__metaclass__.prototype).to.be.instanceOf(Class.__metaclass__);
  });

  it('has descriptive instances', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({}, {
      __name__: 'Dog'
    });
    var dog = Dog.create();
    expect(dog.inspect()).to.eql('[Dog]');
    expect(dog.toString()).to.eql('[Dog]');
  });

  it('has descriptive classes', function() {
    var Animal = Class.extend();
    var Dog = Animal.extend({}, {
      __name__: 'Dog'
    });
    expect(Dog.inspect()).to.eql('[Dog Class]');
    expect(Dog.toString()).to.eql('[Dog Class]');
  });
});
<|endoftext|>


<commit_before>'use strict';

const mkdirp = require('../..').util.mkdirp;
const expect = require('chai').expect;
const fs = require('fs');
const os = require('os');
const path = require('path');
const {coroutine: co, promisify} = require('bluebird');

function deleteFolderRecursive(directoryToDelete) {
  let files;
  if (fs.existsSync(directoryToDelete)) {
    files = fs.readdirSync(directoryToDelete);
    files.map(file => {
      let curPath = path.join(directoryToDelete, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        deleteFolderRecursive(curPath);
      }
      else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(directoryToDelete);
  }
}

function* getNonexistentDirectory() {
  let dirIncrement = -1,
      dirName, stat;
  while (1) {
    dirIncrement++;
    dirName = path.join(os.tmpDir(), dirIncrement.toString());
    try {
      stat = fs.statSync(dirName);
    }
    catch (e) {
      yield dirName;
    }
  }
};

const baseDir = getNonexistentDirectory().next().value;

describe('Defiant utility mkdirp()', () => {
  describe('when invoked', () => {
    it('should create a directory if it does not exist', done => {
      co(function*() {
        let dirName = baseDir;
        let result = yield mkdirp(dirName);
        expect(result).to.be.true;
        done();
      })();
    });
    it('should create all parent directories needed, as required', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'createSubdirectories', 'foo', 'bar', 'baz');
        let result = yield mkdirp(dirName);
        expect(result).to.be.true;
        done();
      })();
    });
    it('should not return an error if the directory already exists', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'directoryExists');
        yield mkdirp(dirName);
        let result = yield mkdirp(dirName);
        expect(result).to.be.true;
        done();
      })();
    });
    it('should return an error if the directory cannot be created', done => {
      co(function*() {
        let dirName = '/../foo';
        yield mkdirp(dirName);
        let result = yield mkdirp(dirName);
        expect(result).to.not.be.true;
        done();
      })();
    });
    it('should return an error if a file exists with the same name as the directory', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'fileExists'),
            filePath = path.join(dirName, 'foo');
        yield mkdirp(dirName);
        fs.writeFileSync(filePath, '', {mode: 0o600});
        let result = yield mkdirp(filePath);
        expect(result).to.not.be.true;
        done();
      })();
    });
    it('should clean up after itself', done => {
      co(function*() {
        deleteFolderRecursive(baseDir);
        done();
      })();
    });
  });
});
<commit_msg>fixing mkdirp() test<commit_after>'use strict';

const mkdirp = require('../..').util.mkdirp;
const expect = require('chai').expect;
const fs = require('fs');
const os = require('os');
const path = require('path');
const {coroutine: co, promisify} = require('bluebird');

function deleteFolderRecursive(directoryToDelete) {
  let files;
  if (fs.existsSync(directoryToDelete)) {
    files = fs.readdirSync(directoryToDelete);
    files.map(file => {
      let curPath = path.join(directoryToDelete, file);
      if (fs.lstatSync(curPath).isDirectory()) {
        deleteFolderRecursive(curPath);
      }
      else {
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(directoryToDelete);
  }
}

function* getNonexistentDirectory() {
  let dirIncrement = -1,
      dirName, stat;
  while (1) {
    dirIncrement++;
    dirName = path.join(os.tmpDir(), dirIncrement.toString());
    try {
      stat = fs.statSync(dirName);
    }
    catch (e) {
      yield dirName;
    }
  }
};

const baseDir = getNonexistentDirectory().next().value;

describe('Defiant utility mkdirp()', () => {
  describe('when invoked', () => {
    it('should create a directory if it does not exist', done => {
      co(function*() {
        let dirName = baseDir;
        let result = yield mkdirp(dirName);
        expect(result).to.be.undefined;
        done();
      })();
    });
    it('should create all parent directories needed, as required', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'createSubdirectories', 'foo', 'bar', 'baz');
        let result = yield mkdirp(dirName);
        expect(result).to.be.undefined;
        done();
      })();
    });
    it('should not return an error if the directory already exists', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'directoryExists');
        yield mkdirp(dirName);
        let result = yield mkdirp(dirName);
        expect(result).to.be.undefined;
        done();
      })();
    });
    it('should return an error if the directory cannot be created', done => {
      co(function*() {
        let dirName = '/../foo';
        yield mkdirp(dirName);
        let result = yield mkdirp(dirName);
        expect(result).to.not.be.undefined;
        done();
      })();
    });
    it('should return an error if a file exists with the same name as the directory', done => {
      co(function*() {
        let dirName = path.join(baseDir, 'fileExists'),
            filePath = path.join(dirName, 'foo');
        yield mkdirp(dirName);
        fs.writeFileSync(filePath, '', {mode: 0o600});
        let result = yield mkdirp(filePath);
        expect(result).to.not.be.undefined;
        done();
      })();
    });
    it('should clean up after itself', done => {
      co(function*() {
        deleteFolderRecursive(baseDir);
        done();
      })();
    });
  });
});
<|endoftext|>


<commit_before>/* eslint-env node, mocha */
/* eslint-disable no-sync */
/* eslint-disable max-len */
'use strict';
const fs = require('fs');
const path = require('path');
const {strictEqual, deepStrictEqual, notDeepStrictEqual} = require('assert');
const {CLIEngine} = require('eslint');
const configs = require('..');
const {version} = require('../package.json');
const dirPackages = path.join(__dirname, '../packages');
const dirFixtures = path.join(__dirname, 'fixtures');

function testPackage(packageId, done){
	const {commonjs, esmodules, stage2, es2017, react} = configs[packageId];
	const babelParser = stage2;

	// Describes when it's expected to fail (e.g. `true` means always, `false` means never).
	const expected = {
		var: es2017,

		arrow_function_single_param_without_parens: !es2017,
		arrow_function_single_param_with_parens: true,
		arrow_function_multiple_params_without_type: !es2017,

		class_empty: !es2017,
		class_stage0_function_without_return_type: !es2017,
		class_stage0_function_with_return_type: !babelParser,

		class_stage2_instance_property_without_type: !babelParser,
		class_stage2_static_property_without_type: !babelParser,
		class_stage2_instance_property_with_type: !babelParser,
		class_stage2_static_property_with_type: !babelParser,

		class_stage2_instance_function_without_return_type: !babelParser,
		class_stage2_static_function_without_return_type: !babelParser,
		class_stage2_instance_arrow_without_return_type: !babelParser,
		class_stage2_static_arrow_without_return_type: !babelParser,
		class_stage2_instance_expression_without_return_type: !babelParser,
		class_stage2_static_expression_without_return_type: !babelParser,

		class_stage2_instance_function_with_return_type: !babelParser,
		class_stage2_static_function_with_return_type: !babelParser,
		class_stage2_instance_arrow_with_return_type: !babelParser,
		class_stage2_static_arrow_with_return_type: !babelParser,
		class_stage2_instance_expression_with_return_type: !babelParser,
		class_stage2_static_expression_with_return_type: !babelParser,

		class_stage2_instance_function_without_params_type: !babelParser,
		class_stage2_static_function_without_params_type: !babelParser,
		class_stage2_instance_arrow_without_params_type: !babelParser,
		class_stage2_static_arrow_without_params_type: !babelParser,
		class_stage2_instance_expression_without_params_type: !babelParser,
		class_stage2_static_expression_without_params_type: !babelParser,

		class_stage2_instance_function_with_params_type: !babelParser,
		class_stage2_static_function_with_params_type: !babelParser,
		class_stage2_instance_arrow_with_params_type: !babelParser,
		class_stage2_static_arrow_with_params_type: !babelParser,
		class_stage2_instance_expression_with_params_type: !babelParser,
		class_stage2_static_expression_with_params_type: !babelParser,

		class_stage2_instance_function_underscore_params_without_type: !babelParser,
		class_stage2_static_function_underscore_params_without_type: !babelParser,
		class_stage2_instance_arrow_underscore_params_without_type: !babelParser,
		class_stage2_static_arrow_underscore_params_without_type: !babelParser,
		class_stage2_instance_expression_underscore_params_without_type: !babelParser,
		class_stage2_static_expression_underscore_params_without_type: !babelParser,

		class_stage2_instance_function_underscore_params_with_type: !babelParser,
		class_stage2_static_function_underscore_params_with_type: !babelParser,
		class_stage2_instance_arrow_underscore_params_with_type: !babelParser,
		class_stage2_static_arrow_underscore_params_with_type: !babelParser,
		class_stage2_instance_expression_underscore_params_with_type: !babelParser,
		class_stage2_static_expression_underscore_params_with_type: !babelParser,

		line_80: false,
		line_120: false,
		line_140: true,

		without_env_node: true,
		with_env_node: false,

		without_env_browser: true,
		with_env_browser: false,

		without_env_mocha: true,
		with_env_mocha: false,

		commonjs: !commonjs,
		export_var: !esmodules,
		export_const: !esmodules,
		export_arrow: true,
		export_function: !esmodules,
		export_default_var: !esmodules,
		export_default_const: true,
		export_default_arrow: !esmodules,
		export_default_function: !esmodules,

		// @warning Cannot enable this test because it acts differently in CLI mode and in Node API mode:
		// https://github.com/zaggino/brackets-eslint/issues/51
		// promise: !es2017,

		react_jsx: !babelParser && !react,
		await: !es2017,

		quotes_property_inconsistent_single: true,
		quotes_property_consistent_single: false,
		quotes_property_backtick: true,
		quotes_property_single: false,
		quotes_backtick: !es2017,
		quotes_single: false,
		quotes_property_double: true,
		quotes_double: true,

		chained_two_methods_single_line: false,
		chained_two_methods_multiple_lines: false,
		chained_four_methods_single_line: false,
		chained_four_methods_multiple_lines: false,
		chained_six_methods_single_line: true,
		chained_six_methods_multiple_lines: false,

		this_root: true,
		this_function: false,
		this_arrow: true,
		this_class_constructor: !es2017,
		this_class_method: !es2017,
		this_class_static: !es2017, // @warning I'd rather `true`, but only checkJs catches that issue, not even "class-methods-use-this" rule

		padding_class_beginning_zero_lines: !es2017,
		padding_class_beginning_one_line: !es2017,
		padding_class_beginning_two_lines: !es2017, // @warning I'd rather `true`
		padding_class_end_zero_lines: !es2017,
		padding_class_end_one_line: !es2017, // @warning I'd rather `true`
		padding_class_end_two_lines: !es2017, // @warning I'd rather `true`

		padding_class_method_beginning_zero_lines: !es2017,
		padding_class_method_beginning_one_line: !es2017,
		padding_class_method_beginning_two_lines: !es2017, // @warning I'd rather `true`
		padding_class_method_end_zero_lines: !es2017,
		padding_class_method_end_one_line: !es2017, // @warning I'd rather `true`
		padding_class_method_end_two_lines: !es2017, // @warning I'd rather `true`

		padding_function_beginning_zero_lines: false,
		padding_function_beginning_one_line: false,
		padding_function_beginning_two_lines: false, // @warning I'd rather `true`
		padding_function_end_zero_lines: false,
		padding_function_end_one_line: false, // @warning I'd rather `true`
		padding_function_end_two_lines: false // @warning I'd rather `true`
	};

	const folder = path.join(dirPackages, packageId);
	fs.access(folder, fs.constants.R_OK, folderError => {
		strictEqual(folderError, null, 'Folder exists');

		let throws = false;
		let packageJson;
		try {
			packageJson = JSON.parse(
				fs.readFileSync(path.join(folder, 'package.json'), 'utf8')
			);
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'package.json can be read');
		strictEqual(typeof packageJson, 'object', 'packageJson is a JSON Object');
		strictEqual(packageJson.name, `@wildpeaks/${packageId}`, 'package.name');
		strictEqual(packageJson.main, 'settings.js', 'package.main');
		strictEqual(packageJson.version, version, 'package.version');

		throws = false;
		try {
			fs.readFileSync(path.join(folder, 'settings.js'), 'utf8');
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'settings.js can be read');

		throws = false;
		try {
			fs.readFileSync(path.join(folder, 'README.md'), 'utf8');
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'README.md can be read');

		throws = false;
		let settings;
		try {
			settings = require(`../packages/${packageId}`); // eslint-disable-line global-require
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'Package can be required');
		strictEqual(typeof settings, 'object', 'Package exports an Object');
		settings.useEslintrc = false;

		// Real configs need an Object, CLIEngine needs an Array.
		// @see https://github.com/eslint/eslint/issues/892
		// @see https://github.com/eslint/eslint/pull/6922
		// @see https://github.com/eslint/eslint/issues/7967
		if (typeof settings.globals === 'object'){
			settings.globals = Object.keys(settings.globals);
		}

		const cli = new CLIEngine(settings);
		const report = cli.executeOnFiles([dirFixtures]);
		const actual = {};
		report.results.forEach(result => {
			const rules = {};
			result.messages.forEach(message => {
				if (message.fatal){
					rules.fatal = message.message;
				} else {
					rules[message.ruleId] = message.message;
				}
			});
			const fixtureId = path.basename(result.filePath, '.js');
			actual[fixtureId] = rules;
		});

		for (const fixtureId in expected){
			const expectedError = expected[fixtureId];
			const actualError = actual[fixtureId];
			const rules = Object.keys(actualError);
			if (expectedError){
				notDeepStrictEqual(rules, [], `Fixture "${fixtureId}" should have errors`);
			} else {
				deepStrictEqual(rules, [], `Fixture "${fixtureId}" should pass`);
			}
		}

		done();
	});
}

describe('Packages', /* @this */ function(){
	this.slow(3000);
	this.timeout(5000);
	before(done => {
		fs.access(dirPackages, fs.constants.R_OK, err => {
			strictEqual(err, null, 'Folder "packages" exists');
			done();
		});
	});
	for (const id in configs){
		it(id, testPackage.bind(this, id));
	}
});
<commit_msg>Tests check the rules that fail, not merely that it fails/passes<commit_after>/* eslint-env node, mocha */
/* eslint-disable no-sync */
/* eslint-disable max-len */
/* eslint-disable no-nested-ternary */
'use strict';
const fs = require('fs');
const path = require('path');
const {strictEqual, deepStrictEqual} = require('assert');
const {CLIEngine} = require('eslint');
const configs = require('..');
const {version} = require('../package.json');
const dirPackages = path.join(__dirname, '../packages');
const dirFixtures = path.join(__dirname, 'fixtures');

function testPackage(packageId, done){
	const {commonjs, esmodules, stage2, es2017, react} = configs[packageId];
	const babelParser = stage2;

	// Describes when it's expected to fail (e.g. `true` means always, `false` means never).
	const expected = {
		var: es2017 ? ['no-var'] : [],

		arrow_function_single_param_without_parens: es2017 ? [] : ['fatal'],
		arrow_function_single_param_with_parens: es2017 ? ['arrow-parens'] : ['fatal'],
		arrow_function_multiple_params_without_type: es2017 ? [] : ['fatal'],

		class_empty: es2017 ? [] : ['fatal'],
		class_stage0_function_without_return_type: es2017 ? [] : ['fatal'],
		class_stage0_function_with_return_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_property_without_type: babelParser ? [] : ['fatal'],
		class_stage2_static_property_without_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_property_with_type: babelParser ? [] : ['fatal'],
		class_stage2_static_property_with_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_without_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_without_return_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_without_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_without_return_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_without_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_without_return_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_with_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_with_return_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_with_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_with_return_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_with_return_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_with_return_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_without_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_without_params_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_without_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_without_params_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_without_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_without_params_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_with_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_with_params_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_with_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_with_params_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_with_params_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_with_params_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_underscore_params_without_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_underscore_params_without_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_underscore_params_without_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_underscore_params_without_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_underscore_params_without_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_underscore_params_without_type: babelParser ? [] : ['fatal'],

		class_stage2_instance_function_underscore_params_with_type: babelParser ? [] : ['fatal'],
		class_stage2_static_function_underscore_params_with_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_arrow_underscore_params_with_type: babelParser ? [] : ['fatal'],
		class_stage2_static_arrow_underscore_params_with_type: babelParser ? [] : ['fatal'],
		class_stage2_instance_expression_underscore_params_with_type: babelParser ? [] : ['fatal'],
		class_stage2_static_expression_underscore_params_with_type: babelParser ? [] : ['fatal'],

		line_80: [],
		line_120: [],
		line_140: ['max-len'],

		without_env_node: ['no-undef'],
		with_env_node: [],

		without_env_browser: ['no-undef'],
		with_env_browser: [],

		without_env_mocha: ['no-undef'],
		with_env_mocha: [],

		commonjs: commonjs ? [] : ['no-undef'],
		export_var: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),
		export_const: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),
		export_arrow: ['fatal'],
		export_function: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),
		export_default_var: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),
		export_default_const: ['fatal'],
		export_default_arrow: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),
		export_default_function: esmodules ? [] : (stage2 ? ['no-restricted-syntax'] : ['fatal']),

		// @warning Cannot enable this test because it acts differently in CLI mode and in Node API mode:
		// https://github.com/zaggino/brackets-eslint/issues/51
		// promise: es2017 ? [] : ['no-undef'],

		react_jsx: (babelParser || react) ? [] : ['fatal'],
		await: es2017 ? [] : ['fatal'],

		quotes_property_inconsistent_single: ['quote-props'],
		quotes_property_consistent_single: [],
		quotes_property_backtick: ['fatal'],
		quotes_property_single: [],
		quotes_backtick: es2017 ? [] : ['fatal'],
		quotes_single: [],
		quotes_property_double: ['quotes'],
		quotes_double: ['quotes'],

		chained_two_methods_single_line: [],
		chained_two_methods_multiple_lines: [],
		chained_four_methods_single_line: [],
		chained_four_methods_multiple_lines: [],
		chained_six_methods_single_line: ['newline-per-chained-call'],
		chained_six_methods_multiple_lines: [],

		this_root: babelParser ? ['babel/no-invalid-this'] : ['no-invalid-this'],
		this_function: [],
		this_arrow: babelParser ? ['babel/no-invalid-this'] : (es2017 ? ['no-invalid-this'] : ['fatal']),
		this_class_constructor: es2017 ? [] : ['fatal'],
		this_class_method: es2017 ? [] : ['fatal'],
		this_class_static: es2017 ? [] : ['fatal'], // @warning I'd rather always an error, but only checkJs catches that issue, not even "class-methods-use-this" rule

		padding_class_beginning_zero_lines: es2017 ? [] : ['fatal'],
		padding_class_beginning_one_line: es2017 ? [] : ['fatal'],
		padding_class_beginning_two_lines: es2017 ? [] : ['fatal'], // @warning I'd rather always an error
		padding_class_end_zero_lines: es2017 ? [] : ['fatal'],
		padding_class_end_one_line: es2017 ? [] : ['fatal'], // @warning I'd rather always an error
		padding_class_end_two_lines: es2017 ? [] : ['fatal'], // @warning I'd rather always an error

		padding_class_method_beginning_zero_lines: es2017 ? [] : ['fatal'],
		padding_class_method_beginning_one_line: es2017 ? [] : ['fatal'],
		padding_class_method_beginning_two_lines: es2017 ? [] : ['fatal'], // @warning I'd rather always an error
		padding_class_method_end_zero_lines: es2017 ? [] : ['fatal'],
		padding_class_method_end_one_line: es2017 ? [] : ['fatal'], // @warning I'd rather always an error
		padding_class_method_end_two_lines: es2017 ? [] : ['fatal'], // @warning I'd rather always an error

		padding_function_beginning_zero_lines: [],
		padding_function_beginning_one_line: [],
		padding_function_beginning_two_lines: [], // @warning I'd rather always an error
		padding_function_end_zero_lines: [],
		padding_function_end_one_line: [], // @warning I'd rather always an error
		padding_function_end_two_lines: [] // @warning I'd rather always an error
	};

	const folder = path.join(dirPackages, packageId);
	fs.access(folder, fs.constants.R_OK, folderError => {
		strictEqual(folderError, null, 'Folder exists');

		let throws = false;
		let packageJson;
		try {
			packageJson = JSON.parse(
				fs.readFileSync(path.join(folder, 'package.json'), 'utf8')
			);
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'package.json can be read');
		strictEqual(typeof packageJson, 'object', 'packageJson is a JSON Object');
		strictEqual(packageJson.name, `@wildpeaks/${packageId}`, 'package.name');
		strictEqual(packageJson.main, 'settings.js', 'package.main');
		strictEqual(packageJson.version, version, 'package.version');

		throws = false;
		try {
			fs.readFileSync(path.join(folder, 'settings.js'), 'utf8');
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'settings.js can be read');

		throws = false;
		try {
			fs.readFileSync(path.join(folder, 'README.md'), 'utf8');
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'README.md can be read');

		throws = false;
		let settings;
		try {
			settings = require(`../packages/${packageId}`); // eslint-disable-line global-require
		} catch(e){
			throws = true;
		}
		strictEqual(throws, false, 'Package can be required');
		strictEqual(typeof settings, 'object', 'Package exports an Object');
		settings.useEslintrc = false;

		// Real configs need an Object, CLIEngine needs an Array.
		// @see https://github.com/eslint/eslint/issues/892
		// @see https://github.com/eslint/eslint/pull/6922
		// @see https://github.com/eslint/eslint/issues/7967
		if (typeof settings.globals === 'object'){
			settings.globals = Object.keys(settings.globals);
		}

		const cli = new CLIEngine(settings);
		const report = cli.executeOnFiles([dirFixtures]);
		const actual = {};
		report.results.forEach(result => {
			const rules = {};
			result.messages.forEach(message => {
				if (message.fatal){
					rules.fatal = message.message;
				} else {
					rules[message.ruleId] = message.message;
				}
			});
			const fixtureId = path.basename(result.filePath, '.js');
			actual[fixtureId] = rules;
		});

		for (const fixtureId in expected){
			const expectedError = expected[fixtureId].sort();
			const actualError = Object.keys(actual[fixtureId]).sort();
			if (expectedError.length > 0){
				deepStrictEqual(actualError, expectedError, `Fixture "${fixtureId}" should have errors`);
			} else {
				deepStrictEqual(actualError, [], `Fixture "${fixtureId}" should pass`);
			}
		}

		done();
	});
}

describe('Packages', /* @this */ function(){
	this.slow(3000);
	this.timeout(5000);
	before(done => {
		fs.access(dirPackages, fs.constants.R_OK, err => {
			strictEqual(err, null, 'Folder "packages" exists');
			done();
		});
	});
	for (const id in configs){
		it(id, testPackage.bind(this, id));
	}
});
<|endoftext|>


<commit_before>const Format = require('./utils/Format');
const ResponseParser = require('./utils/ResponseParser');
const Filter = require('./utils/Filter');

const ClientListMethod = require('./methods/ClientList');

class Channel
{
    /**
     * Construct the channel class.
     *
     * @param {Query} query
     * @param {string} data
     * @param {number} channelID
     */
    constructor(query, data, channelID) {
        this.query = query;
        this.raw = data;
        this.data = { cid: channelID };

        this.parse();
    }

    /**
     * Parse the raw channel info.
     */
    parse() {
        let attributes = ResponseParser.parseLine(this.raw);

        Object.keys(attributes).forEach(key => {
            this.data[key] = attributes[key];
        });
    }

    /**
     * Return the channel in object format.
     *
     * @returns {object}
     */
    getObject() {
        let properties = ['data', 'name', 'topic', 'description', 'neededTalkPower',
                          'defaultChannel', 'channelType', 'permanent', 'semiPermanent',
                          'temporary', 'spacer', 'spacerAlignment'];
        let data = {};

        properties.forEach(property => {
            data[property] = this[property];
        });

        return data;
    }

    /**
     * Get the channel's sub-channels.
     *
     * @param {array} channelList
     * @return {array}
     */
    subChannels(channelList) {
        return Filter.run(channelList, 'data', { cid: this.data.cid });
    }

    /**
     * Get the channel's clients.
     *
     * @param {array} clientList
     * @returns {array}
     */
    clients(clientList) {
        return Filter.run(clientList, 'data', { cid: this.data.cid });
    }

    /**
     * Get the channel's name.
     */
    get name() {
        return this.data.channel_name;
    }

    /**
     * Get the channel's topic.
     */
    get topic() {
        return this.data.channel_topic;
    }

    /**
     * Get the channel's description.
     */
    get description() {
        return this.data.channel_description;
    }

    /**
     * Get the channel's needed talk power.
     */
    get neededTalkPower() {
        return this.data.channel_needed_talk_power;
    }

    /**
     * Determine if the channel is the server's default channel.
     */
    get defaultChannel() {
        return this.data.channel_flag_default == 1;
    }

    /**
     * Determine channel type.
     *
     * 1: Permanent
     * 2: Semi-permanent
     * 3: Temporary
     */
    get channelType() {
        if (this.data.channel_flag_permanent == 1)
            return 1;

        if (this.data.channel_flag_semi_permanent == 1)
            return 2;

        return 3;
    }

    /**
     * Determine if the channel is permanent.
     */
    get permanent() {
        return this.channelType == 1;
    }

    /**
     * Determine if the channel is semi-permanent.
     */
    get semiPermanent() {
        return this.channelType == 2;
    }

    /**
     * Determine if the channel is temporary.
     */
    get temporary() {
        return this.channelType == 3;
    }

    /**
     * Determine if the channel is a spacer.
     */
    get spacer() {
        return this.permanent && this.data.pid == 0 && (/\[[^\]]*spacer[^\]]*\]/).test(this.name);
    }

    /**
     * Determine the spacer alignment.
     *
     * 0: Not a spacer
     * 1: Left
     * 2: Center
     * 3: Right
     * 4: Repeat
     */
    get spacerAlignment() {
        if (!this.spacer)
            return 0;

        let parse = this.name.match(/\[(.*)spacer.*\]/);

        switch (parse[1]) {
            case 'c':
                return 2;

            case 'r':
                return 3;

            case '*':
                return 4;

            default:
                return 1;
        }
    }
}

module.exports = Channel;
<commit_msg>Channel: added spacerName property<commit_after>const Format = require('./utils/Format');
const ResponseParser = require('./utils/ResponseParser');
const Filter = require('./utils/Filter');

const ClientListMethod = require('./methods/ClientList');

class Channel
{
    /**
     * Construct the channel class.
     *
     * @param {Query} query
     * @param {string} data
     * @param {number} channelID
     */
    constructor(query, data, channelID) {
        this.query = query;
        this.raw = data;
        this.data = { cid: channelID };

        this.parse();
    }

    /**
     * Parse the raw channel info.
     */
    parse() {
        let attributes = ResponseParser.parseLine(this.raw);

        Object.keys(attributes).forEach(key => {
            this.data[key] = attributes[key];
        });
    }

    /**
     * Return the channel in object format.
     *
     * @returns {object}
     */
    getObject() {
        let properties = ['data', 'name', 'topic', 'description', 'neededTalkPower',
                          'defaultChannel', 'channelType', 'permanent', 'semiPermanent',
                          'temporary', 'spacer', 'spacerAlignment', 'spacerName'];
        let data = {};

        properties.forEach(property => {
            data[property] = this[property];
        });

        return data;
    }

    /**
     * Get the channel's sub-channels.
     *
     * @param {array} channelList
     * @return {array}
     */
    subChannels(channelList) {
        return Filter.run(channelList, 'data', { cid: this.data.cid });
    }

    /**
     * Get the channel's clients.
     *
     * @param {array} clientList
     * @returns {array}
     */
    clients(clientList) {
        return Filter.run(clientList, 'data', { cid: this.data.cid });
    }

    /**
     * Get the channel's name.
     */
    get name() {
        return this.data.channel_name;
    }

    /**
     * Get the channel's topic.
     */
    get topic() {
        return this.data.channel_topic;
    }

    /**
     * Get the channel's description.
     */
    get description() {
        return this.data.channel_description;
    }

    /**
     * Get the channel's needed talk power.
     */
    get neededTalkPower() {
        return this.data.channel_needed_talk_power;
    }

    /**
     * Determine if the channel is the server's default channel.
     */
    get defaultChannel() {
        return this.data.channel_flag_default == 1;
    }

    /**
     * Determine channel type.
     *
     * 1: Permanent
     * 2: Semi-permanent
     * 3: Temporary
     */
    get channelType() {
        if (this.data.channel_flag_permanent == 1)
            return 1;

        if (this.data.channel_flag_semi_permanent == 1)
            return 2;

        return 3;
    }

    /**
     * Determine if the channel is permanent.
     */
    get permanent() {
        return this.channelType == 1;
    }

    /**
     * Determine if the channel is semi-permanent.
     */
    get semiPermanent() {
        return this.channelType == 2;
    }

    /**
     * Determine if the channel is temporary.
     */
    get temporary() {
        return this.channelType == 3;
    }

    /**
     * Determine if the channel is a spacer.
     */
    get spacer() {
        return this.permanent && this.data.pid == 0 && (/\[[^\]]*spacer[^\]]*\]/).test(this.name);
    }

    /**
     * Determine the spacer alignment.
     *
     * 0: Not a spacer
     * 1: Left
     * 2: Center
     * 3: Right
     * 4: Repeat
     */
    get spacerAlignment() {
        if (!this.spacer)
            return 0;

        let parse = this.name.match(/\[(.*)spacer.*\]/);

        switch (parse[1]) {
            case 'c':
                return 2;

            case 'r':
                return 3;

            case '*':
                return 4;

            default:
                return 1;
        }
    }

    /**
     * Get the spacer name after parsing.
     */
    get spacerName() {
        if (!this.spacer)
            return this.name;

        let cleanedName = this.name.substring(this.name.indexOf(']') + 1);
        if (this.spacerAlignment == 4)
            cleanedName = cleanedName.repeat(Math.floor(30 / cleanedName.length));

        return cleanedName;
    }
}

module.exports = Channel;
<|endoftext|>


<commit_before>import data from './tasks.json';
import fixture from 'can-fixture';
import DefineList from 'can-define/list/list';
import assign from 'object-assign';
import dev from 'can-util/js/dev/dev';

let index = 1000;

//a mock ajax service
fixture.delay = 200;
fixture({
    'GET /tasks' (params) {
        const perPage = params.data.perPage || 10;
        const page = params.data.page || 0;
        const sortInfo = params.data.sort;
        let totalItems = data.length;
        let tempData = new DefineList(data);

        //filter it
        if (params.data.filters && params.data.filters.length) {
            //lets just handle one filter for testing
            const f = params.data.filters[0];
            dev.warn('only the first filter is going to be used!');

            switch (f.operator) {
            case 'equals':
                tempData = tempData.filter((d) => {
                    //eslint-disable-next-line
                    return d[f.name] == f.value;
                });
                break;
            default:
                if (f.operator !== 'like') {
                    dev.warn(f.operator, 'operator not implemented in fixture, like will be used instead!');
                }
                tempData = tempData.filter((d) => {
                    return d[f.name].indexOf(f.value) !== -1;
                });
            }
            dev.warn('found ' + tempData.length + ' items after filtering');
            totalItems = tempData.length;
        }

        //sort it
        if (sortInfo && sortInfo.fieldName) {
            const field = sortInfo.fieldName;
            tempData = tempData.sort((a, b) => {
                return sortInfo.type === 'asc' ? (a[field] === b[field] ? 0 : a[field] > b[field] ? 1 : -1) : (a[field] === b[field] ? 0 : a[field] > b[field] ? -1 : 1);
            });
        }

        //pageinate it
        tempData = tempData.slice(page * perPage, (page + 1) * perPage);

        //return the serialized version
        return {
            data: tempData.serialize(),
            total: totalItems
        };
    },
    'POST /tasks' (params, response) {
        const newId = index++;
        const newObj = assign({
            id: newId
        }, params.data);
        data.push(newObj);
        response(data[data.length - 1]);
    },
    'GET /tasks/{id}' (params, response) {
        const items = data.filter((item) => {
            //eslint-disable-next-line eqeqeq
            return item.id == params.data.id;
        });
        if (!items.length) {
            response(404, 'Not Found');
            return null;
        }
        return items[0];
    },
    'PUT /tasks/{id}' (params, response) {
        let item = data.filter((i) => {
            //eslint-disable-next-line eqeqeq
            return i.id == params.data.id;
        });
        if (!item.length) {
            response(404, 'Not Found');
            return;
        }
        item = item[0];
        const idx = data.indexOf(item);
        if (idx !== -1) {
            data[idx] = assign(item, params.data);
            response(data);
        } else {
            response(404, 'Not Found');
        }
    },
    'DELETE /tasks/{id}' (params, response) {
        let item = data.filter((i) => {
            // eslint-disable-next-line eqeqeq
            return i.id == params.data.id;
        });
        if (!item.length) {
            response(404, 'Not Found');
            return;
        }
        item = item[0];
        const idx = data.indexOf(item);
        if (idx !== -1) {
            data.splice(data.indexOf(item), 1);
            response(data);
        } else {
            response(404, 'Not Found');
        }
    }
});
<commit_msg>TEST: add additional cases to fixture<commit_after>import data from './tasks.json';
import fixture from 'can-fixture';
import DefineList from 'can-define/list/list';
import assign from 'object-assign';
import dev from 'can-util/js/dev/dev';

let index = 1000;

//a mock ajax service
fixture.delay = 200;
fixture({
    'GET /tasks' (params) {
        const perPage = params.data.perPage || 10;
        const page = params.data.page || 0;
        const sortInfo = params.data.sort;
        let totalItems = data.length;
        let tempData = new DefineList(data);

        //filter it
        if (params.data.filters && params.data.filters.length) {
            //lets just handle one filter for testing
            dev.warn('only the first filter is going to be used!');
            const f = params.data.filters[0];
            const exclusions = [null, '', undefined];
            if (exclusions.indexOf(f.value === -1)) {
                switch (f.operator) {
                case 'equals':
                    tempData = tempData.filter((d) => {
                    //eslint-disable-next-line
                    return d[f.name] == f.value;
                    });
                    break;
                default:
                    if (f.operator !== 'like') {
                        dev.warn(f.operator, 'operator not implemented in fixture, like will be used instead!');
                    }
                    if (typeof f.value !== 'string') {
                        dev.warn('ignoring filter on non-string value');
                    } else {
                        tempData = tempData.filter((d) => {
                            return d[f.name].toUpperCase().indexOf(f.value.toUpperCase()) !== -1;
                        });
                    }
                }
                dev.warn('found ' + tempData.length + ' items after filtering');
                totalItems = tempData.length;
            }
        }

        //sort it
        if (sortInfo && sortInfo.fieldName) {
            const field = sortInfo.fieldName;
            tempData = tempData.sort((a, b) => {
                return sortInfo.type === 'asc' ? (a[field] === b[field] ? 0 : a[field] > b[field] ? 1 : -1) : (a[field] === b[field] ? 0 : a[field] > b[field] ? -1 : 1);
            });
        }

        //pageinate it
        tempData = tempData.slice(page * perPage, (page + 1) * perPage);

        //return the serialized version
        return {
            data: tempData.serialize(),
            total: totalItems
        };
    },
    'POST /tasks' (params, response) {
        const newId = index++;
        const newObj = assign({
            id: newId
        }, params.data);
        data.push(newObj);
        response(data[data.length - 1]);
    },
    'GET /tasks/{id}' (params, response) {
        const items = data.filter((item) => {
            //eslint-disable-next-line eqeqeq
            return item.id == params.data.id;
        });
        if (!items.length) {
            response(404, 'Not Found');
            return null;
        }
        return items[0];
    },
    'PUT /tasks/{id}' (params, response) {
        let item = data.filter((i) => {
            //eslint-disable-next-line eqeqeq
            return i.id == params.data.id;
        });
        if (!item.length) {
            response(404, 'Not Found');
            return;
        }
        item = item[0];
        const idx = data.indexOf(item);
        if (idx !== -1) {
            data[idx] = assign(item, params.data);
            response(data);
        } else {
            response(404, 'Not Found');
        }
    },
    'DELETE /tasks/{id}' (params, response) {
        let item = data.filter((i) => {
            // eslint-disable-next-line eqeqeq
            return i.id == params.data.id;
        });
        if (!item.length) {
            response(404, 'Not Found');
            return;
        }
        item = item[0];
        const idx = data.indexOf(item);
        if (idx !== -1) {
            data.splice(data.indexOf(item), 1);
            response(data);
        } else {
            response(404, 'Not Found');
        }
    }
});
<|endoftext|>


<commit_before>import chai from 'chai';
chai.should();
import sql from 'mssql';

import database from '../src/database';

describe("when retrieving a database object to perform queries", function() {
    it("it returns a mssql npm module when no config is supplied", () => {
        database().should.eql(sql);
    });
    it("it returns a mssql npm module when config.isUnitTest is undefined", () => {
        database({}).should.eql(sql);
    });
    it("it return a mssql npm module when config.isUnitTest is false", () => {
       database({isUnitTest: false}).should.eql(sql);
    });
    it("it returns a fakeDb when config.isUnitTest is true", () => {
        const fakeDb = {connect: () => {}};
        database({isUnitTest: true, fakeDb: fakeDb}).should.eql(fakeDb);
    });
});<commit_msg>improve test to cover when isUnitTest is false<commit_after>import chai from 'chai';
chai.should();
import sql from 'mssql';

import database from '../src/database';

describe("when retrieving a database object to perform queries", function() {
    it("it returns a mssql npm module when no config is supplied", () => {
        database().should.eql(sql);
    });
    it("it returns a mssql npm module when config.isUnitTest is undefined", () => {
        database({}).should.eql(sql);
    });
    it("it return a mssql npm module when config.isUnitTest is false", () => {
        const fakeDb = {connect: () => {}};
        database({isUnitTest: false, fakeDb: fakeDb}).should.eql(sql);
    });
    it("it returns a fakeDb when config.isUnitTest is true", () => {
        const fakeDb = {connect: () => {}};
        database({isUnitTest: true, fakeDb: fakeDb}).should.eql(fakeDb);
    });
});<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const constants = require('./generator-constants');

const ANGULAR_DIR = constants.ANGULAR_DIR;
const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;

module.exports = {
    cleanupOldFiles,
    cleanupOldServerFiles,
    upgradeFiles
};

/**
 * Removes files that where generated in previous JHipster versions and therefore
 * need to be removed.
 *
 * WARNING this only removes files created by the main generator. Each sub-generator
 * should clean-up its own files: see the `cleanup` method in entity/index.js for cleaning
 * up entities.
 *
 * @param {any} generator - reference to generator
 */
function cleanupOldFiles(generator) {
    if (generator.isJhipsterVersionLessThan('3.2.0')) {
        // removeFile and removeFolder methods should be called here for files and folders to cleanup
        generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`);
        generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`);
    }
    if (generator.isJhipsterVersionLessThan('5.0.0')) {
        generator.removeFile(`${ANGULAR_DIR}/app.route.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`);

        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`);
    }
    if (generator.isJhipsterVersionLessThan('5.8.0')) {
        generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`);
        generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`);
    }
    if (generator.isJhipsterVersionLessThan('6.3.0') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}account/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}core/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}home/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}layouts/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/shared-common.module.ts`);
    }

    if (generator.isJhipsterVersionLessThan('6.3.0') && generator.configOptions && generator.configOptions.clientFramework === 'react') {
        generator.removeFile('tslint.json');
    }

    if (generator.isJhipsterVersionLessThan('6.4.0') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}admin/admin.route.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/admin.module.ts`);
    }

    if (generator.isJhipsterVersionLessThan('6.6.1') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}core/language/language.helper.ts`);
    }
}

/**
 * Removes server files that where generated in previous JHipster versions and therefore
 * need to be removed.
 *
 * @param {any} generator - reference to generator
 * @param {string} javaDir - Java directory
 * @param {string} testDir - Java tests directory
 * @param {string} mainResourceDir - Main resources directory
 * @param {string} testResourceDir - Test resources directory
 */
function cleanupOldServerFiles(generator, javaDir, testDir, mainResourceDir, testResourceDir) {
    if (generator.isJhipsterVersionLessThan('3.5.0')) {
        generator.removeFile(`${javaDir}domain/util/JSR310DateTimeSerializer.java`);
        generator.removeFile(`${javaDir}domain/util/JSR310LocalDateDeserializer.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.6.0')) {
        generator.removeFile(`${javaDir}config/HerokuDatabaseConfiguration.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.10.0')) {
        generator.removeFile(`${javaDir}config/CloudMongoDbConfiguration.java`);
        generator.removeFile(`${javaDir}security/CustomAccessDeniedHandler.java`);
        generator.removeFile(`${javaDir}web/filter/CsrfCookieGeneratorFilter.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.11.0')) {
        generator.removeFile(`${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/active-link.directive.js`);
    }
    if (generator.isJhipsterVersionLessThan('3.12.0')) {
        generator.removeFile(`${javaDir}config/hazelcast/HazelcastCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/hazelcast/package-info.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.0.0')) {
        generator.removeFile(`${javaDir}async/ExceptionHandlingAsyncTaskExecutor.java`);
        generator.removeFile(`${javaDir}async/package-info.java`);
        generator.removeFile(`${javaDir}config/jHipsterProperties.java`);
        generator.removeFile(`${javaDir}config/LoadBalancedResourceDetails.java`);
        generator.removeFile(`${javaDir}config/ElasticSearchConfiguration.java`);
        generator.removeFile(`${javaDir}config/apidoc/package-info.java`);
        generator.removeFile(`${javaDir}config/apidoc/PageableParameterBuilderPlugin.java`);
        generator.removeFile(`${javaDir}config/apidoc/SwaggerConfiguration.java`);
        generator.removeFile(`${javaDir}config/jcache/SpringCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/jcache/SpringCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/liquibase/AsyncSpringLiquibase.java`);
        generator.removeFile(`${javaDir}config/liquibase/package-info.java`);
        generator.removeFile(`${javaDir}config/locale/AngularCookieLocaleResolver.java`);
        generator.removeFile(`${javaDir}config/locale/package-info.java`);
        generator.removeFile(`${javaDir}domain/util/FixedH2Dialect.java`);
        generator.removeFile(`${javaDir}domain/util/FixedPostgreSQL82Dialect`);
        generator.removeFile(`${javaDir}domain/util/JSR310DateConverters.java`);
        generator.removeFile(`${javaDir}domain/util/JSR310PersistenceConverters.java`);
        generator.removeFile(`${javaDir}security/AjaxAuthenticationFailureHandler.java`);
        generator.removeFile(`${javaDir}security/AjaxAuthenticationSuccessHandler.java`);
        generator.removeFile(`${javaDir}security/AjaxLogoutSuccessHandler.java`);
        generator.removeFile(`${javaDir}security/CustomPersistentRememberMeServices.java`);
        generator.removeFile(`${javaDir}security/Http401UnauthorizedEntryPoint.java`);
        generator.removeFile(`${javaDir}security/UserDetailsService.java`);
        generator.removeFile(`${javaDir}web/filter/CachingHttpHeadersFilter.java`);
        generator.removeFile(`${javaDir}web/filter/package-info.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.3.0')) {
        generator.removeFile(`${javaDir}gateway/ratelimiting/RateLimitingRepository.java`);
        generator.removeFile(`${javaDir}config/cassandra/CustomZonedDateTimeCodec.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.7.1')) {
        generator.removeFile(`${javaDir}web/rest/errors/ErrorVM.java`);
        generator.removeFile(`${javaDir}web/rest/errors/ParameterizedErrorVM.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.11.1')) {
        generator.removeFile(`${CLIENT_MAIN_SRC_DIR}app/app.main-aot.ts`);
    }
    if (generator.isJhipsterVersionLessThan('4.13.1')) {
        generator.config.delete('hibernateCache');
    }
    if (generator.isJhipsterVersionLessThan('5.0.0')) {
        generator.removeFile(`${javaDir}config/ThymeleafConfiguration.java`);
        generator.removeFile(`${javaDir}web/rest/ProfileInfoResource.java`);
        generator.removeFile(`${mainResourceDir}mails/activationEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/creationEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/passwordResetEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/socialRegistrationValidationEmail.html`);
        generator.removeFile(`${testResourceDir}mail/testEmail.html`);
        generator.removeFile(`${testDir}web/rest/ProfileInfoResourceIT.java`);
        generator.removeFile('gradle/mapstruct.gradle');
    }
    if (generator.isJhipsterVersionLessThan('5.2.2')) {
        generator.removeFile(`${javaDir}config/ElasticsearchConfiguration.java`);
        generator.removeFile('gradle/liquibase.gradle');

        if (generator.authenticationType === 'oauth2' && generator.applicationType === 'microservice') {
            generator.removeFolder(`${constants.DOCKER_DIR}realm-config`);
            generator.removeFile(`${constants.DOCKER_DIR}keycloak.yml`);
        }
    }
    if (generator.isJhipsterVersionLessThan('5.8.0')) {
        generator.removeFile(`${javaDir}config/MetricsConfiguration.java`);
        if (generator.databaseType === 'cassandra') {
            generator.removeFile(`${testResourceDir}cassandra-random-port.yml`);
        }
    }
    if (generator.isJhipsterVersionLessThan('6.0.0')) {
        generator.removeFile(`${javaDir}web/rest/errors/CustomParameterizedException.java`);
        generator.removeFile(`${javaDir}web/rest/errors/InternalServerErrorException.java`);
        generator.removeFile(`${javaDir}web/rest/util/PaginationUtil.java`);
        generator.removeFile(`${javaDir}web/rest/util/HeaderUtil.java`);
        generator.removeFile(`${testDir}web/rest/util/PaginationUtilUnitTest.java`);
        generator.removeFile(`${javaDir}web/rest/vm/LoggerVM.java`);
        generator.removeFile(`${javaDir}web/rest/LogsResource.java`);
        generator.removeFile(`${testDir}web/rest/LogsResourceIT.java`);
        generator.removeFile(`${javaDir}config/OAuth2Configuration.java`);
        generator.removeFile(`${javaDir}security/OAuth2AuthenticationSuccessHandler.java`);

        generator.removeFolder(`${CLIENT_MAIN_SRC_DIR}app/shared/layout/header/menus`);
        generator.removeFolder(`${CLIENT_TEST_SRC_DIR}spec/app/shared/layout/header/menus`);
    }
    if (generator.isJhipsterVersionLessThan('6.1.0')) {
        generator.config.delete('blueprint');
        generator.config.delete('blueprintVersion');
    }
    if (generator.isJhipsterVersionLessThan('6.5.2')) {
        generator.removeFile(`${testDir}service/mapper/UserMapperIT.java`);
        generator.removeFile(`${javaDir}service/${generator.upperFirstCamelCase(generator.baseName)}KafkaConsumer.java`);
        generator.removeFile(`${javaDir}service/${generator.upperFirstCamelCase(generator.baseName)}KafkaProducer.java`);
        generator.removeFile(`${testDir}web/rest/ClientForwardControllerIT.java`);
    }
    if (generator.isJhipsterVersionLessThan('6.6.1')) {
        generator.removeFile(`${javaDir}web/rest/errors/EmailNotFoundException.java`);
        generator.removeFile(`${javaDir}config/DefaultProfileUtil.java`);
        generator.removeFolder(`${javaDir}service/util`);
    }
}

/**
 * Upgrade files.
 *
 * @param {any} generator - reference to generator
 */
function upgradeFiles(generator) {
    let atLeastOneSuccess = false;
    if (generator.isJhipsterVersionLessThan('6.1.0')) {
        const langNameDiffer = function(lang) {
            const langProp = lang.replace(/-/g, '_');
            // Target file : change xx_yyyy_zz to xx_yyyy_ZZ to match java locales
            const langJavaProp = langProp.replace(/_[a-z]+$/g, lang => lang.toUpperCase());
            return langProp !== langJavaProp ? [langProp, langJavaProp] : undefined;
        };
        const languages = generator.config.get('languages');
        languages
            .map(langNameDiffer)
            .filter(props => props)
            .forEach(props => {
                const code = generator.renameFile(
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${props[0]}.properties`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${props[1]}.properties`
                );
                atLeastOneSuccess = atLeastOneSuccess || code;
            });
    }
    return atLeastOneSuccess;
}
<commit_msg>Remove tsconfig-aot when upgrading<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const constants = require('./generator-constants');

const ANGULAR_DIR = constants.ANGULAR_DIR;
const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;
const CLIENT_TEST_SRC_DIR = constants.CLIENT_TEST_SRC_DIR;
const SERVER_MAIN_RES_DIR = constants.SERVER_MAIN_RES_DIR;

module.exports = {
    cleanupOldFiles,
    cleanupOldServerFiles,
    upgradeFiles
};

/**
 * Removes files that where generated in previous JHipster versions and therefore
 * need to be removed.
 *
 * WARNING this only removes files created by the main generator. Each sub-generator
 * should clean-up its own files: see the `cleanup` method in entity/index.js for cleaning
 * up entities.
 *
 * @param {any} generator - reference to generator
 */
function cleanupOldFiles(generator) {
    if (generator.isJhipsterVersionLessThan('3.2.0')) {
        // removeFile and removeFolder methods should be called here for files and folders to cleanup
        generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`);
        generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`);
    }
    if (generator.isJhipsterVersionLessThan('5.0.0')) {
        generator.removeFile(`${ANGULAR_DIR}/app.route.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`);

        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`);
    }
    if (generator.isJhipsterVersionLessThan('5.8.0')) {
        generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`);
        generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`);
        generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`);
    }
    if (generator.isJhipsterVersionLessThan('6.3.0') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}account/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}core/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}home/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}layouts/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/index.ts`);
        generator.removeFile(`${ANGULAR_DIR}shared/shared-common.module.ts`);
    }

    if (generator.isJhipsterVersionLessThan('6.3.0') && generator.configOptions && generator.configOptions.clientFramework === 'react') {
        generator.removeFile('tslint.json');
    }

    if (generator.isJhipsterVersionLessThan('6.4.0') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}admin/admin.route.ts`);
        generator.removeFile(`${ANGULAR_DIR}admin/admin.module.ts`);
    }

    if (generator.isJhipsterVersionLessThan('6.6.1') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}core/language/language.helper.ts`);
    }

    if (generator.isJhipsterVersionLessThan('6.8.0') && generator.configOptions && generator.configOptions.clientFramework === 'angularX') {
        generator.removeFile(`${ANGULAR_DIR}tsconfig-aot.json`);
    }
}

/**
 * Removes server files that where generated in previous JHipster versions and therefore
 * need to be removed.
 *
 * @param {any} generator - reference to generator
 * @param {string} javaDir - Java directory
 * @param {string} testDir - Java tests directory
 * @param {string} mainResourceDir - Main resources directory
 * @param {string} testResourceDir - Test resources directory
 */
function cleanupOldServerFiles(generator, javaDir, testDir, mainResourceDir, testResourceDir) {
    if (generator.isJhipsterVersionLessThan('3.5.0')) {
        generator.removeFile(`${javaDir}domain/util/JSR310DateTimeSerializer.java`);
        generator.removeFile(`${javaDir}domain/util/JSR310LocalDateDeserializer.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.6.0')) {
        generator.removeFile(`${javaDir}config/HerokuDatabaseConfiguration.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.10.0')) {
        generator.removeFile(`${javaDir}config/CloudMongoDbConfiguration.java`);
        generator.removeFile(`${javaDir}security/CustomAccessDeniedHandler.java`);
        generator.removeFile(`${javaDir}web/filter/CsrfCookieGeneratorFilter.java`);
    }
    if (generator.isJhipsterVersionLessThan('3.11.0')) {
        generator.removeFile(`${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/active-link.directive.js`);
    }
    if (generator.isJhipsterVersionLessThan('3.12.0')) {
        generator.removeFile(`${javaDir}config/hazelcast/HazelcastCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/hazelcast/package-info.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.0.0')) {
        generator.removeFile(`${javaDir}async/ExceptionHandlingAsyncTaskExecutor.java`);
        generator.removeFile(`${javaDir}async/package-info.java`);
        generator.removeFile(`${javaDir}config/jHipsterProperties.java`);
        generator.removeFile(`${javaDir}config/LoadBalancedResourceDetails.java`);
        generator.removeFile(`${javaDir}config/ElasticSearchConfiguration.java`);
        generator.removeFile(`${javaDir}config/apidoc/package-info.java`);
        generator.removeFile(`${javaDir}config/apidoc/PageableParameterBuilderPlugin.java`);
        generator.removeFile(`${javaDir}config/apidoc/SwaggerConfiguration.java`);
        generator.removeFile(`${javaDir}config/jcache/SpringCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/jcache/SpringCacheRegionFactory.java`);
        generator.removeFile(`${javaDir}config/liquibase/AsyncSpringLiquibase.java`);
        generator.removeFile(`${javaDir}config/liquibase/package-info.java`);
        generator.removeFile(`${javaDir}config/locale/AngularCookieLocaleResolver.java`);
        generator.removeFile(`${javaDir}config/locale/package-info.java`);
        generator.removeFile(`${javaDir}domain/util/FixedH2Dialect.java`);
        generator.removeFile(`${javaDir}domain/util/FixedPostgreSQL82Dialect`);
        generator.removeFile(`${javaDir}domain/util/JSR310DateConverters.java`);
        generator.removeFile(`${javaDir}domain/util/JSR310PersistenceConverters.java`);
        generator.removeFile(`${javaDir}security/AjaxAuthenticationFailureHandler.java`);
        generator.removeFile(`${javaDir}security/AjaxAuthenticationSuccessHandler.java`);
        generator.removeFile(`${javaDir}security/AjaxLogoutSuccessHandler.java`);
        generator.removeFile(`${javaDir}security/CustomPersistentRememberMeServices.java`);
        generator.removeFile(`${javaDir}security/Http401UnauthorizedEntryPoint.java`);
        generator.removeFile(`${javaDir}security/UserDetailsService.java`);
        generator.removeFile(`${javaDir}web/filter/CachingHttpHeadersFilter.java`);
        generator.removeFile(`${javaDir}web/filter/package-info.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.3.0')) {
        generator.removeFile(`${javaDir}gateway/ratelimiting/RateLimitingRepository.java`);
        generator.removeFile(`${javaDir}config/cassandra/CustomZonedDateTimeCodec.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.7.1')) {
        generator.removeFile(`${javaDir}web/rest/errors/ErrorVM.java`);
        generator.removeFile(`${javaDir}web/rest/errors/ParameterizedErrorVM.java`);
    }
    if (generator.isJhipsterVersionLessThan('4.11.1')) {
        generator.removeFile(`${CLIENT_MAIN_SRC_DIR}app/app.main-aot.ts`);
    }
    if (generator.isJhipsterVersionLessThan('4.13.1')) {
        generator.config.delete('hibernateCache');
    }
    if (generator.isJhipsterVersionLessThan('5.0.0')) {
        generator.removeFile(`${javaDir}config/ThymeleafConfiguration.java`);
        generator.removeFile(`${javaDir}web/rest/ProfileInfoResource.java`);
        generator.removeFile(`${mainResourceDir}mails/activationEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/creationEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/passwordResetEmail.html`);
        generator.removeFile(`${mainResourceDir}mails/socialRegistrationValidationEmail.html`);
        generator.removeFile(`${testResourceDir}mail/testEmail.html`);
        generator.removeFile(`${testDir}web/rest/ProfileInfoResourceIT.java`);
        generator.removeFile('gradle/mapstruct.gradle');
    }
    if (generator.isJhipsterVersionLessThan('5.2.2')) {
        generator.removeFile(`${javaDir}config/ElasticsearchConfiguration.java`);
        generator.removeFile('gradle/liquibase.gradle');

        if (generator.authenticationType === 'oauth2' && generator.applicationType === 'microservice') {
            generator.removeFolder(`${constants.DOCKER_DIR}realm-config`);
            generator.removeFile(`${constants.DOCKER_DIR}keycloak.yml`);
        }
    }
    if (generator.isJhipsterVersionLessThan('5.8.0')) {
        generator.removeFile(`${javaDir}config/MetricsConfiguration.java`);
        if (generator.databaseType === 'cassandra') {
            generator.removeFile(`${testResourceDir}cassandra-random-port.yml`);
        }
    }
    if (generator.isJhipsterVersionLessThan('6.0.0')) {
        generator.removeFile(`${javaDir}web/rest/errors/CustomParameterizedException.java`);
        generator.removeFile(`${javaDir}web/rest/errors/InternalServerErrorException.java`);
        generator.removeFile(`${javaDir}web/rest/util/PaginationUtil.java`);
        generator.removeFile(`${javaDir}web/rest/util/HeaderUtil.java`);
        generator.removeFile(`${testDir}web/rest/util/PaginationUtilUnitTest.java`);
        generator.removeFile(`${javaDir}web/rest/vm/LoggerVM.java`);
        generator.removeFile(`${javaDir}web/rest/LogsResource.java`);
        generator.removeFile(`${testDir}web/rest/LogsResourceIT.java`);
        generator.removeFile(`${javaDir}config/OAuth2Configuration.java`);
        generator.removeFile(`${javaDir}security/OAuth2AuthenticationSuccessHandler.java`);

        generator.removeFolder(`${CLIENT_MAIN_SRC_DIR}app/shared/layout/header/menus`);
        generator.removeFolder(`${CLIENT_TEST_SRC_DIR}spec/app/shared/layout/header/menus`);
    }
    if (generator.isJhipsterVersionLessThan('6.1.0')) {
        generator.config.delete('blueprint');
        generator.config.delete('blueprintVersion');
    }
    if (generator.isJhipsterVersionLessThan('6.5.2')) {
        generator.removeFile(`${testDir}service/mapper/UserMapperIT.java`);
        generator.removeFile(`${javaDir}service/${generator.upperFirstCamelCase(generator.baseName)}KafkaConsumer.java`);
        generator.removeFile(`${javaDir}service/${generator.upperFirstCamelCase(generator.baseName)}KafkaProducer.java`);
        generator.removeFile(`${testDir}web/rest/ClientForwardControllerIT.java`);
    }
    if (generator.isJhipsterVersionLessThan('6.6.1')) {
        generator.removeFile(`${javaDir}web/rest/errors/EmailNotFoundException.java`);
        generator.removeFile(`${javaDir}config/DefaultProfileUtil.java`);
        generator.removeFolder(`${javaDir}service/util`);
    }
}

/**
 * Upgrade files.
 *
 * @param {any} generator - reference to generator
 */
function upgradeFiles(generator) {
    let atLeastOneSuccess = false;
    if (generator.isJhipsterVersionLessThan('6.1.0')) {
        const langNameDiffer = function(lang) {
            const langProp = lang.replace(/-/g, '_');
            // Target file : change xx_yyyy_zz to xx_yyyy_ZZ to match java locales
            const langJavaProp = langProp.replace(/_[a-z]+$/g, lang => lang.toUpperCase());
            return langProp !== langJavaProp ? [langProp, langJavaProp] : undefined;
        };
        const languages = generator.config.get('languages');
        languages
            .map(langNameDiffer)
            .filter(props => props)
            .forEach(props => {
                const code = generator.renameFile(
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${props[0]}.properties`,
                    `${SERVER_MAIN_RES_DIR}i18n/messages_${props[1]}.properties`
                );
                atLeastOneSuccess = atLeastOneSuccess || code;
            });
    }
    return atLeastOneSuccess;
}
<|endoftext|>