Merge multiple compile_command.json files

508 views Asked by At

Is there any lightweight method or VsCode extension to merge all compile_command.json files in different build folders in the whole workspace? If possible, I think it would be a convenient way for Clangd to configure intellisense.

Update:

Here is a hypothetical workspace

├── build
│   └── compile_command.json
├── compile_command.json
└── src
    ├── project_A
    │   └── build
    │       └── compile_command.json
    └── project_B
        └── build
            └── compile_command.json

, and usually workspaces aren't constructed in such a chaotic way. I want to merge all compile_command.json files, no matter the hierarchy, and output the combined file at the top directory in a simple way.

1

There are 1 answers

0
KKKmelody On BEST ANSWER

Referring to this answer and the comment by @starball,

jq -s add **/*.json > merged.json 

can search all .json files in the current and below paths and combine the output to merged.json, where

-s: The entire input is passed to the filter as a single long string;

add: The filter add takes as input an array, and produces as output the elements of the array added together;

**/*.json: The pattern **/*.json will therefore expand to the pathname of any file that has a filename suffix of .json anywhere in or below the current directory.

Finally, this command can be configured as a task for convenience in VsCode with

{
    "label": "Combine compile_commands.json",
    "type": "shell",
    "command":"jq -s add **/*.json > compile_commands.json",
    "options": {
        "cwd": "${workspaceFolder}"
    }
}

References:

  1. https://jqlang.github.io/jq/manual/#invoking-jq

  2. https://unix.stackexchange.com/a/457404