8
0
Просмотр исходного кода

Sorting dependencies when updating package.json file in development tasks.

Szymon Kupś 10 лет назад
Родитель
Сommit
61f1396c22

+ 1 - 0
dev/tasks/dev/tasks/create-package.js

@@ -90,6 +90,7 @@ module.exports = ( ckeditor5Path, workspaceRoot, writeln ) => {
 					json.dependencies = {};
 				}
 				json.dependencies[ packageName ] = gitHubUrl;
+				json.dependencies = tools.sortObject( json.dependencies );
 
 				return json;
 			} );

+ 1 - 0
dev/tasks/dev/tasks/install.js

@@ -101,6 +101,7 @@ module.exports = ( ckeditor5Path, workspaceRoot, name, writeln ) => {
 		tools.updateJSONFile( path.join( ckeditor5Path, 'package.json' ), ( json ) => {
 			json.dependencies = json.dependencies || {};
 			json.dependencies[ urlInfo.name ] = dependency;
+			json.dependencies = tools.sortObject( json.dependencies );
 
 			return json;
 		} );

+ 18 - 1
dev/tasks/dev/utils/tools.js

@@ -138,7 +138,24 @@ module.exports = {
 		let json = JSON.parse( contents );
 		json = updateFunction( json );
 
-		fs.writeFileSync( path, JSON.stringify( json, null, 2 ), 'utf-8' );
+		fs.writeFileSync( path, JSON.stringify( json, null, 2 ) + '\n', 'utf-8' );
+	},
+
+	/**
+	 * Reinserts all object's properties in alphabetical order (character's Unicode value).
+	 * Used for JSON.stringify method which takes keys in insertion order.
+	 *
+	 * @param { Object } obj
+	 * @returns { Object } Same object with sorted keys.
+	 */
+	sortObject( obj ) {
+		Object.keys( obj ).sort().forEach( key => {
+			const val = obj[ key ];
+			delete obj[ key ];
+			obj[ key ] = val;
+		} );
+
+		return obj;
 	},
 
 	/**

+ 18 - 1
dev/tests/dev/tools.js

@@ -243,7 +243,24 @@ describe( 'utils', () => {
 				expect( readFileStub.firstCall.args[ 0 ] ).to.equal( path );
 				expect( writeFileStub.calledOnce ).to.equal( true );
 				expect( writeFileStub.firstCall.args[ 0 ] ).to.equal( path );
-				expect( writeFileStub.firstCall.args[ 1 ] ).to.equal( JSON.stringify( modifiedJSON, null, 2 ) );
+				expect( writeFileStub.firstCall.args[ 1 ] ).to.equal( JSON.stringify( modifiedJSON, null, 2 ) + '\n' );
+			} );
+		} );
+
+		describe( 'sortObject', () => {
+			it( 'should be defined', () => expect( tools.sortObject ).to.be.a( 'function' ) );
+			it( 'should reinsert object properties in alphabetical order', () => {
+				let obj = {
+					c: '', d: '', a: '', z: ''
+				};
+
+				const sorted = {
+					a: '', c: '', d: '', z: ''
+				};
+
+				obj = tools.sortObject( obj );
+
+				expect( JSON.stringify( obj ) ).to.equal( JSON.stringify( sorted ) );
 			} );
 		} );