@@ -19,6 +19,7 @@ import (
1919 "encoding/json"
2020 "fmt"
2121 "os"
22+ "sync"
2223
2324 "github.com/arduino/arduino-cli/executils"
2425 "github.com/arduino/arduino-cli/i18n"
@@ -29,8 +30,9 @@ var tr = i18n.Tr
2930
3031// Database keeps track of all the compile commands run by the builder
3132type Database struct {
32- Contents []Command
33- File * paths.Path
33+ lock sync.Mutex
34+ contents []Command
35+ file * paths.Path
3436}
3537
3638// Command keeps track of a single run of a compile command
@@ -44,8 +46,8 @@ type Command struct {
4446// NewDatabase creates an empty CompilationDatabase
4547func NewDatabase (filename * paths.Path ) * Database {
4648 return & Database {
47- File : filename ,
48- Contents : []Command {},
49+ file : filename ,
50+ contents : []Command {},
4951 }
5052}
5153
@@ -56,16 +58,18 @@ func LoadDatabase(file *paths.Path) (*Database, error) {
5658 return nil , err
5759 }
5860 res := NewDatabase (file )
59- return res , json .Unmarshal (f , & res .Contents )
61+ return res , json .Unmarshal (f , & res .contents )
6062}
6163
6264// SaveToFile save the CompilationDatabase to file as a clangd-compatible compile_commands.json,
6365// see https://clang.llvm.org/docs/JSONCompilationDatabase.html
6466func (db * Database ) SaveToFile () {
65- if jsonContents , err := json .MarshalIndent (db .Contents , "" , " " ); err != nil {
67+ db .lock .Lock ()
68+ defer db .lock .Unlock ()
69+ if jsonContents , err := json .MarshalIndent (db .contents , "" , " " ); err != nil {
6670 fmt .Println (tr ("Error serializing compilation database: %s" , err ))
6771 return
68- } else if err := db .File .WriteFile (jsonContents ); err != nil {
72+ } else if err := db .file .WriteFile (jsonContents ); err != nil {
6973 fmt .Println (tr ("Error writing compilation database: %s" , err ))
7074 }
7175}
@@ -89,5 +93,7 @@ func (db *Database) Add(target *paths.Path, command *executils.Process) {
8993 File : target .String (),
9094 }
9195
92- db .Contents = append (db .Contents , entry )
96+ db .lock .Lock ()
97+ db .contents = append (db .contents , entry )
98+ db .lock .Unlock ()
9399}
0 commit comments