8000 [BREAKING] gRPC / golang Configuration API refactoring by cmaglie · Pull Request #2565 · arduino/arduino-cli · GitHub
[go: up one dir, main page]

Skip to content

[BREAKING] gRPC / 8000 golang Configuration API refactoring #2565

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 56 commits into from
May 15, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
8c07823
Moved a batch of function from commands/* subpackage to commands
cmaglie Mar 13, 2024
3d8f50a
Moved a batch of function from commands/* subpackage to commands (par…
cmaglie Mar 13, 2024
3ff8e09
Moved a batch of function from commands/* subpackage to commands (par…
cmaglie Mar 13, 2024
8615985
Moved a batch of function from commands/* subpackage to commands (par…
cmaglie Mar 13, 2024
61e5c46
Moved a batch of function from commands/* subpackage to commands (par…
cmaglie Mar 13, 2024
9e75b4d
Removed unused parameters
cmaglie Mar 13, 2024
f1a015c
Removed unused file
cmaglie Mar 13, 2024
c4ca852
Removed ToRPCStatus in favor of standardized GRPCStatus() interface
cmaglie Mar 13, 2024
23ccd43
Inlining methods in ArduinoCoreServiceImpl (part 1: BoardListAll)
cmaglie Mar 13, 2024
53f03e5
Inlining methods in ArduinoCoreServiceImpl (part 2: BoardDetails)
cmaglie Mar 13, 2024
0df2149
Inlining methods in ArduinoCoreServiceImpl (part 3: BoardList)
cmaglie Mar 13, 2024
f65eff2
Inlining methods in ArduinoCoreServiceImpl (part 4: BoardListWatch)
cmaglie Mar 14, 2024
06d6842
Inlining methods in ArduinoCoreServiceImpl (part 5: Create and Destroy)
cmaglie Mar 14, 2024
8bd0eef
Follow convetion where context must be the first argument
cmaglie Mar 14, 2024
a81069d
Inlining methods in ArduinoCoreServiceImpl (part 6: Init)
cmaglie Mar 14, 2024
917dcc5
Inlining methods in ArduinoCoreServiceImpl (part 7: UpdateIndex)
cmaglie Mar 14, 2024
bb815cf
Inlining methods in ArduinoCoreServiceImpl (part 8: Monitor)
cmaglie Mar 15, 2024 8000
0e434f2
Inlining methods in ArduinoCoreServiceImpl (part 9: Compile)
cmaglie Mar 18, 2024
12cf52e
Inlining methods in ArduinoCoreServiceImpl (part 10: PlatformInstall,…
cmaglie Mar 18, 2024
cfe4b27
Inlining methods in ArduinoCoreServiceImpl (part 11: LibraryDownload,…
cmaglie Mar 18, 2024
a3800fa
Inlining methods in ArduinoCoreServiceImpl (part 12: UpdateLibrariesI…
cmaglie Mar 18, 2024
738ad7c
Inlining methods in ArduinoCoreServiceImpl (part 13: NewSketch, LoadS…
cmaglie Mar 18, 2024
0442319
Inlining methods in ArduinoCoreServiceImpl (part 14: Upload, UploadUs…
cmaglie Mar 18, 2024
65ecbaf
Inlining methods in ArduinoCoreServiceImpl (part 15: SupportedUserFie…
cmaglie Mar 18, 2024
0bdc07a
Inlining methods in ArduinoCoreServiceImpl (part 16: CleanDownloadCac…
cmaglie Mar 25, 2024
3193b7c
Made utility functions private and put them in their own file
cmaglie Mar 18, 2024
c08c59e
Run tests forcing the english language
cmaglie Mar 20, 2024
e8e1574
Use correct env var to force configuration in integration test
cmaglie Apr 19, 2024
9bab3c5
Fixed markdown link
cmaglie Apr 19, 2024
6320f6e
Always use arduino-cli in user-agent string
cmaglie Apr 19, 2024
1fddba7
Removed global *viper.Viper settings instance
cmaglie Mar 20, 2024
4c50868
Implementation of Viper replacement library
cmaglie Apr 17, 2024
0453677
Use custom type to avoid context-values collisions
cmaglie Apr 22, 2024
61b66a7
Fixed test
cmaglie Apr 19, 2024
087a6f5
Fixed FindConfigFileInArgsFallbackOnEnv unit test
cmaglie Apr 19, 2024
9cd9c97
Fixed TestUserAgentHeader and TestProxy
cmaglie Apr 19, 2024
384c30c
Improved error message
cmaglie Apr 21, 2024
6aa742f
Config set adds only unique values
cmaglie Apr 21, 2024
0aafda3
Fixed initialization sequence for 'config init' command
cmaglie Apr 21, 2024
921fa61
Config search now looks into ARDUINO_DIRECTORIES_DATA env too
cmaglie Apr 21, 2024
ad8dbd9
Fixed all config* integration test
cmaglie Apr 21, 2024
4061131
Added missing type schema
cmaglie Apr 21, 2024
fa835de
Added docs
cmaglie Apr 23, 2024
72e05ee
Updated documentation about configuration file format
cmaglie Apr 29, 2024
89a79cb
Fixed a small imperfection in test
cmaglie Apr 30, 2024
240c8b3
Pass context in upload and burn-bootloader
cmaglie Apr 30, 2024
24ac040
Pass down context in all places where it's needed
cmaglie Apr 30, 2024
6cf4eb7
Removed unused parameter
cmaglie Apr 30, 2024
27e9c3e
Tolerate errors in invalid config files, and report them as warnings
cmaglie May 2, 2024
7658db6
Improved handling of incomplete configs array
cmaglie May 2, 2024
a58c350
Disable logging until it is setup in the arduino-cli pre-run
cmaglie May 6, 2024
9585728
Show config-load warning after feedback package initialization
cmaglie May 6, 2024
b279d4b
Fixed 'feedback' package initialization order
cmaglie May 6, 2024
278a331
Applied changes from code review
cmaglie May 6, 2024
c355478
Updated client_example
cmaglie May 6, 2024
cec1fdb
Improved array handling in configmap, and unit-tests
cmaglie May 6, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Inlining methods in ArduinoCoreServiceImpl (part 9: Compile)
  • Loading branch information
cmaglie committed May 6, 2024
commit 0e434f236743afb0599fd478785a46a0a2f9a7af
35 changes: 0 additions & 35 deletions commands/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,41 +76,6 @@ func (s *arduinoCoreServerImpl) SetSketchDefaults(ctx context.Context, req *rpc.
return SetSketchDefaults(ctx, req)
}

// Compile FIXMEDOC
func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.ArduinoCoreService_CompileServer) error {
syncSend := NewSynchronizedSend(stream.Send)
outStream := feedStreamTo(func(data []byte) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_OutStream{OutStream: data},
})
})
errStream := feedStreamTo(func(data []byte) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_ErrStream{ErrStream: data},
})
})
progressStream := func(p *rpc.TaskProgress) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_Progress{Progress: p},
})
}
compileRes, compileErr := Compile(stream.Context(), req, outStream, errStream, progressStream)
outStream.Close()
errStream.Close()
var compileRespSendErr error
if compileRes != nil {
compileRespSendErr = syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_Result{
Result: compileRes,
},
})
}
if compileErr != nil {
return compileErr
}
return compileRespSendErr
}

// PlatformInstall FIXMEDOC
func (s *arduinoCoreServerImpl) PlatformInstall(req *rpc.PlatformInstallRequest, stream rpc.ArduinoCoreService_PlatformInstallServer) error {
syncSend := NewSynchronizedSend(stream.Send)
Expand Down
120 changes: 83 additions & 37 deletions commands/service_compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,36 +38,62 @@ import (
"github.com/sirupsen/logrus"
)

// Compile FIXMEDOC
func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream io.Writer, progressCB rpc.TaskProgressCB) (r *rpc.BuilderResult, e error) {
// CompilerServerToStreams creates a gRPC CompileServer that sends the responses to the provided streams.
// The returned callback function can be used to retrieve the builder result after the compilation is done.
func CompilerServerToStreams(ctx context.Context, stdOut, stderr io.Writer) (server rpc.ArduinoCoreService_CompileServer, resultCB func() *rpc.BuilderResult) {
var builderResult *rpc.BuilderResult
stream := streamResponseToCallback(ctx, func(resp *rpc.CompileResponse) error {
if out := resp.GetOutStream(); len(out) > 0 {
if _, err := stdOut.Write(out); err != nil {
return err
}
}
if err := resp.GetErrStream(); len(err) > 0 {
if _, err := stderr.Write(err); err != nil {
return err
}
}
if result := resp.GetResult(); result != nil {
builderResult = result
}
return nil
})
return stream, func() *rpc.BuilderResult { return builderResult }
}

// Compile performs a compilation of a sketch.
func (s *arduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.ArduinoCoreService_CompileServer) error {
ctx := stream.Context()
syncSend := NewSynchronizedSend(stream.Send)

exportBinaries := configuration.Settings.GetBool("sketch.always_export_binaries")
if e := req.ExportBinaries; e != nil {
exportBinaries = *e
}

pme, release, err := instances.GetPackageManagerExplorer(req.GetInstance())
if err != nil {
return nil, err
return err
}
defer release()

if pme.Dirty() {
return nil, &cmderrors.InstanceNeedsReinitialization{}
return &cmderrors.InstanceNeedsReinitialization{}
}

lm, err := instances.GetLibraryManager(req.GetInstance())
if err != nil {
return nil, err
return err
}

logrus.Tracef("Compile %s for %s started", req.GetSketchPath(), req.GetFqbn())
if req.GetSketchPath() == "" {
return nil, &cmderrors.MissingSketchPathError{}
return &cmderrors.MissingSketchPathError{}
}
sketchPath := paths.New(req.GetSketchPath())
sk, err := sketch.New(sketchPath)
if err != nil {
return nil, &cmderrors.CantOpenSketchError{Cause: err}
return &cmderrors.CantOpenSketchError{Cause: err}
}

fqbnIn := req.GetFqbn()
Expand All @@ -79,25 +105,30 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
}
}
if fqbnIn == "" {
return nil, &cmderrors.MissingFQBNError{}
return &cmderrors.MissingFQBNError{}
}

fqbn, err := cores.ParseFQBN(fqbnIn)
if err != nil {
return nil, &cmderrors.InvalidFQBNError{Cause: err}
return &cmderrors.InvalidFQBNError{Cause: err}
}
_, targetPlatform, targetBoard, boardBuildProperties, buildPlatform, err := pme.ResolveFQBN(fqbn)
if err != nil {
if targetPlatform == nil {
return nil, &cmderrors.PlatformNotFoundError{
return &cmderrors.PlatformNotFoundError{
Platform: fmt.Sprintf("%s:%s", fqbn.Package, fqbn.PlatformArch),
Cause: fmt.Errorf(tr("platform not installed")),
}
}
return nil, &cmderrors.InvalidFQBNError{Cause: err}
return &cmderrors.InvalidFQBNError{Cause: err}
}

r = &rpc.BuilderResult{}
r := &rpc.BuilderResult{}
defer func() {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_Result{Result: r},
})
}()
r.BoardPlatform = targetPlatform.ToRPCPlatformReference()
r.BuildPlatform = buildPlatform.ToRPCPlatformReference()

Expand All @@ -120,7 +151,7 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
encryptProp := boardBuildProperties.ContainsKey("build.keys.encrypt_key")
// we verify that all the properties for the secure boot keys are defined or none of them is defined.
if !(keychainProp == signProp && signProp == encryptProp) {
return nil, fmt.Errorf(tr("Firmware encryption/signing requires all the following properties to be defined: %s", "build.keys.keychain, build.keys.sign_key, build.keys.encrypt_key"))
return fmt.Errorf(tr("Firmware encryption/signing requires all the following properties to be defined: %s", "build.keys.keychain, build.keys.sign_key, build.keys.encrypt_key"))
}

// Generate or retrieve build path
Expand All @@ -129,15 +160,15 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
buildPath = paths.New(req.GetBuildPath()).Canonical()
if in, _ := buildPath.IsInsideDir(sk.FullPath); in && buildPath.IsDir() {
if sk.AdditionalFiles, err = removeBuildFromSketchFiles(sk.AdditionalFiles, buildPath); err != nil {
return nil, err
return err
}
}
}
if buildPath == nil {
buildPath = sk.DefaultBuildPath()
}
if err = buildPath.MkdirAll(); err != nil {
return nil, &cmderrors.PermissionDeniedError{Message: tr("Cannot create build directory"), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Cannot create build directory"), Cause: err}
}
buildcache.New(buildPath.Parent()).GetOrCreate(buildPath.Base())
// cache is purged after compilation to not remove entries that might be required
Expand All @@ -149,16 +180,16 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
} else {
buildCachePath, err := paths.New(req.GetBuildCachePath()).Abs()
if err != nil {
return nil, &cmderrors.PermissionDeniedError{Message: tr("Cannot create build cache directory"), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Cannot create build cache directory"), Cause: err}
}
if err := buildCachePath.MkdirAll(); err != nil {
return nil, &cmderrors.PermissionDeniedError{Message: tr("Cannot create build cache directory"), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Cannot create build cache directory"), Cause: err}
}
coreBuildCachePath = buildCachePath.Join("core")
}

if _, err := pme.FindToolsRequiredForBuild(targetPlatform, buildPlatform); err != nil {
return nil, err
return err
}

actualPlatform := buildPlatform
Expand All @@ -170,7 +201,25 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
libsManager = lm
}

outStream := feedStreamTo(func(data []byte) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_OutStream{OutStream: data},
})
})
defer outStream.Close()
errStream := feedStreamTo(func(data []byte) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_ErrStream{ErrStream: data},
})
})
defer errStream.Close()
progressCB := func(p *rpc.TaskProgress) {
syncSend.Send(&rpc.CompileResponse{
Message: &rpc.CompileResponse_Progress{Progress: p},
})
}
sketchBuilder, err := builder.NewBuilder(
ctx,
sk,
boardBuildProperties,
buildPath,
Expand All @@ -195,14 +244,14 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
)
if err != nil {
if strings.Contains(err.Error(), "invalid build properties") {
return nil, &cmderrors.InvalidArgumentError{Message: tr("Invalid build properties"), Cause: err}
return &cmderrors.InvalidArgumentError{Message: tr("Invalid build properties"), Cause: err}
}
if errors.Is(err, builder.ErrSketchCannotBeLocatedInBuildPath) {
return r, &cmderrors.CompileFailedError{
return &cmderrors.CompileFailedError{
Message: tr("Sketch cannot be located in build path. Please specify a different build path"),
}
}
return r, &cmderrors.CompileFailedError{Message: err.Error()}
return &cmderrors.CompileFailedError{Message: err.Error()}
}

defer func() {
Expand Down Expand Up @@ -232,18 +281,18 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream

// Just get build properties and exit
if req.GetShowProperties() {
return r, nil
return nil
}

if req.GetPreprocess() {
// Just output preprocessed source code and exit
preprocessedSketch, err := sketchBuilder.Preprocess()
if err != nil {
err = &cmderrors.CompileFailedError{Message: err.Error()}
return r, err
return err
}
_, err = outStream.Write(preprocessedSketch)
return r, err
return err
}

defer func() {
Expand Down Expand Up @@ -285,7 +334,7 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
}

if err := sketchBuilder.Build(); err != nil {
return r, &cmderrors.CompileFailedError{Message: err.Error()}
return &cmderrors.CompileFailedError{Message: err.Error()}
}

// If the export directory is set we assume you want to export the binaries
Expand All @@ -297,9 +346,8 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
exportBinaries = false
}
if exportBinaries {
err := sketchBuilder.RunRecipe("recipe.hooks.savehex.presavehex", ".pattern", false)
if err != nil {
return r, err
if err := sketchBuilder.RunRecipe("recipe.hooks.savehex.presavehex", ".pattern", false); err != nil {
return err
}

exportPath := paths.New(req.GetExportDir())
Expand All @@ -313,38 +361,36 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
if !buildPath.EqualsTo(exportPath) {
logrus.WithField("path", exportPath).Trace("Saving sketch to export path.")
if err := exportPath.MkdirAll(); err != nil {
return r, &cmderrors.PermissionDeniedError{Message: tr("Error creating output dir"), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Error creating output dir"), Cause: err}
}

baseName, ok := sketchBuilder.GetBuildProperties().GetOk("build.project_name") // == "sketch.ino"
if !ok {
return r, &cmderrors.MissingPlatformPropertyError{Property: "build.project_name"}
return &cmderrors.MissingPlatformPropertyError{Property: "build.project_name"}
}
buildFiles, err := sketchBuilder.GetBuildPath().ReadDir()
if err != nil {
return r, &cmderrors.PermissionDeniedError{Message: tr("Error reading build directory"), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Error reading build directory"), Cause: err}
}
buildFiles.FilterPrefix(baseName)
for _, buildFile := range buildFiles {
exportedFile := exportPath.Join(buildFile.Base())
logrus.WithField("src", buildFile).WithField("dest", exportedFile).Trace("Copying artifact.")
if err = buildFile.CopyTo(exportedFile); err != nil {
return r, &cmderrors.PermissionDeniedError{Message: tr("Error copying output file %s", buildFile), Cause: err}
return &cmderrors.PermissionDeniedError{Message: tr("Error copying output file %s", buildFile), Cause: err}
}
}
}

err = sketchBuilder.RunRecipe("recipe.hooks.savehex.postsavehex", ".pattern", false)
if err != nil {
return r, err
if err = sketchBuilder.RunRecipe("recipe.hooks.savehex.postsavehex", ".pattern", false); err != nil {
return err
}
}

r.ExecutableSectionsSize = sketchBuilder.ExecutableSectionsSize().ToRPCExecutableSectionSizeArray()

logrus.Tracef("Compile %s for %s successful", sk.Name, fqbnIn)

return r, nil
return nil
}

// maybePurgeBuildCache runs the build files cache purge if the policy conditions are met.
Expand Down
2 changes: 2 additions & 0 deletions internal/arduino/builder/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
package builder

import (
"context"
"errors"
"fmt"
"io"
Expand Down Expand Up @@ -111,6 +112,7 @@ type buildArtifacts struct {

// NewBuilder creates a sketch Builder.
func NewBuilder(
ctx context.Context,
sk *sketch.Sketch,
boardBuildProperties *properties.Map,
buildPath *paths.Path,
Expand Down
4 changes: 3 additions & 1 deletion internal/cli/compile/compile.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,9 @@ func runCompileCommand(cmd *cobra.Command, args []string, srv rpc.ArduinoCoreSer
DoNotExpandBuildProperties: showProperties == arguments.ShowPropertiesUnexpanded,
Jobs: jobs,
}
builderRes, compileError := commands.Compile(context.Background(), compileRequest, stdOut, stdErr, nil)
server, builderResCB := commands.CompilerServerToStreams(ctx, stdOut, stdErr)
compileError := srv.Compile(compileRequest, server)
builderRes := builderResCB()

var uploadRes *rpc.UploadResult
if compileError == nil && uploadAfterCompile {
Expand Down
0