@@ -19,6 +19,7 @@ import (
1919 "io/ioutil"
2020 "os"
2121 "path/filepath"
22+ "regexp"
2223 "strings"
2324
2425 "github.com/arduino/arduino-cli/arduino/globals"
@@ -27,6 +28,17 @@ import (
2728 "github.com/pkg/errors"
2829)
2930
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+
3042// SaveSketchItemCpp saves a preprocessed .cpp sketch file on disk
3143func SaveSketchItemCpp (item * sketch.Item , buildPath string ) error {
3244
@@ -120,3 +132,26 @@ func LoadSketch(sketchPath, buildPath string) (*sketch.Sketch, error) {
120132
121133 return sketch .New (sketchFolder , mainSketchFile , buildPath , files )
122134}
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