Merging two bower.json files with similar attributes(合并两个 JSON files with similar attributes)

Merging two bower.json files with similar attributes (merging two JSON files with similar attributes)

我想合并两个 bower.json 文件。一个在我的项目本地,另一个在不同项目之间共享。我需要在 运行 bower 安装之前合并这两个文件。

请根据我的要求检查示例:

本地bower.json

{
    "name": "myLocalProject",
    "version": "0.0.1",
    "devDependencies": {
        "angular": "1.1.0"
    },
    "dependencies": {
       "components-font-awesome": "*"
    },
    "resolutions": {
        "angular": "1.3.15"
    }
}

并分享了 bower.json

{
    "name": "sharedBowerFile",
    "version": "0.0.3",
    "devDependencies": {
        "angular": "1.3.15",
        "angular-resource": "1.3.15"
    },
    "dependencies": {

    },
    "resolutions": {
        "angular": "1.3.15"
    }
}

和结果 bower.json 将替换本地 bower.json

{
        "name": "myLocalProject",           // unchanged
        "version": "0.0.1",                 // unchanged
        "devDependencies": {
            "angular": "1.3.15",             //version updated
            "angular-resource": "1.3.15"     // added to local
        },
        "dependencies": {
            "components-font-awesome": "*"   //stays the same in local
        },
        "resolutions": {
            "angular": "1.3.15"                 
        }
    }

我将为合并创建一个 Grunt 任务,因此我需要在 JavaScript 中进行合并。

好的,我自己写了函数:

var mergeJSON = function (local, shared) {
    var check = true;
    for(var i in shared ) {
        if(typeof(shared[i]) == 'object') {
            for(var j in shared[i]) {
                check =true;
                for (var z in local[i]) {
                    if(j == z){
                        check = false;
                            if( cmp(shared[i][j], local[i][j])>0 ) {
                            //For upgrading the version of dependencies from shared to local
                            grunt.log.writeln("Updating local " + j + " from " + local[i][j] + " to >" + shared[i][j]);
                            local[i][j] = shared[i][j];
                            }else if(cmp(shared[i][j], local[i][j])<0){
                                grunt.log.writeln(j + " in shared bower.json " + " is " + shared[i][j] + " and older than local version " + local[i][j]);

                            }
                    }
                }
                if(check){
                    //add the dependency if does not exist in local
                    local[i][j] = shared[i][j];
                    grunt.log.writeln("Added dependency: " + j + ": " + local[i][j] );
                }
            }
        }
    }
    return JSON.stringify(local,null,4);
};

和我的 Grunt 任务:

 grunt.task.registerTask('merge','A task to merge local and shared bower.json file', function(){

            var shared = grunt.file.readJSON("/path/to/sharedJSON");
            var local = grunt.file.readJSON("bower.json");
            grunt.file.write('bower.json',mergeJSON(local,shared));
    });

运行:

$ grunt merge