Skip to content

Commit edc63f8

Browse files
authoredJan 11, 2022
[breaking] legacy: refactoring of the old i18n.Logger (#1621)
* LoggerToCustomStreams must have pointer receiver Becuase it has a mutex field that otherwise is copied. * Removed barely used legacy i18n.Logger.UnformattedFprintln function * Removed barely used legacy i18n.Logger.UnformattedWrite function * Removed unused AccumulatorLogger * Added 'percent' to TaskProgress gRPC message * Added gRPC placeholders to report compile progress * legacy: builder task progress is now transferred via TaskProgress callback * Removed unused Logger.Flush interface method * Removed Logger.Name method (use type-assertions instead) * Added note on breaking API change
1 parent 60c1c98 commit edc63f8

File tree

17 files changed

+148
-233
lines changed

17 files changed

+148
-233
lines changed
 

‎cli/compile/compile.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,9 +199,9 @@ func runCompileCommand(cmd *cobra.Command, args []string) {
199199
var compileRes *rpc.CompileResponse
200200
var compileError error
201201
if output.OutputFormat == "json" {
202-
compileRes, compileError = compile.Compile(context.Background(), compileRequest, compileStdOut, compileStdErr, verboseCompile)
202+
compileRes, compileError = compile.Compile(context.Background(), compileRequest, compileStdOut, compileStdErr, nil, verboseCompile)
203203
} else {
204-
compileRes, compileError = compile.Compile(context.Background(), compileRequest, os.Stdout, os.Stderr, verboseCompile)
204+
compileRes, compileError = compile.Compile(context.Background(), compileRequest, os.Stdout, os.Stderr, nil, verboseCompile)
205205
}
206206

207207
if compileError == nil && uploadAfterCompile {

‎commands/compile/compile.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import (
4646
var tr = i18n.Tr
4747

4848
// Compile FIXMEDOC
49-
func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream io.Writer, debug bool) (r *rpc.CompileResponse, e error) {
49+
func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream io.Writer, progressCB commands.TaskProgressCB, debug bool) (r *rpc.CompileResponse, e error) {
5050

5151
// There is a binding between the export binaries setting and the CLI flag to explicitly set it,
5252
// since we want this binding to work also for the gRPC interface we must read it here in this
@@ -132,6 +132,7 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
132132
builderCtx.PackageManager = pm
133133
builderCtx.FQBN = fqbn
134134
builderCtx.SketchLocation = sk.FullPath
135+
builderCtx.ProgressCB = progressCB
135136

136137
// FIXME: This will be redundant when arduino-builder will be part of the cli
137138
builderCtx.HardwareDirs = configuration.HardwareDirectories(configuration.Settings)
@@ -206,7 +207,7 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream
206207

207208
builderCtx.ExecStdout = outStream
208209
builderCtx.ExecStderr = errStream
209-
builderCtx.SetLogger(legacyi18n.LoggerToCustomStreams{Stdout: outStream, Stderr: errStream})
210+
builderCtx.SetLogger(&legacyi18n.LoggerToCustomStreams{Stdout: outStream, Stderr: errStream})
210211
builderCtx.Clean = req.GetClean()
211212
builderCtx.OnlyUpdateCompilationDatabase = req.GetCreateCompilationDatabaseOnly()
212213

‎commands/daemon/daemon.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,7 @@ func (s *ArduinoCoreServerImpl) Compile(req *rpc.CompileRequest, stream rpc.Ardu
262262
stream.Context(), req,
263263
utils.FeedStreamTo(func(data []byte) { stream.Send(&rpc.CompileResponse{OutStream: data}) }),
264264
utils.FeedStreamTo(func(data []byte) { stream.Send(&rpc.CompileResponse{ErrStream: data}) }),
265+
func(p *rpc.TaskProgress) { stream.Send(&rpc.CompileResponse{Progress: p}) },
265266
false) // Set debug to false
266267
if err != nil {
267268
return convertErrorToRPCStatus(err)

‎docs/UPGRADING.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,23 @@ Here you can find a list of migration guides to handle breaking changes between
44

55
## Unreleased
66

7+
### `commands.Compile` function change
8+
9+
A new argument `progressCB` has been added to `commands.Compile`, the new function signature is:
10+
11+
```go
12+
func Compile(
13+
ctx context.Context,
14+
req *rpc.CompileRequest,
15+
outStream, errStream io.Writer,
16+
progressCB commands.TaskProgressCB,
17+
debug bool
18+
) (r *rpc.CompileResponse, e error) {
19+
```
20+
21+
if a callback function is provided the `Compile` command will call it periodically with progress reports with the
22+
percentage of compilation completed, otherwise, if the parameter is `nil`, no progress reports will be performed.
23+
724
### `github.com/arduino/arduino-cli/cli/arguments.ParseReferences` function change
825
926
The `parseArch` parameter was removed since it was unused and was always true. This means that the architecture gets

‎legacy/builder/builder.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323

2424
"github.com/arduino/arduino-cli/arduino/sketch"
2525
"github.com/arduino/arduino-cli/i18n"
26-
"github.com/arduino/arduino-cli/legacy/builder/builder_utils"
2726
"github.com/arduino/arduino-cli/legacy/builder/phases"
2827
"github.com/arduino/arduino-cli/legacy/builder/types"
2928
"github.com/arduino/arduino-cli/legacy/builder/utils"
@@ -195,7 +194,7 @@ func runCommands(ctx *types.Context, commands []types.Command) error {
195194
return errors.WithStack(err)
196195
}
197196
ctx.Progress.CompleteStep()
198-
builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx)
197+
ctx.PushProgress()
199198
}
200199
return nil
201200
}

‎legacy/builder/builder_utils/utils.go

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import (
2020
"os/exec"
2121
"path/filepath"
2222
"runtime"
23-
"strconv"
2423
"strings"
2524
"sync"
2625

@@ -35,18 +34,6 @@ import (
3534

3635
var tr = i18n.Tr
3736

38-
func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) {
39-
40-
if !ctx.Progress.PrintEnabled {
41-
return
42-
}
43-
44-
log := ctx.GetLogger()
45-
if log.Name() == "machine" {
46-
log.Println(constants.LOG_LEVEL_INFO, tr("Progress {0}"), strconv.FormatFloat(float64(ctx.Progress.Progress), 'f', 2, 32))
47-
}
48-
}
49-
5037
func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) {
5138
objectFiles, err := CompileFiles(ctx, sourcePath, false, buildPath, buildProperties, includes)
5239
if err != nil {
@@ -215,7 +202,7 @@ func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources
215202
queue <- source
216203

217204
ctx.Progress.CompleteStep()
218-
PrintProgressIfProgressEnabledAndMachineLogger(ctx)
205+
ctx.PushProgress()
219206
}
220207
close(queue)
221208
wg.Wait()

‎legacy/builder/container_setup.go

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import (
1919
"fmt"
2020

2121
sk "github.com/arduino/arduino-cli/arduino/sketch"
22-
"github.com/arduino/arduino-cli/legacy/builder/builder_utils"
2322
"github.com/arduino/arduino-cli/legacy/builder/types"
2423
"github.com/pkg/errors"
2524
)
@@ -50,7 +49,7 @@ func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context)
5049
return errors.WithStack(err)
5150
}
5251
ctx.Progress.CompleteStep()
53-
builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx)
52+
ctx.PushProgress()
5453
}
5554

