Skip to content

Commit 6241da5

Browse files
committed
Added feedback functions to report warnings
1 parent 099850b commit 6241da5

File tree

9 files changed

+64
-49
lines changed

9 files changed

+64
-49
lines changed

cli/arguments/sketch.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
package arguments
1717

1818
import (
19+
"fmt"
20+
1921
"github.com/arduino/arduino-cli/arduino/sketch"
2022
"github.com/arduino/arduino-cli/cli/errorcodes"
2123
"github.com/arduino/arduino-cli/cli/feedback"
@@ -54,9 +56,10 @@ func NewSketch(sketchPath *paths.Path) *sketch.Sketch {
5456
func WarnDeprecatedFiles(sketchPath *paths.Path) {
5557
// .pde files are still supported but deprecated, this warning urges the user to rename them
5658
if files := sketch.CheckForPdeFiles(sketchPath); len(files) > 0 {
57-
feedback.Error(tr("Sketches with .pde extension are deprecated, please rename the following files to .ino:"))
59+
msg := tr("Sketches with .pde extension are deprecated, please rename the following files to .ino:")
5860
for _, f := range files {
59-
feedback.Error(f)
61+
msg += fmt.Sprintf("\n - %s", f)
6062
}
63+
feedback.Warning(msg)
6164
}
6265
}

cli/board/list.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,10 +69,10 @@ func runListCommand(cmd *cobra.Command, args []string) {
6969
Timeout: timeoutArg.Get().Milliseconds(),
7070
})
7171
if err != nil {
72-
feedback.Errorf(tr("Error detecting boards: %v"), err)
72+
feedback.Warning(tr("Error detecting boards: %v", err))
7373
}
7474
for _, err := range discvoeryErrors {
75-
feedback.Errorf(tr("Error starting discovery: %v"), err)
75+
feedback.Warning(tr("Error starting discovery: %v", err))
7676
}
7777
feedback.PrintResult(result{ports})
7878
}

cli/compile/compile.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -272,9 +272,10 @@ func runCompileCommand(cmd *cobra.Command, args []string) {
272272
libs += fmt.Sprintln(" - " + lib.GetName() + " (" + lib.GetVersion() + ")")
273273
}
274274
if hasVendoredLibs {
275-
fmt.Println()
276-
fmt.Println(tr("WARNING: The sketch is compiled using one or more custom libraries."))
277-
fmt.Println(tr("Currently, Build Profiles only support libraries available through Arduino Library Manager."))
275+
msg := "\n"
276+
msg += tr("WARNING: The sketch is compiled using one or more custom libraries.") + "\n"
277+
msg += tr("Currently, Build Profiles only support libraries available through Arduino Library Manager.")
278+
feedback.Warning(msg)
278279
}
279280

280281
newProfileName := "my_profile_name"

cli/core/upgrade.go

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,16 +80,16 @@ func Upgrade(inst *rpc.Instance, args []string, skipPostInstall bool) {
8080
}
8181

8282
// proceed upgrading, if anything is upgradable
83-
exitErr := false
8483
platformsRefs, err := arguments.ParseReferences(args)
8584
if err != nil {
8685
feedback.Fatal(tr("Invalid argument passed: %v", err), errorcodes.ErrBadArgument)
8786
}
8887

