@@ -19,6 +19,7 @@ import (
19
19
"io/ioutil"
20
20
"os"
21
21
"path/filepath"
22
+ "regexp"
22
23
"strings"
23
24
24
25
"github.com/arduino/arduino-cli/arduino/globals"
@@ -27,6 +28,17 @@ import (
27
28
"github.com/pkg/errors"
28
29
)
29
30
31
+ var includesArduinoH = regexp .MustCompile (`^\s*#\s*include\s*[<\"]Arduino\.h[>\"]` )
32
+
33
+ // QuoteCppString returns the given string as a quoted string for use with the C
34
+ // preprocessor. This adds double quotes around it and escapes any
35
+ // double quotes and backslashes in the string.
36
+ func QuoteCppString (str string ) string {
37
+ str = strings .Replace (str , "\\ " , "\\ \\ " , - 1 )
38
+ str = strings .Replace (str , "\" " , "\\ \" " , - 1 )
39
+ return "\" " + str + "\" "
40
+ }
41
+
30
42
// SaveSketchItemCpp saves a preprocessed .cpp sketch file on disk
31
43
func SaveSketchItemCpp (item * sketch.Item , buildPath string ) error {
32
44
@@ -120,3 +132,26 @@ func LoadSketch(sketchPath, buildPath string) (*sketch.Sketch, error) {
120
132
121
133
return sketch .New (sketchFolder , mainSketchFile , buildPath , files )
122
134
}
135
+
136
+ // MergeSketchSources merges all the source files included in a sketch
137
+ func MergeSketchSources (sketch * sketch.Sketch ) (int , string ) {
138
+ lineOffset := 0
139
+ mergedSource := ""
140
+
141
+ // add Arduino.h inclusion directive if missing
142
+ if ! includesArduinoH .MatchString (sketch .MainFile .GetSourceStr ()) {
143
+ mergedSource += "#include <Arduino.h>\n "
144
+ lineOffset ++
145
+ }
146
+
147
+ mergedSource += "#line 1 " + QuoteCppString (sketch .MainFile .Path ) + "\n "
148
+ mergedSource += sketch .MainFile .GetSourceStr () + "\n "
149
+ lineOffset ++
150
+
151
+ for _ , item := range sketch .OtherSketchFiles {
152
+ mergedSource += "#line 1 " + QuoteCppString (item .Path ) + "\n "
153
+ mergedSource += item .GetSourceStr () + "\n "
154
+ }
155
+
156
+ return lineOffset , mergedSource
157
+ }
0 commit comments