5655
if ctx.SketchLocation != nil {
@@ -78,7 +77,7 @@ func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context)
7877
ctx.Sketch = sketch
7978
}
8079
ctx.Progress.CompleteStep()
81-
builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx)
80+
ctx.PushProgress()
8281

8382
commands = []types.Command{
8483
&SetupBuildProperties{},
@@ -94,7 +93,7 @@ func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context)
9493
return errors.WithStack(err)
9594
}
9695
ctx.Progress.CompleteStep()
97-
builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx)
96+
ctx.PushProgress()
9897
}
9998

10099
return nil

‎legacy/builder/i18n/errors.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
)
99

1010
func ErrorfWithLogger(logger Logger, format string, a ...interface{}) error {
11-
if logger.Name() == "machine" {
11+
if _, isMachineLogger := logger.(*MachineLogger); isMachineLogger {
1212
logger.Fprintln(os.Stderr, constants.LOG_LEVEL_ERROR, format, a...)
1313
return errors.New("")
1414
}

‎legacy/builder/i18n/i18n.go

Lines changed: 11 additions & 139 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,11 @@ import (
2626
"sync"
2727
)
2828

29-
var PLACEHOLDER = regexp.MustCompile("{(\\d)}")
29+
var PLACEHOLDER = regexp.MustCompile(`{(\d)}`)
3030

3131
type Logger interface {
3232
Fprintln(w io.Writer, level string, format string, a ...interface{})
33-
UnformattedFprintln(w io.Writer, s string)
34-
UnformattedWrite(w io.Writer, data []byte)
3533
Println(level string, format string, a ...interface{})
36-
Name() string
37-
Flush() string
3834
}
3935

4036
type LoggerToCustomStreams struct {
@@ -43,7 +39,7 @@ type LoggerToCustomStreams struct {
4339
mux sync.Mutex
4440
}
4541

46-
func (s LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
42+
func (s *LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
4743
s.mux.Lock()
4844
defer s.mux.Unlock()
4945
target := s.Stdout
@@ -53,165 +49,47 @@ func (s LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string
5349
fmt.Fprintln(target, Format(format, a...))
5450
}
5551

56-
func (s LoggerToCustomStreams) UnformattedFprintln(w io.Writer, str string) {
57-
s.mux.Lock()
58-
defer s.mux.Unlock()
59-
target := s.Stdout
60-
if w == os.Stderr {
61-
target = s.Stderr
62-
}
63-
fmt.Fprintln(target, str)
64-
}
65-
66-
func (s LoggerToCustomStreams) UnformattedWrite(w io.Writer, data []byte) {
67-
s.mux.Lock()
68-
defer s.mux.Unlock()
69-
target := s.Stdout
70-
if w == os.Stderr {
71-
target = s.Stderr
72-
}
73-
target.Write(data)
74-
}
75-
76-
func (s LoggerToCustomStreams) Println(level string, format string, a ...interface{}) {
52+
func (s *LoggerToCustomStreams) Println(level string, format string, a ...interface{}) {
7753
s.Fprintln(nil, level, format, a...)
7854
}
7955

80-
func (s LoggerToCustomStreams) Flush() string {
81-
return ""
82-
}
83-
84-
func (s LoggerToCustomStreams) Name() string {
85-
return "LoggerToCustomStreams"
86-
}
87-
8856
type NoopLogger struct{}
8957

90-
func (s NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {}
91-
92-
func (s NoopLogger) UnformattedFprintln(w io.Writer, str string) {}
58+
func (s *NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {}
9359

94-
func (s NoopLogger) UnformattedWrite(w io.Writer, data []byte) {}
95-
96-
func (s NoopLogger) Println(level string, format string, a ...interface{}) {}
97-
98-
func (s NoopLogger) Flush() string {
99-
return ""
100-
}
101-
102-
func (s NoopLogger) Name() string {
103-
return "noop"
104-
}
105-
106-
type AccumulatorLogger struct {
107-
Buffer *[]string
108-
}
109-
110-
func (s AccumulatorLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
111-
*s.Buffer = append(*s.Buffer, Format(format, a...))
112-
}
113-
114-
func (s AccumulatorLogger) UnformattedFprintln(w io.Writer, str string) {
115-
*s.Buffer = append(*s.Buffer, str)
116-
}
117-
118-
func (s AccumulatorLogger) UnformattedWrite(w io.Writer, data []byte) {
119-
*s.Buffer = append(*s.Buffer, string(data))
120-
}
121-
122-
func (s AccumulatorLogger) Println(level string, format string, a ...interface{}) {
123-
s.Fprintln(nil, level, format, a...)
124-
}
125-
126-
func (s AccumulatorLogger) Flush() string {
127-
str := strings.Join(*s.Buffer, "\n")
128-
*s.Buffer = (*s.Buffer)[0:0]
129-
return str
130-
}
131-
132-
func (s AccumulatorLogger) Name() string {
133-
return "accumulator"
134-
}
60+
func (s *NoopLogger) Println(level string, format string, a ...interface{}) {}
13561

13662
type HumanTagsLogger struct{}
13763

138-
func (s HumanTagsLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
64+
func (s *HumanTagsLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
13965
format = "[" + level + "] " + format
14066
fprintln(w, Format(format, a...))
14167
}
14268

143-
func (s HumanTagsLogger) Println(level string, format string, a ...interface{}) {
69+
func (s *HumanTagsLogger) Println(level string, format string, a ...interface{}) {
14470
s.Fprintln(os.Stdout, level, format, a...)
14571
}
14672

147-
func (s HumanTagsLogger) UnformattedFprintln(w io.Writer, str string) {
148-
fprintln(w, str)
149-
}
150-
151-
func (s HumanTagsLogger) UnformattedWrite(w io.Writer, data []byte) {
152-
write(w, data)
153-
}
154-
155-
func (s HumanTagsLogger) Flush() string {
156-
return ""
157-
}
158-
159-
func (s HumanTagsLogger) Name() string {
160-
return "humantags"
161-
}
162-
16373
type HumanLogger struct{}
16474

165-
func (s HumanLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
75+
func (s *HumanLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
16676
fprintln(w, Format(format, a...))
16777
}
16878

169-
func (s HumanLogger) Println(level string, format string, a ...interface{}) {
79+
func (s *HumanLogger) Println(level string, format string, a ...interface{}) {
17080
s.Fprintln(os.Stdout, level, format, a...)
17181
}
17282

173-
func (s HumanLogger) UnformattedFprintln(w io.Writer, str string) {
174-
fprintln(w, str)
175-
}
176-
177-
func (s HumanLogger) UnformattedWrite(w io.Writer, data []byte) {
178-
write(w, data)
179-
}
180-
181-
func (s HumanLogger) Flush() string {
182-
return ""
183-
}
184-
185-
func (s HumanLogger) Name() string {
186-
return "human"
187-
}
188-
18983
type MachineLogger struct{}
19084

191-
func (s MachineLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
85+
func (s *MachineLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {
19286
printMachineFormattedLogLine(w, level, format, a)
19387
}
19488

195-
func (s MachineLogger) Println(level string, format string, a ...interface{}) {
89+
func (s *MachineLogger) Println(level string, format string, a ...interface{}) {
19690
printMachineFormattedLogLine(os.Stdout, level, format, a)
19791
}
19892

199-
func (s MachineLogger) UnformattedFprintln(w io.Writer, str string) {
200-
fprintln(w, str)
201-
}
202-
203-
func (s MachineLogger) Flush() string {
204-
return ""
205-
}
206-
207-
func (s MachineLogger) Name() string {
208-
return "machine"
209-
}
210-
211-
func (s MachineLogger) UnformattedWrite(w io.Writer, data []byte) {
212-
write(w, data)
213-
}
214-
21593
func printMachineFormattedLogLine(w io.Writer, level string, format string, a []interface{}) {
21694
a = append([]interface{}(nil), a...)
21795
for idx, value := range a {
@@ -232,12 +110,6 @@ func fprintln(w io.Writer, s string) {
232110
fmt.Fprintln(w, s)
233111
}
234112

235-
func write(w io.Writer, data []byte) {
236-
lock.Lock()
237-
defer lock.Unlock()
238-
w.Write(data)
239-
}
240-
241113
func fprintf(w io.Writer, format string, a ...interface{}) {
242114
lock.Lock()
243115
defer lock.Unlock()

‎legacy/builder/phases/libraries_builder.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *p
123123
objectFiles.AddAll(libraryObjectFiles)
124124

125125
ctx.Progress.CompleteStep()
126-
builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx)
126+
ctx.PushProgress()
127127
}
128128

129129
return objectFiles, nil

‎legacy/builder/test/i18n_test.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@ package test
1717

1818
import (
1919
"fmt"
20+
"testing"
21+
2022
"github.com/arduino/arduino-cli/legacy/builder/constants"
2123
"github.com/arduino/arduino-cli/legacy/builder/i18n"
2224
"github.com/stretchr/testify/require"
23-
"testing"
2425
)
2526

2627
func TestI18NSyntax(t *testing.T) {
@@ -50,9 +51,9 @@ func TestI18NSyntax(t *testing.T) {
5051

5152
func TestI18NInheritance(t *testing.T) {
5253
var logger i18n.Logger
53-
logger = i18n.HumanLogger{}
54+
logger = &i18n.HumanLogger{}
5455
logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!")
5556

56-
logger = i18n.MachineLogger{}
57+
logger = &i18n.MachineLogger{}
5758
logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!")
5859
}

‎legacy/builder/types/context.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,17 +26,17 @@ import (
2626
"github.com/arduino/arduino-cli/arduino/libraries/librariesmanager"
2727
"github.com/arduino/arduino-cli/arduino/libraries/librariesresolver"
2828
"github.com/arduino/arduino-cli/arduino/sketch"
29+
"github.com/arduino/arduino-cli/commands"
2930
"github.com/arduino/arduino-cli/legacy/builder/i18n"
3031
rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1"
3132
paths "github.com/arduino/go-paths-helper"
3233
properties "github.com/arduino/go-properties-orderedmap"
3334
)
3435

3536
type ProgressStruct struct {
36-
PrintEnabled bool
37-
Progress float32
38-
StepAmount float32
39-
Parent *ProgressStruct
37+
Progress float32
38+
StepAmount float32
39+
Parent *ProgressStruct
4040
}
4141

4242
func (p *ProgressStruct) AddSubSteps(steps int) {
@@ -144,6 +144,8 @@ type Context struct {
144144

145145
// Dry run, only create progress map
146146
Progress ProgressStruct
147+
// Send progress events to this callback
148+
ProgressCB commands.TaskProgressCB
147149

148150
// Contents of a custom build properties file (line by line)
149151
CustomBuildProperties []string
@@ -254,3 +256,9 @@ func (ctx *Context) GetLogger() i18n.Logger {
254256
func (ctx *Context) SetLogger(l i18n.Logger) {
255257
ctx.logger = l
256258
}
259+
260+
func (ctx *Context) PushProgress() {
261+
if ctx.ProgressCB != nil {
262+
ctx.ProgressCB(&rpc.TaskProgress{Percent: ctx.Progress.Progress})
263+
}
264+
}

‎legacy/builder/utils/utils.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int)
183183
}
184184

185185
if ctx.Verbose {
186-
ctx.GetLogger().UnformattedFprintln(os.Stdout, PrintableCommand(command.Args))
186+
ctx.GetLogger().Println("info", "{0}", PrintableCommand(command.Args))
187187
}
188188

189189
if stdout == Capture {

‎rpc/cc/arduino/cli/commands/v1/common.pb.go

Lines changed: 49 additions & 39 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rpc/cc/arduino/cli/commands/v1/common.proto

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ message TaskProgress {
4444
string message = 2;
4545
// Whether the task is complete.
4646
bool completed = 3;
47+
// Amount in percent of the task completion (optional)
48+
float percent = 4;
4749
}
4850

4951
message Programmer {

‎rpc/cc/arduino/cli/commands/v1/compile.pb.go

Lines changed: 35 additions & 19 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rpc/cc/arduino/cli/commands/v1/compile.proto

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,9 @@ message CompileRequest {
8383
}
8484

8585
message CompileResponse {
86-
// The output of the compilation process.
86+
// The output of the compilation process (stream)
8787
bytes out_stream = 1;
88-
// The error output of the compilation process.
88+
// The error output of the compilation process (stream)
8989
bytes err_stream = 2;
9090
// The compiler build path
9191
string build_path = 3;
@@ -97,6 +97,8 @@ message CompileResponse {
9797
PlatformReference board_platform = 6;
9898
// The platform used for the build (if referenced from the board platform)
9999
PlatformReference build_platform = 7;
100+
// Completions reports of the compilation process (stream)
101+
TaskProgress progress = 8;
100102
}
101103

102104
message ExecutableSectionSize {

0 commit comments

Comments
 (0)
Please sign in to comment.