88+
hasBadArguments := false
8989
for i, platformRef := range platformsRefs {
9090
if platformRef.Version != "" {
91-
feedback.Errorf(tr("Invalid item %s"), args[i])
92-
exitErr = true
91+
feedback.Warning(tr("Invalid item %s", args[i]))
92+
hasBadArguments = true
9393
continue
9494
}
9595

@@ -99,7 +99,6 @@ func Upgrade(inst *rpc.Instance, args []string, skipPostInstall bool) {
9999
Architecture: platformRef.Architecture,
100100
SkipPostInstall: skipPostInstall,
101101
}
102-
103102
if _, err := core.PlatformUpgrade(context.Background(), r, feedback.ProgressBar(), feedback.TaskProgress()); err != nil {
104103
if errors.Is(err, &arduino.PlatformAlreadyAtTheLatestVersionError{}) {
105104
feedback.Print(err.Error())
@@ -110,7 +109,7 @@ func Upgrade(inst *rpc.Instance, args []string, skipPostInstall bool) {
110109
}
111110
}
112111

113-
if exitErr {
114-
os.Exit(errorcodes.ErrBadArgument)
112+
if hasBadArguments {
113+
feedback.Fatal(tr("Some upgrades failed, please check the output for details."), errorcodes.ErrBadArgument)
115114
}
116115
}

cli/feedback/feedback.go

Lines changed: 31 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,13 @@ package feedback
2020
import (
2121
"bytes"
2222
"encoding/json"
23-
"errors"
2423
"fmt"
2524
"io"
2625
"os"
2726

2827
"github.com/arduino/arduino-cli/cli/errorcodes"
2928
"github.com/arduino/arduino-cli/i18n"
3029
"github.com/sirupsen/logrus"
31-
"google.golang.org/grpc/status"
3230
"gopkg.in/yaml.v2"
3331
)
3432

@@ -76,6 +74,7 @@ var (
7674
feedbackErr io.Writer
7775
bufferOut *bytes.Buffer
7876
bufferErr *bytes.Buffer
77+
bufferWarnings []string
7978
format OutputFormat
8079
formatSelected bool
8180
)
@@ -92,6 +91,7 @@ func reset() {
9291
feedbackErr = os.Stderr
9392
bufferOut = &bytes.Buffer{}
9493
bufferErr = &bytes.Buffer{}
94+
bufferWarnings = nil
9595
format = Text
9696
formatSelected = false
9797
}
@@ -135,6 +135,7 @@ func SetFormat(f OutputFormat) {
135135
} else {
136136
feedbackOut = bufferOut
137137
feedbackErr = bufferErr
138+
bufferWarnings = nil
138139
}
139140
}
140141

@@ -153,27 +154,14 @@ func Print(v string) {
153154
fmt.Fprintln(feedbackOut, v)
154155
}
155156

156-
// Errorf behaves like fmt.Printf but writes on the error writer and adds a
157-
// newline. It also logs the error.
158-
func Errorf(format string, v ...interface{}) {
159-
// Unbox grpc status errors
160-
for i := range v {
161-
if s, isStatus := v[i].(*status.Status); isStatus {
162-
v[i] = errors.New(s.Message())
163-
} else if err, isErr := v[i].(error); isErr {
164-
if s, isStatus := status.FromError(err); isStatus {
165-
v[i] = errors.New(s.Message())
166-
}
167-
}
157+
// Warning outputs a warning message.
158+
func Warning(msg string) {
159+
if format == Text {
160+
fmt.Fprintln(feedbackErr, msg)
161+
} else {
162+
bufferWarnings = append(bufferWarnings, msg)
168163
}
169-
Error(fmt.Sprintf(format, v...))
170-
}
171-
172-
// Error behaves like fmt.Print but writes on the error writer and adds a
173-
// newline. It also logs the error.
174-
func Error(v ...interface{}) {
175-
fmt.Fprintln(stdErr, v...)
176-
logrus.Error(fmt.Sprint(v...))
164+
logrus.Warning(msg)
177165
}
178166

179167
// FatalError outputs the error and exits with status exitCode.
@@ -213,26 +201,44 @@ func Fatal(errorMsg string, exitCode int) {
213201
os.Exit(exitCode)
214202
}
215203

204+
func augment(data interface{}) interface{} {
205+
if len(bufferWarnings) == 0 {
206+
return data
207+
}
208+
d, err := json.Marshal(data)
209+
if err != nil {
210+
return data
211+
}
212+
var res interface{}
213+
if err := json.Unmarshal(d, &res); err != nil {
214+
return data
215+
}
216+
if m, ok := res.(map[string]interface{}); ok {
217+
m["warnings"] = bufferWarnings
218+
}
219+
return res
220+
}
221+
216222
// PrintResult is a convenient wrapper to provide feedback for complex data,
217223
// where the contents can't be just serialized to JSON but requires more
218224
// structure.
219225
func PrintResult(res Result) {
220226
var data string
221227
switch format {
222228
case JSON:
223-
d, err := json.MarshalIndent(res.Data(), "", " ")
229+
d, err := json.MarshalIndent(augment(res.Data()), "", " ")
224230
if err != nil {
225231
Fatal(fmt.Sprintf("Error during JSON encoding of the output: %v", err), errorcodes.ErrGeneric)
226232
}
227233
data = string(d)
228234
case MinifiedJSON:
229-
d, err := json.Marshal(res.Data())
235+
d, err := json.Marshal(augment(res.Data()))
230236
if err != nil {
231237
Fatal(fmt.Sprintf("Error during JSON encoding of the output: %v", err), errorcodes.ErrGeneric)
232238
}
233239
data = string(d)
234240
case YAML:
235-
d, err := yaml.Marshal(res.Data())
241+
d, err := yaml.Marshal(augment(res.Data()))
236242
if err != nil {
237243
Fatal(fmt.Sprintf("Error during YAML encoding of the output: %v", err), errorcodes.ErrGeneric)
238244
}

cli/instance/instance.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ func Init(instance *rpc.Instance) {
7474
func InitWithProfile(instance *rpc.Instance, profileName string, sketchPath *paths.Path) *rpc.Profile {
7575
// In case the CLI is executed for the first time
7676
if err := FirstUpdate(instance); err != nil {
77-
feedback.Errorf(tr("Error initializing instance: %v"), err)
77+
feedback.Warning(tr("Error initializing instance: %v", err))
7878
return nil
7979
}
8080

@@ -89,7 +89,7 @@ func InitWithProfile(instance *rpc.Instance, profileName string, sketchPath *pat
8989
var profile *rpc.Profile
9090
err := commands.Init(initReq, func(res *rpc.InitResponse) {
9191
if st := res.GetError(); st != nil {
92-
feedback.Errorf(tr("Error initializing instance: %v"), st.Message)
92+
feedback.Warning(tr("Error initializing instance: %v", st.Message))
9393
}
9494

9595
if progress := res.GetInitProgress(); progress != nil {
@@ -106,7 +106,7 @@ func InitWithProfile(instance *rpc.Instance, profileName string, sketchPath *pat
106106
}
107107
})
108108
if err != nil {
109-
feedback.Errorf(tr("Error initializing instance: %v"), err)
109+
feedback.Warning(tr("Error initializing instance: %v", err))
110110
}
111111

112112
return profile

cli/monitor/monitor.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,14 +155,18 @@ func runMonitorCmd(cmd *cobra.Command, args []string) {
155155
go func() {
156156
_, err := io.Copy(tty, portProxy)
157157
if err != nil && !errors.Is(err, io.EOF) {
158-
feedback.Error(tr("Port closed:"), err)
158+
if !quiet {
159+
feedback.Print(tr("Port closed: %v", err))
160+
}
159161
}
160162
cancel()
161163
}()
162164
go func() {
163165
_, err := io.Copy(portProxy, tty)
164166
if err != nil && !errors.Is(err, io.EOF) {
165-
feedback.Error(tr("Port closed:"), err)
167+
if !quiet {
168+
feedback.Print(tr("Port closed: %v", err))
169+
}
166170
}
167171
cancel()
168172
}()

cli/updater/updater.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
package updater
1717

1818
import (
19+
"fmt"
1920
"os"
2021
"strings"
2122
"time"
@@ -66,11 +67,12 @@ func ForceCheckForUpdate(currentVersion *semver.Version) *semver.Version {
6667

6768
// NotifyNewVersionIsAvailable prints information about the new latestVersion
6869
func NotifyNewVersionIsAvailable(latestVersion string) {
69-
feedback.Errorf("\n\n%s %s → %s\n%s",
70+
msg := fmt.Sprintf("\n\n%s %s → %s\n%s",
7071
color.YellowString(tr("A new release of Arduino CLI is available:")),
7172
color.CyanString(globals.VersionInfo.VersionString),
7273
color.CyanString(latestVersion),
7374
color.YellowString("https://arduino.github.io/arduino-cli/latest/installation/#latest-packages"))
75+
feedback.Warning(msg)
7476
}
7577

7678
// shouldCheckForUpdate return true if it actually makes sense to check for new updates,

configuration/configuration.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func Init(configFile string) *viper.Viper {
6565
// ConfigFileNotFoundError is acceptable, anything else
6666
// should be reported to the user
6767
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
68-
feedback.Errorf(tr("Error reading config file: %v"), err)
68+
feedback.Warning(tr("Error reading config file: %v", err))
6969
}
7070
}
7171

@@ -85,7 +85,7 @@ func BindFlags(cmd *cobra.Command, settings *viper.Viper) {
8585
func getDefaultArduinoDataDir() string {
8686
userHomeDir, err := os.UserHomeDir()
8787
if err != nil {
88-
feedback.Errorf(tr("Unable to get user home dir: %v"), err)
88+
feedback.Warning(tr("Unable to get user home dir: %v", err))
8989
return "."
9090
}
9191

@@ -97,7 +97,7 @@ func getDefaultArduinoDataDir() string {
9797
case "windows":
9898
localAppDataPath, err := win32.GetLocalAppDataFolder()
9999
if err != nil {
100-
feedback.Errorf(tr("Unable to get Local App Data Folder: %v"), err)
100+
feedback.Warning(tr("Unable to get Local App Data Folder: %v", err))
101101
return "."
102102
}
103103
return filepath.Join(localAppDataPath, "Arduino15")
@@ -110,7 +110,7 @@ func getDefaultArduinoDataDir() string {
110110
func getDefaultUserDir() string {
111111
userHomeDir, err := os.UserHomeDir()
112112
if err != nil {
113-
feedback.Errorf(tr("Unable to get user home dir: %v"), err)
113+
feedback.Warning(tr("Unable to get user home dir: %v", err))
114114
return "."
115115
}
116116

@@ -122,7 +122,7 @@ func getDefaultUserDir() string {
122122
case "windows":
123123
documentsPath, err := win32.GetDocumentsFolder()
124124
if err != nil {
125-
feedback.Errorf(tr("Unable to get Documents Folder: %v"), err)
125+
feedback.Warning(tr("Unable to get Documents Folder: %v", err))
126126
return "."
127127
}
128128
return filepath.Join(documentsPath, "Arduino")

0 commit comments

Comments
 (0)