diff --git a/arduino/libraries/lint.go b/arduino/libraries/lint.go deleted file mode 100644 index e604f4e148d..00000000000 --- a/arduino/libraries/lint.go +++ /dev/null @@ -1,45 +0,0 @@ -// This file is part of arduino-cli. -// -// Copyright 2020 ARDUINO SA (http://www.arduino.cc/) -// -// This software is released under the GNU General Public License version 3, -// which covers the main part of arduino-cli. -// The terms of this license can be found at: -// https://www.gnu.org/licenses/gpl-3.0.en.html -// -// You can be released from the requirements of the above licenses by purchasing -// a commercial license. Buying such a license is mandatory if you want to -// modify or otherwise use the software for commercial activities involving the -// Arduino software without disclosing the source code of your own applications. -// To purchase a commercial license, send an email to license@arduino.cc. - -package libraries - -// Lint produce warnings about the formal correctness of a Library -func (l *Library) Lint() ([]string, error) { - - // TODO: check for spurious dirs - // subDirs, err := ioutil.ReadDir(libraryDir) - // if err != nil { - // return nil, fmt.Errorf("reading dir %s: %s", libraryDir, err) - // } - // for _, subDir := range subDirs { - // if utils.IsSCCSOrHiddenFile(subDir) { - // if !utils.IsSCCSFile(subDir) && utils.IsHiddenFile(subDir) { - // logger.Fprintln(os.Stdout, "warn", - // "WARNING: Spurious {0} directory in '{1}' library", - // filepath.Base(subDir.Name()), libProperties["name"]) - // } - // } - // } - - // TODO: check for invalid category in library.properties - // if !ValidCategories[libProperties["category"]] { - // logger.Fprintln(os.Stdout, "warn", - // "WARNING: Category '{0}' in library {1} is not valid. Setting to '{2}'", - // libProperties["category"], libProperties["name"], "Uncategorized") - // libProperties["category"] = "Uncategorized" - // } - - return []string{}, nil -} diff --git a/commands/compile/compile.go b/commands/compile/compile.go index 78ee36f98de..084b2814687 100644 --- a/commands/compile/compile.go +++ b/commands/compile/compile.go @@ -33,7 +33,6 @@ import ( "github.com/arduino/arduino-cli/configuration" "github.com/arduino/arduino-cli/i18n" "github.com/arduino/arduino-cli/legacy/builder" - legacyi18n "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/metrics" rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1" @@ -167,12 +166,6 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream builderCtx.USBVidPid = req.GetVidPid() builderCtx.WarningsLevel = req.GetWarnings() - if debug { - builderCtx.DebugLevel = 100 - } else { - builderCtx.DebugLevel = 5 - } - builderCtx.CustomBuildProperties = append(req.GetBuildProperties(), "build.warn_data_percentage=75") if req.GetBuildCachePath() != "" { @@ -205,9 +198,8 @@ func Compile(ctx context.Context, req *rpc.CompileRequest, outStream, errStream builderCtx.BuiltInLibrariesDirs = paths.NewPathList(ideLibrariesPath) } - builderCtx.ExecStdout = outStream - builderCtx.ExecStderr = errStream - builderCtx.SetLogger(&legacyi18n.LoggerToCustomStreams{Stdout: outStream, Stderr: errStream}) + builderCtx.Stdout = outStream + builderCtx.Stderr = errStream builderCtx.Clean = req.GetClean() builderCtx.OnlyUpdateCompilationDatabase = req.GetCreateCompilationDatabaseOnly() diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index 0515eeb3365..c61370cc08b 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -32,6 +32,29 @@ The `parseArch` parameter was removed since it was unused and was always true. T always parsed by the function. Furthermore the function now should also correctly interpret `packager:arch` spelled with the wrong casing. +### `github.com/arduino/arduino-cli/i18n.Init(...)` now requires an empty string to be passed for autodetection of locale + +For automated detection of locale, change the call from: + +```go +i18n.Init() +``` + +to + +```go +i18n.Init("") +``` + +### `github.com/arduino/arduino-cli/legacy/i18n` module has been removed (in particular the `i18n.Logger`) + +The `i18n.Logger` is no longer available. It was mainly used in the legacy builder struct field `Context.Logger`. + +The `Context.Logger` field has been replaced with plain `io.Writer` fields `Contex.Stdout` and `Context.Stderr`. All +existing logger functionality has been dropped, for example the Java-Style formatting with tags like `{0} {1}...` must +be replaced with one of the equivalent golang printf-based alternatives and logging levels must be replaced with direct +writes to `Stdout` or `Stderr`. + ## 0.20.0 ### `board details` arguments change diff --git a/i18n/convert.go b/i18n/convert.go new file mode 100644 index 00000000000..eb3b8939732 --- /dev/null +++ b/i18n/convert.go @@ -0,0 +1,44 @@ +// This file is part of arduino-cli. +// +// Copyright 2020 ARDUINO SA (http://www.arduino.cc/) +// +// This software is released under the GNU General Public License version 3, +// which covers the main part of arduino-cli. +// The terms of this license can be found at: +// https://www.gnu.org/licenses/gpl-3.0.en.html +// +// You can be released from the requirements of the above licenses by purchasing +// a commercial license. Buying such a license is mandatory if you want to +// modify or otherwise use the software for commercial activities involving the +// Arduino software without disclosing the source code of your own applications. +// To purchase a commercial license, send an email to license@arduino.cc. + +package i18n + +import ( + "regexp" + "strconv" + "strings" +) + +var javaFormatPlaceholderRegexp = regexp.MustCompile(`{(\d)}`) + +// FromJavaToGoSyntax convert a translation string made for Java to a one suitable for golang (printf-style). +// The conversion transforms java placeholders like "{0}","{1}","{2}",etc... with the equivalent for golang +// "%[1]v","%[2]v","%[3]v",etc... +// The double single-quote "''" is translated into a single single-quote "'". +func FromJavaToGoSyntax(s string) string { + // Replace "{x}" => "%[x+1]v" + for _, submatch := range javaFormatPlaceholderRegexp.FindAllStringSubmatch(s, -1) { + idx, err := strconv.Atoi(submatch[1]) + if err != nil { + panic(err) + } + s = strings.Replace(s, submatch[0], "%["+strconv.Itoa(idx+1)+"]v", -1) + } + + // Replace "''" => "'" + s = strings.Replace(s, "''", "'", -1) + + return s +} diff --git a/i18n/convert_test.go b/i18n/convert_test.go new file mode 100644 index 00000000000..618fa977b3b --- /dev/null +++ b/i18n/convert_test.go @@ -0,0 +1,54 @@ +// This file is part of arduino-cli. +// +// Copyright 2020 ARDUINO SA (http://www.arduino.cc/) +// +// This software is released under the GNU General Public License version 3, +// which covers the main part of arduino-cli. +// The terms of this license can be found at: +// https://www.gnu.org/licenses/gpl-3.0.en.html +// +// You can be released from the requirements of the above licenses by purchasing +// a commercial license. Buying such a license is mandatory if you want to +// modify or otherwise use the software for commercial activities involving the +// Arduino software without disclosing the source code of your own applications. +// To purchase a commercial license, send an email to license@arduino.cc. + +package i18n + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/require" +) + +func format(format string, a ...interface{}) string { + format = FromJavaToGoSyntax(format) + message := fmt.Sprintf(format, a...) + return message +} + +func TestI18NSyntax(t *testing.T) { + require.Equal(t, "Do you want to remove %[1]v?\nIf you do so you won't be able to use %[1]v any more.", FromJavaToGoSyntax("Do you want to remove {0}?\nIf you do so you won't be able to use {0} any more.")) + require.Equal(t, "A file named \"%[1]v\" already exists in \"%[2]v\"", FromJavaToGoSyntax("A file named \"{0}\" already exists in \"{1}\"")) + require.Equal(t, "Board %[1]v:%[2]v:%[3]v doesn't define a 'build.board' preference. Auto-set to: %[4]v", FromJavaToGoSyntax("Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}")) + + require.Equal(t, "22 11\n", fmt.Sprintf("%[2]d %[1]d\n", 11, 22)) + require.Equal(t, "d c b a", format("{3} {2} {1} {0}", "a", "b", "c", "d")) + + require.Equal(t, "e d b a", format("{4} {3} {1} {0}", "a", "b", "c", "d", "e")) + + require.Equal(t, "a b", format("{0} {1}", "a", "b", "c", "d", "e")) + + require.Equal(t, "%!v(BADINDEX) c b a", format("{3} {2} {1} {0}", "a", "b", "c")) + require.Equal(t, "%!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX)", format("{3} {2} {1} {0}")) + + require.Equal(t, "I'm %[1]v%% sure", FromJavaToGoSyntax("I'm {0}%% sure")) + require.Equal(t, "I'm 100% sure", format("I'm {0}%% sure", 100)) + + require.Equal(t, "Either in [1] or in [2]", format("Either in [{0}] or in [{1}]", 1, 2)) + + require.Equal(t, "Using library a at version b in folder: c ", format("Using library {0} at version {1} in folder: {2} {3}", "a", "b", "c", "")) + + require.Equal(t, "Missing 'a' from library in b", format("Missing '{0}' from library in {1}", "a", "b")) +} diff --git a/i18n/i18n.go b/i18n/i18n.go index a9ac5f74c07..aa4f82edd33 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -19,14 +19,10 @@ package i18n // 1. Locale specified via the function call // 2. OS Locale // 3. en (default) -func Init(configLocale ...string) { +func Init(configLocale string) { locales := supportedLocales() - if len(configLocale) > 1 { - panic("Multiple arguments not supported") - } - - if len(configLocale) > 0 && configLocale[0] != "" { - if locale := findMatchingLocale(configLocale[0], locales); locale != "" { + if configLocale != "" { + if locale := findMatchingLocale(configLocale, locales); locale != "" { setLocale(locale) return } diff --git a/legacy/builder/add_build_board_property_if_missing.go b/legacy/builder/add_build_board_property_if_missing.go index 973b8041b8e..69791318222 100644 --- a/legacy/builder/add_build_board_property_if_missing.go +++ b/legacy/builder/add_build_board_property_if_missing.go @@ -16,7 +16,6 @@ package builder import ( - "os" "strings" "github.com/arduino/arduino-cli/legacy/builder/constants" @@ -27,7 +26,6 @@ type AddBuildBoardPropertyIfMissing struct{} func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { packages := ctx.Hardware - logger := ctx.GetLogger() for _, aPackage := range packages { for _, platform := range aPackage.Platforms { @@ -35,14 +33,10 @@ func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { for _, board := range platformRelease.Boards { if board.Properties.Get("build.board") == "" { board.Properties.Set("build.board", strings.ToUpper(platform.Architecture+"_"+board.BoardID)) - logger.Fprintln( - os.Stdout, - constants.LOG_LEVEL_WARN, - tr("Warning: Board {0}:{1}:{2} doesn''t define a %s preference. Auto-set to: {3}", "''build.board''"), - aPackage.Name, - platform.Architecture, - board.BoardID, - board.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) + ctx.Info(tr("Warning: Board %[1]s doesn't define a %[2]s preference. Auto-set to: %[3]s", + aPackage.Name+":"+platform.Architecture+":"+board.BoardID, + "'build.board'", + board.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD))) } } } diff --git a/legacy/builder/builder.go b/legacy/builder/builder.go index f4de21815d1..10588b341f0 100644 --- a/legacy/builder/builder.go +++ b/legacy/builder/builder.go @@ -16,9 +16,7 @@ package builder import ( - "os" "reflect" - "strconv" "time" "github.com/arduino/arduino-cli/arduino/sketch" @@ -27,6 +25,7 @@ import ( "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/legacy/builder/utils" "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) var tr = i18n.Tr @@ -57,31 +56,31 @@ func (s *Builder) Run(ctx *types.Context) error { &ContainerMergeCopySketchFiles{}, - utils.LogIfVerbose("info", tr("Detecting libraries used...")), + utils.LogIfVerbose(false, tr("Detecting libraries used...")), &ContainerFindIncludes{}, &WarnAboutArchIncompatibleLibraries{}, - utils.LogIfVerbose("info", tr("Generating function prototypes...")), + utils.LogIfVerbose(false, tr("Generating function prototypes...")), &PreprocessSketch{}, - utils.LogIfVerbose("info", tr("Compiling sketch...")), + utils.LogIfVerbose(false, tr("Compiling sketch...")), &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.sketch.prebuild", Suffix: ".pattern"}, &phases.SketchBuilder{}, &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.sketch.postbuild", Suffix: ".pattern", SkipIfOnlyUpdatingCompilationDatabase: true}, - utils.LogIfVerbose("info", tr("Compiling libraries...")), + utils.LogIfVerbose(false, tr("Compiling libraries...")), &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.libraries.prebuild", Suffix: ".pattern"}, &UnusedCompiledLibrariesRemover{}, &phases.LibrariesBuilder{}, &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.libraries.postbuild", Suffix: ".pattern", SkipIfOnlyUpdatingCompilationDatabase: true}, - utils.LogIfVerbose("info", tr("Compiling core...")), + utils.LogIfVerbose(false, tr("Compiling core...")), &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.core.prebuild", Suffix: ".pattern"}, &phases.CoreBuilder{}, &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.core.postbuild", Suffix: ".pattern", SkipIfOnlyUpdatingCompilationDatabase: true}, - utils.LogIfVerbose("info", tr("Linking everything together...")), + utils.LogIfVerbose(false, tr("Linking everything together...")), &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.linking.prelink", Suffix: ".pattern"}, &phases.Linker{}, &RecipeByPrefixSuffixRunner{Prefix: "recipe.hooks.linking.postlink", Suffix: ".pattern", SkipIfOnlyUpdatingCompilationDatabase: true}, @@ -163,7 +162,7 @@ func (s *Preprocess) Run(ctx *types.Context) error { } // Output arduino-preprocessed source - ctx.ExecStdout.Write([]byte(ctx.Source)) + ctx.Stdout.Write([]byte(ctx.Source)) return nil } @@ -200,9 +199,7 @@ func runCommands(ctx *types.Context, commands []types.Command) error { } func PrintRingNameIfDebug(ctx *types.Context, command types.Command) { - if ctx.DebugLevel >= 10 { - ctx.GetLogger().Fprintln(os.Stdout, "debug", "Ts: {0} - Running: {1}", strconv.FormatInt(time.Now().Unix(), 10), reflect.Indirect(reflect.ValueOf(command)).Type().Name()) - } + logrus.Debugf("Ts: %d - Running: %s", time.Now().Unix(), reflect.Indirect(reflect.ValueOf(command)).Type().Name()) } func RunBuilder(ctx *types.Context) error { diff --git a/legacy/builder/builder_utils/utils.go b/legacy/builder/builder_utils/utils.go index e5cc2c25cee..3f98139956b 100644 --- a/legacy/builder/builder_utils/utils.go +++ b/legacy/builder/builder_utils/utils.go @@ -30,6 +30,7 @@ import ( "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-orderedmap" "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) var tr = i18n.Tr @@ -215,7 +216,6 @@ func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources } func compileFileWithRecipe(ctx *types.Context, sourcePath *paths.Path, source *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string, recipe string) (*paths.Path, error) { - logger := ctx.GetLogger() properties := buildProperties.Clone() properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel)) properties.Set(constants.BUILD_PROPERTIES_INCLUDES, strings.Join(includes, constants.SPACE)) @@ -251,9 +251,9 @@ func compileFileWithRecipe(ctx *types.Context, sourcePath *paths.Path, source *p } } else if ctx.Verbose { if objIsUpToDate { - logger.Println(constants.LOG_LEVEL_INFO, tr("Using previously compiled file: {0}"), objectFile) + ctx.Info(tr("Using previously compiled file: %[1]s", objectFile)) } else { - logger.Println("info", tr("Skipping compile of: {0}"), objectFile) + ctx.Info(tr("Skipping compile of: %[1]s", objectFile)) } } @@ -261,15 +261,9 @@ func compileFileWithRecipe(ctx *types.Context, sourcePath *paths.Path, source *p } func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFile *paths.Path) (bool, error) { - logger := ctx.GetLogger() - debugLevel := ctx.DebugLevel - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Checking previous results for {0} (result = {1}, dep = {2})"), sourceFile, objectFile, dependencyFile) - } + logrus.Debugf("Checking previous results for %v (result = %v, dep = %v)", sourceFile, objectFile, dependencyFile) if objectFile == nil || dependencyFile == nil { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: nil")) - } + logrus.Debugf("Not found: nil") return false, nil } @@ -283,9 +277,7 @@ func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFil objectFileStat, err := objectFile.Stat() if err != nil { if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), objectFile) - } + logrus.Debugf("Not found: %v", objectFile) return false, nil } else { return false, errors.WithStack(err) @@ -296,9 +288,7 @@ func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFil dependencyFileStat, err := dependencyFile.Stat() if err != nil { if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), dependencyFile) - } + logrus.Debugf("Not found: %v", dependencyFile) return false, nil } else { return false, errors.WithStack(err) @@ -306,15 +296,11 @@ func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFil } if sourceFileStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), sourceFile, objectFile) - } + logrus.Debugf("%v newer than %v", sourceFile, objectFile) return false, nil } if sourceFileStat.ModTime().After(dependencyFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), sourceFile, dependencyFile) - } + logrus.Debugf("%v newer than %v", sourceFile, dependencyFile) return false, nil } @@ -334,16 +320,12 @@ func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFil firstRow := rows[0] if !strings.HasSuffix(firstRow, ":") { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("No colon in first line of depfile")) - } + logrus.Debugf("No colon in first line of depfile") return false, nil } objFileInDepFile := firstRow[:len(firstRow)-1] if objFileInDepFile != objectFile.String() { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Depfile is about different file: {0}"), objFileInDepFile) - } + logrus.Debugf("Depfile is about different file: %v", objFileInDepFile) return false, nil } @@ -363,22 +345,15 @@ func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFil if err != nil && !os.IsNotExist(err) { // There is probably a parsing error of the dep file // Ignore the error and trigger a full rebuild anyway - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Failed to read: {0}"), row) - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, err.Error()) - } + logrus.WithError(err).Debugf("Failed to read: %v", row) return false, nil } if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Not found: {0}"), row) - } + logrus.Debugf("Not found: %v", row) return false, nil } if depStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("{0} newer than {1}"), row, objectFile) - } + logrus.Debugf("%v newer than %v", row, objectFile) return false, nil } } @@ -455,12 +430,11 @@ func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile *paths.Path) } func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile *paths.Path, objectFilesToArchive paths.PathList, buildProperties *properties.Map) (*paths.Path, error) { - logger := ctx.GetLogger() archiveFilePath := buildPath.JoinPath(archiveFile) if ctx.OnlyUpdateCompilationDatabase { if ctx.Verbose { - logger.Println("info", tr("Skipping archive creation of: {0}"), archiveFilePath) + ctx.Info(tr("Skipping archive creation of: %[1]s", archiveFilePath)) } return archiveFilePath, nil } @@ -483,7 +457,7 @@ func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile } } else { if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, tr("Using previously compiled file: {0}"), archiveFilePath) + ctx.Info(tr("Using previously compiled file: %[1]s", archiveFilePath)) } return archiveFilePath, nil } @@ -514,7 +488,7 @@ const COMMANDLINE_LIMIT = 30000 func PrepareCommandForRecipe(buildProperties *properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) { pattern := buildProperties.Get(recipe) if pattern == "" { - return nil, errors.Errorf(tr("%s pattern is missing"), recipe) + return nil, errors.Errorf(tr("%[1]s pattern is missing"), recipe) } commandLine := buildProperties.ExpandPropsInString(pattern) diff --git a/legacy/builder/container_add_prototypes.go b/legacy/builder/container_add_prototypes.go index cc3a77ab407..ed16f6e2aff 100644 --- a/legacy/builder/container_add_prototypes.go +++ b/legacy/builder/container_add_prototypes.go @@ -16,6 +16,8 @@ package builder import ( + "fmt" + bldr "github.com/arduino/arduino-cli/arduino/builder" "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" @@ -39,7 +41,10 @@ func (s *ContainerAddPrototypes) Run(ctx *types.Context) error { } // Do not bail out if we are generating the compile commands database - ctx.GetLogger().Println("info", "%s: %s", tr("An error occurred adding prototypes"), tr("the compilation database may be incomplete or inaccurate")) + ctx.Info( + fmt.Sprintf("%s: %s", + tr("An error occurred adding prototypes"), + tr("the compilation database may be incomplete or inaccurate"))) if err := sourceFile.CopyTo(targetFilePath); err != nil { return errors.WithStack(err) } diff --git a/legacy/builder/container_find_includes.go b/legacy/builder/container_find_includes.go index 19b587921e9..c8c5325eac9 100644 --- a/legacy/builder/container_find_includes.go +++ b/legacy/builder/container_find_includes.go @@ -100,7 +100,6 @@ import ( "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/arduino-cli/legacy/builder/builder_utils" - "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/legacy/builder/utils" "github.com/arduino/go-paths-helper" @@ -112,7 +111,10 @@ type ContainerFindIncludes struct{} func (s *ContainerFindIncludes) Run(ctx *types.Context) error { err := s.findIncludes(ctx) if err != nil && ctx.OnlyUpdateCompilationDatabase { - ctx.GetLogger().Println("info", "%s: %s", tr("An error occurred detecting libraries"), tr("the compilation database may be incomplete or inaccurate")) + ctx.Info( + fmt.Sprintf("%s: %s", + tr("An error occurred detecting libraries"), + tr("the compilation database may be incomplete or inaccurate"))) return nil } return err @@ -330,7 +332,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t // Fully precompiled libraries should have no dependencies // to avoid ABI breakage if ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_DEBUG, tr("Skipping dependencies detection for precompiled library {0}"), library.Name) + ctx.Info(tr("Skipping dependencies detection for precompiled library %[1]s", library.Name)) } return nil } @@ -342,7 +344,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t if unchanged && cache.valid { include = cache.Next().Include if first && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, tr("Using cached library dependencies for file: {0}"), sourcePath) + ctx.Info(tr("Using cached library dependencies for file: %[1]s", sourcePath)) } } else { preproc_stderr, preproc_err = GCCPreprocRunnerForDiscoveringIncludes(ctx, sourcePath, targetFilePath, includes) @@ -359,7 +361,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t } else { include = IncludesFinderWithRegExp(string(preproc_stderr)) if include == "" && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_DEBUG, tr("Error while detecting libraries included by {0}"), sourcePath) + ctx.Info(tr("Error while detecting libraries included by %[1]s", sourcePath)) } } } @@ -386,7 +388,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t return errors.New(tr("Internal error in cache")) } } - ctx.ExecStderr.Write(preproc_stderr) + ctx.Stderr.Write(preproc_stderr) return errors.WithStack(preproc_err) } diff --git a/legacy/builder/create_cmake_rule.go b/legacy/builder/create_cmake_rule.go index 875f76afdcb..9e8f499605c 100644 --- a/legacy/builder/create_cmake_rule.go +++ b/legacy/builder/create_cmake_rule.go @@ -27,7 +27,6 @@ import ( "github.com/arduino/arduino-cli/legacy/builder/builder_utils" "github.com/arduino/arduino-cli/legacy/builder/constants" - "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/legacy/builder/utils" ) @@ -42,9 +41,6 @@ type ExportProjectCMake struct { } func (s *ExportProjectCMake) Run(ctx *types.Context) error { - //verbose := ctx.Verbose - logger := ctx.GetLogger() - if s.SketchError || !canExportCmakeProject(ctx) { return nil } @@ -160,9 +156,9 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error { var dynamicLibsFromGccMinusL []string var linkDirectories []string - extractCompileFlags(ctx, constants.RECIPE_C_COMBINE_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) - extractCompileFlags(ctx, constants.RECIPE_C_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) - extractCompileFlags(ctx, constants.RECIPE_CPP_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories, logger) + extractCompileFlags(ctx, constants.RECIPE_C_COMBINE_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories) + extractCompileFlags(ctx, constants.RECIPE_C_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories) + extractCompileFlags(ctx, constants.RECIPE_CPP_PATTERN, &defines, &dynamicLibsFromGccMinusL, &linkerflags, &linkDirectories) // Extract folders with .h in them for adding in include list var headerFiles []string @@ -240,7 +236,7 @@ func canExportCmakeProject(ctx *types.Context) bool { return ctx.BuildProperties.Get("compiler.export_cmake") != "" } -func extractCompileFlags(ctx *types.Context, recipe string, defines, dynamicLibs, linkerflags, linkDirectories *[]string, logger i18n.Logger) { +func extractCompileFlags(ctx *types.Context, recipe string, defines, dynamicLibs, linkerflags, linkDirectories *[]string) { command, _ := builder_utils.PrepareCommandForRecipe(ctx.BuildProperties, recipe, true) for _, arg := range command.Args { diff --git a/legacy/builder/fail_if_buildpath_equals_sketchpath.go b/legacy/builder/fail_if_buildpath_equals_sketchpath.go index 48bdb967401..0cfe7073a77 100644 --- a/legacy/builder/fail_if_buildpath_equals_sketchpath.go +++ b/legacy/builder/fail_if_buildpath_equals_sketchpath.go @@ -16,7 +16,6 @@ package builder import ( - "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/pkg/errors" ) @@ -40,8 +39,7 @@ func (s *FailIfBuildPathEqualsSketchPath) Run(ctx *types.Context) error { sketchPath = sketchPath.Parent() if buildPath.EqualsTo(sketchPath) { - return i18n.ErrorfWithLogger(ctx.GetLogger(), - tr("Sketch cannot be located in build path. Please specify a different build path")) + return errors.New(tr("Sketch cannot be located in build path. Please specify a different build path")) } return nil diff --git a/legacy/builder/fail_if_imported_library_is_wrong.go b/legacy/builder/fail_if_imported_library_is_wrong.go index 139dd900e2c..34a69d8d9c2 100644 --- a/legacy/builder/fail_if_imported_library_is_wrong.go +++ b/legacy/builder/fail_if_imported_library_is_wrong.go @@ -16,9 +16,10 @@ package builder import ( + "errors" + "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/arduino-cli/legacy/builder/constants" - "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" ) @@ -29,21 +30,19 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { return nil } - logger := ctx.GetLogger() - for _, library := range ctx.ImportedLibraries { if !library.IsLegacy { if library.InstallDir.Join(constants.LIBRARY_FOLDER_ARCH).IsDir() { - return i18n.ErrorfWithLogger(logger, tr("%[1]s folder is no longer supported! See %[2]s for more information", "'arch'", "http://goo.gl/gfFJzU")) + return errors.New(tr("%[1]s folder is no longer supported! See %[2]s for more information", "'arch'", "http://goo.gl/gfFJzU")) } for _, propName := range libraries.MandatoryProperties { if !library.Properties.ContainsKey(propName) { - return i18n.ErrorfWithLogger(logger, tr("Missing '{0}' from library in {1}"), propName, library.InstallDir) + return errors.New(tr("Missing '%[1]s' from library in %[2]s", propName, library.InstallDir)) } } if library.Layout == libraries.RecursiveLayout { if library.UtilityDir != nil { - return i18n.ErrorfWithLogger(logger, tr("Library can't use both '%[1]s' and '%[2]s' folders. Double check {0}", "src", "utility"), library.InstallDir) + return errors.New(tr("Library can't use both '%[1]s' and '%[2]s' folders. Double check in '%[3]s'.", "src", "utility", library.InstallDir)) } } } diff --git a/legacy/builder/hardware_loader.go b/legacy/builder/hardware_loader.go index a73f4ecad86..70ce36a9524 100644 --- a/legacy/builder/hardware_loader.go +++ b/legacy/builder/hardware_loader.go @@ -34,9 +34,8 @@ func (s *HardwareLoader) Run(ctx *types.Context) error { // When we're gonna refactor the legacy package this will be gone. if ctx.Verbose { - log := ctx.GetLogger() for _, err := range errs { - log.Println("info", "Error loading hardware platform: {0}", err.Message()) + ctx.Info(tr("Error loading hardware platform: %[1]s", err.Message())) } } } diff --git a/legacy/builder/i18n/errors.go b/legacy/builder/i18n/errors.go deleted file mode 100644 index 4080742690b..00000000000 --- a/legacy/builder/i18n/errors.go +++ /dev/null @@ -1,16 +0,0 @@ -package i18n - -import ( - "os" - - "github.com/arduino/arduino-cli/legacy/builder/constants" - "github.com/pkg/errors" -) - -func ErrorfWithLogger(logger Logger, format string, a ...interface{}) error { - if _, isMachineLogger := logger.(*MachineLogger); isMachineLogger { - logger.Fprintln(os.Stderr, constants.LOG_LEVEL_ERROR, format, a...) - return errors.New("") - } - return errors.New(Format(format, a...)) -} diff --git a/legacy/builder/i18n/i18n.go b/legacy/builder/i18n/i18n.go deleted file mode 100644 index 3d745f0a49b..00000000000 --- a/legacy/builder/i18n/i18n.go +++ /dev/null @@ -1,139 +0,0 @@ -// This file is part of arduino-cli. -// -// Copyright 2020 ARDUINO SA (http://www.arduino.cc/) -// -// This software is released under the GNU General Public License version 3, -// which covers the main part of arduino-cli. -// The terms of this license can be found at: -// https://www.gnu.org/licenses/gpl-3.0.en.html -// -// You can be released from the requirements of the above licenses by purchasing -// a commercial license. Buying such a license is mandatory if you want to -// modify or otherwise use the software for commercial activities involving the -// Arduino software without disclosing the source code of your own applications. -// To purchase a commercial license, send an email to license@arduino.cc. - -package i18n - -import ( - "fmt" - "io" - "net/url" - "os" - "regexp" - "strconv" - "strings" - "sync" -) - -var PLACEHOLDER = regexp.MustCompile(`{(\d)}`) - -type Logger interface { - Fprintln(w io.Writer, level string, format string, a ...interface{}) - Println(level string, format string, a ...interface{}) -} - -type LoggerToCustomStreams struct { - Stdout io.Writer - Stderr io.Writer - mux sync.Mutex -} - -func (s *LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - s.mux.Lock() - defer s.mux.Unlock() - target := s.Stdout - if w == os.Stderr { - target = s.Stderr - } - fmt.Fprintln(target, Format(format, a...)) -} - -func (s *LoggerToCustomStreams) Println(level string, format string, a ...interface{}) { - s.Fprintln(nil, level, format, a...) -} - -type NoopLogger struct{} - -func (s *NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {} - -func (s *NoopLogger) Println(level string, format string, a ...interface{}) {} - -type HumanTagsLogger struct{} - -func (s *HumanTagsLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - format = "[" + level + "] " + format - fprintln(w, Format(format, a...)) -} - -func (s *HumanTagsLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(os.Stdout, level, format, a...) -} - -type HumanLogger struct{} - -func (s *HumanLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - fprintln(w, Format(format, a...)) -} - -func (s *HumanLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(os.Stdout, level, format, a...) -} - -type MachineLogger struct{} - -func (s *MachineLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - printMachineFormattedLogLine(w, level, format, a) -} - -func (s *MachineLogger) Println(level string, format string, a ...interface{}) { - printMachineFormattedLogLine(os.Stdout, level, format, a) -} - -func printMachineFormattedLogLine(w io.Writer, level string, format string, a []interface{}) { - a = append([]interface{}(nil), a...) - for idx, value := range a { - if str, ok := value.(string); ok { - a[idx] = url.QueryEscape(str) - } else if stringer, ok := value.(fmt.Stringer); ok { - a[idx] = url.QueryEscape(stringer.String()) - } - } - fprintf(w, "===%s ||| %s ||| %s\n", level, format, a) -} - -var lock sync.Mutex - -func fprintln(w io.Writer, s string) { - lock.Lock() - defer lock.Unlock() - fmt.Fprintln(w, s) -} - -func fprintf(w io.Writer, format string, a ...interface{}) { - lock.Lock() - defer lock.Unlock() - fmt.Fprintf(w, format, a...) -} - -func FromJavaToGoSyntax(s string) string { - submatches := PLACEHOLDER.FindAllStringSubmatch(s, -1) - for _, submatch := range submatches { - idx, err := strconv.Atoi(submatch[1]) - if err != nil { - panic(err) - } - idx = idx + 1 - s = strings.Replace(s, submatch[0], "%["+strconv.Itoa(idx)+"]v", -1) - } - - s = strings.Replace(s, "''", "'", -1) - - return s -} - -func Format(format string, a ...interface{}) string { - format = FromJavaToGoSyntax(format) - message := fmt.Sprintf(format, a...) - return message -} diff --git a/legacy/builder/libraries_loader.go b/legacy/builder/libraries_loader.go index d486febe95e..97ca9339c1c 100644 --- a/legacy/builder/libraries_loader.go +++ b/legacy/builder/libraries_loader.go @@ -16,8 +16,6 @@ package builder import ( - "os" - "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" @@ -39,9 +37,6 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { lm.AddLibrariesDir(folder, libraries.IDEBuiltIn) } - debugLevel := ctx.DebugLevel - logger := ctx.GetLogger() - actualPlatform := ctx.ActualPlatform platform := ctx.TargetPlatform if actualPlatform != platform { @@ -74,20 +69,6 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } } - if debugLevel > 0 { - for _, lib := range lm.Libraries { - for _, libAlt := range lib.Alternatives { - warnings, err := libAlt.Lint() - if err != nil { - return errors.WithStack(err) - } - for _, warning := range warnings { - logger.Fprintln(os.Stdout, "warn", warning) - } - } - } - } - resolver := librariesresolver.NewCppResolver() if err := resolver.ScanFromLibrariesManager(lm); err != nil { return errors.WithStack(err) diff --git a/legacy/builder/merge_sketch_with_bootloader.go b/legacy/builder/merge_sketch_with_bootloader.go index f8ec29757b0..377b5a9f697 100644 --- a/legacy/builder/merge_sketch_with_bootloader.go +++ b/legacy/builder/merge_sketch_with_bootloader.go @@ -22,7 +22,6 @@ import ( "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" - "github.com/arduino/arduino-cli/legacy/builder/utils" "github.com/arduino/go-paths-helper" "github.com/marcinbor85/gohex" "github.com/pkg/errors" @@ -66,7 +65,9 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { bootloaderPath := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH).Join(constants.FOLDER_BOOTLOADERS, bootloader) if bootloaderPath.NotExist() { - utils.LogIfVerbose(constants.LOG_LEVEL_WARN, tr("Bootloader file specified but missing: {0}"), bootloaderPath) + if ctx.Verbose { + ctx.Warn(tr("Bootloader file specified but missing: %[1]s", bootloaderPath)) + } return nil } @@ -79,8 +80,8 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { maximumBinSize *= 2 } err := merge(builtSketchPath, bootloaderPath, mergedSketchPath, maximumBinSize) - if err != nil { - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, err.Error()) + if err != nil && ctx.Verbose { + ctx.Info(err.Error()) } return nil diff --git a/legacy/builder/phases/core_builder.go b/legacy/builder/phases/core_builder.go index 9d5caaa6914..c1c8a2fb63c 100644 --- a/legacy/builder/phases/core_builder.go +++ b/legacy/builder/phases/core_builder.go @@ -44,9 +44,8 @@ func (s *CoreBuilder) Run(ctx *types.Context) error { if coreBuildCachePath != nil { if _, err := coreBuildCachePath.RelTo(ctx.BuildPath); err != nil { - logger := ctx.GetLogger() - logger.Println(constants.LOG_LEVEL_INFO, tr("Couldn't deeply cache core build: {0}"), err) - logger.Println(constants.LOG_LEVEL_INFO, tr("Running normal build of the core...")) + ctx.Info(tr("Couldn't deeply cache core build: %[1]s", err)) + ctx.Info(tr("Running normal build of the core...")) coreBuildCachePath = nil ctx.CoreBuildCachePath = nil } else if err := coreBuildCachePath.MkdirAll(); err != nil { @@ -66,7 +65,6 @@ func (s *CoreBuilder) Run(ctx *types.Context) error { } func compileCore(ctx *types.Context, buildPath *paths.Path, buildCachePath *paths.Path, buildProperties *properties.Map) (*paths.Path, paths.PathList, error) { - logger := ctx.GetLogger() coreFolder := buildProperties.GetPath("build.core.path") variantFolder := buildProperties.GetPath("build.variant.path") @@ -104,7 +102,7 @@ func compileCore(ctx *types.Context, buildPath *paths.Path, buildCachePath *path if canUseArchivedCore { // use archived core if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, tr("Using precompiled core: {0}"), targetArchivedCore) + ctx.Info(tr("Using precompiled core: %[1]s", targetArchivedCore)) } return targetArchivedCore, variantObjectFiles, nil } @@ -125,15 +123,13 @@ func compileCore(ctx *types.Context, buildPath *paths.Path, buildCachePath *path err := archiveFile.CopyTo(targetArchivedCore) if ctx.Verbose { if err == nil { - logger.Println(constants.LOG_LEVEL_INFO, tr("Archiving built core (caching) in: {0}"), targetArchivedCore) + ctx.Info(tr("Archiving built core (caching) in: %[1]s", targetArchivedCore)) } else if os.IsNotExist(err) { - logger.Println( - constants.LOG_LEVEL_INFO, - tr("Unable to cache built core, please tell {0} maintainers to follow %s", - "https://arduino.github.io/arduino-cli/latest/platform-specification/#recipes-to-build-the-corea-archive-file"), - ctx.ActualPlatform) + ctx.Info(tr("Unable to cache built core, please tell %[1]s maintainers to follow %[2]s", + ctx.ActualPlatform, + "https://arduino.github.io/arduino-cli/latest/platform-specification/#recipes-to-build-the-corea-archive-file")) } else { - logger.Println(constants.LOG_LEVEL_INFO, tr("Error archiving built core (caching) in {0}: {1}"), targetArchivedCore, err) + ctx.Info(tr("Error archiving built core (caching) in %[1]s: %[2]s", targetArchivedCore, err)) } } } diff --git a/legacy/builder/phases/libraries_builder.go b/legacy/builder/phases/libraries_builder.go index 7253c8a67e9..b19363db01f 100644 --- a/legacy/builder/phases/libraries_builder.go +++ b/legacy/builder/phases/libraries_builder.go @@ -16,7 +16,6 @@ package phases import ( - "os" "strings" "github.com/arduino/arduino-cli/arduino/libraries" @@ -87,26 +86,25 @@ func findExpectedPrecompiledLibFolder(ctx *types.Context, library *libraries.Lib } } - logger := ctx.GetLogger() - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("Library {0} has been declared precompiled:"), library.Name) + ctx.Info(tr("Library %[1]s has been declared precompiled:", library.Name)) // Try directory with full fpuSpecs first, if available if len(fpuSpecs) > 0 { fpuSpecs = strings.TrimRight(fpuSpecs, "-") fullPrecompDir := library.SourceDir.Join(mcu).Join(fpuSpecs) if fullPrecompDir.Exist() && directoryContainsFile(fullPrecompDir) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("Using precompiled library in {0}"), fullPrecompDir) + ctx.Info(tr("Using precompiled library in %[1]s", fullPrecompDir)) return fullPrecompDir } - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("Precompiled library in \"{0}\" not found"), fullPrecompDir) + ctx.Info(tr(`Precompiled library in "%[1]s" not found`, fullPrecompDir)) } precompDir := library.SourceDir.Join(mcu) if precompDir.Exist() && directoryContainsFile(precompDir) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("Using precompiled library in {0}"), precompDir) + ctx.Info(tr("Using precompiled library in %[1]s", precompDir)) return precompDir } - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("Precompiled library in \"{0}\" not found"), precompDir) + ctx.Info(tr(`Precompiled library in "%[1]s" not found`, precompDir)) return nil } @@ -130,9 +128,8 @@ func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *p } func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { - logger := ctx.GetLogger() if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, tr("Compiling library \"{0}\""), library.Name) + ctx.Info(tr(`Compiling library "%[1]s"`, library.Name)) } libraryBuildPath := buildPath.Join(library.Name) @@ -147,9 +144,7 @@ func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *p precompiledPath := findExpectedPrecompiledLibFolder(ctx, library) if !coreSupportPrecompiled { - logger := ctx.GetLogger() - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_INFO, tr("The platform does not support '{0}' for precompiled libraries."), "compiler.libraries.ldflags") - + ctx.Info(tr("The platform does not support '%[1]s' for precompiled libraries.", "compiler.libraries.ldflags")) } else if precompiledPath != nil { // Find all libraries in precompiledPath libs, err := precompiledPath.ReadDir() diff --git a/legacy/builder/phases/linker.go b/legacy/builder/phases/linker.go index 5b1b4b1f7d7..a78762ebac0 100644 --- a/legacy/builder/phases/linker.go +++ b/legacy/builder/phases/linker.go @@ -32,7 +32,7 @@ type Linker struct{} func (s *Linker) Run(ctx *types.Context) error { if ctx.OnlyUpdateCompilationDatabase { if ctx.Verbose { - ctx.GetLogger().Println("info", tr("Skip linking of final executable.")) + ctx.Info(tr("Skip linking of final executable.")) } return nil } diff --git a/legacy/builder/phases/sizer.go b/legacy/builder/phases/sizer.go index b4a372049b9..a23a8312ca2 100644 --- a/legacy/builder/phases/sizer.go +++ b/legacy/builder/phases/sizer.go @@ -51,8 +51,6 @@ func (s *Sizer) Run(ctx *types.Context) error { } func checkSize(ctx *types.Context, buildProperties *properties.Map) error { - logger := ctx.GetLogger() - properties := buildProperties.Clone() properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel)) @@ -78,26 +76,23 @@ func checkSize(ctx *types.Context, buildProperties *properties.Map) error { textSize, dataSize, _, err := execSizeRecipe(ctx, properties) if err != nil { - logger.Println(constants.LOG_LEVEL_WARN, tr("Couldn't determine program size")) + ctx.Warn(tr("Couldn't determine program size")) return nil } - logger.Println(constants.LOG_LEVEL_INFO, - tr("Sketch uses {0} bytes ({2}%%) of program storage space. Maximum is {1} bytes."), + ctx.Info(tr("Sketch uses %[1]s bytes (%[3]s%%) of program storage space. Maximum is %[2]s bytes.", strconv.Itoa(textSize), strconv.Itoa(maxTextSize), - strconv.Itoa(textSize*100/maxTextSize)) + strconv.Itoa(textSize*100/maxTextSize))) if dataSize >= 0 { if maxDataSize > 0 { - logger.Println(constants.LOG_LEVEL_INFO, - tr("Global variables use {0} bytes ({2}%%) of dynamic memory, leaving {3} bytes for local variables. Maximum is {1} bytes."), + ctx.Info(tr("Global variables use %[1]s bytes (%[3]s%%) of dynamic memory, leaving %[4]s bytes for local variables. Maximum is %[2]s bytes.", strconv.Itoa(dataSize), strconv.Itoa(maxDataSize), strconv.Itoa(dataSize*100/maxDataSize), - strconv.Itoa(maxDataSize-dataSize)) + strconv.Itoa(maxDataSize-dataSize))) } else { - logger.Println(constants.LOG_LEVEL_INFO, - tr("Global variables use {0} bytes of dynamic memory."), strconv.Itoa(dataSize)) + ctx.Info(tr("Global variables use %[1]s bytes of dynamic memory.", strconv.Itoa(dataSize))) } } @@ -117,14 +112,12 @@ func checkSize(ctx *types.Context, buildProperties *properties.Map) error { } if textSize > maxTextSize { - logger.Println(constants.LOG_LEVEL_ERROR, - tr("Sketch too big; see %s for tips on reducing it.", "https://support.arduino.cc/hc/en-us/articles/360013825179")) + ctx.Warn(tr("Sketch too big; see %[1]s for tips on reducing it.", "https://support.arduino.cc/hc/en-us/articles/360013825179")) return errors.New(tr("text section exceeds available space in board")) } if maxDataSize > 0 && dataSize > maxDataSize { - logger.Println(constants.LOG_LEVEL_ERROR, - tr("Not enough memory; see %s for tips on reducing your footprint.", "https://support.arduino.cc/hc/en-us/articles/360013825179")) + ctx.Warn(tr("Not enough memory; see %[1]s for tips on reducing your footprint.", "https://support.arduino.cc/hc/en-us/articles/360013825179")) return errors.New(tr("data section exceeds available space in board")) } @@ -134,7 +127,7 @@ func checkSize(ctx *types.Context, buildProperties *properties.Map) error { return err } if maxDataSize > 0 && dataSize > maxDataSize*warnDataPercentage/100 { - logger.Println(constants.LOG_LEVEL_WARN, tr("Low memory available, stability problems may occur.")) + ctx.Warn(tr("Low memory available, stability problems may occur.")) } } diff --git a/legacy/builder/preprocess_sketch.go b/legacy/builder/preprocess_sketch.go index 8b272093b95..a252ae4900b 100644 --- a/legacy/builder/preprocess_sketch.go +++ b/legacy/builder/preprocess_sketch.go @@ -144,6 +144,6 @@ func (s *OutputCodeCompletions) Run(ctx *types.Context) error { // we assume it is a json, let's make it compliant at least ctx.CodeCompletions = "[]" } - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, ctx.CodeCompletions) + fmt.Fprintln(ctx.Stdout, ctx.CodeCompletions) return nil } diff --git a/legacy/builder/print_used_and_not_used_libraries.go b/legacy/builder/print_used_and_not_used_libraries.go index 96d7d507c3c..971036bea45 100644 --- a/legacy/builder/print_used_and_not_used_libraries.go +++ b/legacy/builder/print_used_and_not_used_libraries.go @@ -16,10 +16,10 @@ package builder import ( - "os" + "fmt" + "strings" "time" - "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" ) @@ -29,32 +29,31 @@ type PrintUsedAndNotUsedLibraries struct { } func (s *PrintUsedAndNotUsedLibraries) Run(ctx *types.Context) error { - var logLevel string - // Print this message as warning when the sketch didn't compile, - // as info when we're verbose and not all otherwise - if s.SketchError { - logLevel = constants.LOG_LEVEL_WARN - } else if ctx.Verbose { - logLevel = constants.LOG_LEVEL_INFO - } else { + // Print this message: + // - as warning, when the sketch didn't compile + // - as info, when verbose is on + // - otherwise, output nothing + if !s.SketchError && !ctx.Verbose { return nil } - logger := ctx.GetLogger() - libraryResolutionResults := ctx.LibrariesResolutionResults - - for header, libResResult := range libraryResolutionResults { + res := "" + for header, libResResult := range ctx.LibrariesResolutionResults { if len(libResResult.NotUsedLibraries) == 0 { continue } - logger.Fprintln(os.Stdout, logLevel, tr("Multiple libraries were found for \"{0}\""), header) - logger.Fprintln(os.Stdout, logLevel, " "+tr("Used: {0}"), libResResult.Library.InstallDir) + res += fmt.Sprintln(tr(`Multiple libraries were found for "%[1]s"`, header)) + res += fmt.Sprintln(" " + tr("Used: %[1]s", libResResult.Library.InstallDir)) for _, notUsedLibrary := range libResResult.NotUsedLibraries { - logger.Fprintln(os.Stdout, logLevel, " "+tr("Not used: {0}"), notUsedLibrary.InstallDir) + res += fmt.Sprintln(" " + tr("Not used: %[1]s", notUsedLibrary.InstallDir)) } } - + res = strings.TrimSpace(res) + if s.SketchError { + ctx.Warn(res) + } else { + ctx.Info(res) + } time.Sleep(100 * time.Millisecond) - return nil } diff --git a/legacy/builder/print_used_libraries_if_verbose.go b/legacy/builder/print_used_libraries_if_verbose.go index 409fb18eb18..8c32c925995 100644 --- a/legacy/builder/print_used_libraries_if_verbose.go +++ b/legacy/builder/print_used_libraries_if_verbose.go @@ -18,17 +18,13 @@ package builder import ( "time" - "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" ) type PrintUsedLibrariesIfVerbose struct{} func (s *PrintUsedLibrariesIfVerbose) Run(ctx *types.Context) error { - verbose := ctx.Verbose - logger := ctx.GetLogger() - - if !verbose || len(ctx.ImportedLibraries) == 0 { + if !ctx.Verbose || len(ctx.ImportedLibraries) == 0 { return nil } @@ -38,22 +34,21 @@ func (s *PrintUsedLibrariesIfVerbose) Run(ctx *types.Context) error { legacy = tr("(legacy)") } if library.Version.String() == "" { - logger.Println(constants.LOG_LEVEL_INFO, - tr("Using library {0} in folder: {1} {2}"), - library.Name, - library.InstallDir, - legacy) + ctx.Info( + tr("Using library %[1]s in folder: %[2]s %[3]s", + library.Name, + library.InstallDir, + legacy)) } else { - logger.Println(constants.LOG_LEVEL_INFO, - tr("Using library {0} at version {1} in folder: {2} {3}"), - library.Name, - library.Version, - library.InstallDir, - legacy) + ctx.Info( + tr("Using library %[1]s at version %[2]s in folder: %[3]s %[4]s", + library.Name, + library.Version, + library.InstallDir, + legacy)) } } time.Sleep(100 * time.Millisecond) - return nil } diff --git a/legacy/builder/recipe_runner.go b/legacy/builder/recipe_runner.go index a9ce71de39e..6dfb914d7b9 100644 --- a/legacy/builder/recipe_runner.go +++ b/legacy/builder/recipe_runner.go @@ -16,16 +16,16 @@ package builder import ( - "os" + "fmt" "sort" "strings" "github.com/arduino/arduino-cli/legacy/builder/builder_utils" - "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/legacy/builder/utils" properties "github.com/arduino/go-properties-orderedmap" "github.com/pkg/errors" + "github.com/sirupsen/logrus" ) type RecipeByPrefixSuffixRunner struct { @@ -35,19 +35,14 @@ type RecipeByPrefixSuffixRunner struct { } func (s *RecipeByPrefixSuffixRunner) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - if ctx.DebugLevel >= 10 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Looking for recipes like {0}*{1}"), s.Prefix, s.Suffix) - } + logrus.Debugf(fmt.Sprintf("Looking for recipes like %s", s.Prefix+"*"+s.Suffix)) buildProperties := ctx.BuildProperties.Clone() recipes := findRecipes(buildProperties, s.Prefix, s.Suffix) properties := buildProperties.Clone() for _, recipe := range recipes { - if ctx.DebugLevel >= 10 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, tr("Running recipe: {0}"), recipe) - } + logrus.Debugf(fmt.Sprintf("Running recipe: %s", recipe)) command, err := builder_utils.PrepareCommandForRecipe(properties, recipe, false) if err != nil { @@ -56,7 +51,7 @@ func (s *RecipeByPrefixSuffixRunner) Run(ctx *types.Context) error { if ctx.OnlyUpdateCompilationDatabase && s.SkipIfOnlyUpdatingCompilationDatabase { if ctx.Verbose { - ctx.GetLogger().Println("info", tr("Skipping: {0}"), strings.Join(command.Args, " ")) + ctx.Info(tr("Skipping: %[1]s", strings.Join(command.Args, " "))) } return nil } diff --git a/legacy/builder/resolve_library.go b/legacy/builder/resolve_library.go index 9d9a9781e25..3cb3c07aee3 100644 --- a/legacy/builder/resolve_library.go +++ b/legacy/builder/resolve_library.go @@ -19,7 +19,6 @@ import ( "fmt" "github.com/arduino/arduino-cli/arduino/libraries" - "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" ) @@ -29,11 +28,10 @@ func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { candidates := resolver.AlternativesFor(header) - logger := ctx.GetLogger() if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, tr("Alternatives for %[1]s: %[2]s", header, candidates)) - logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf("ResolveLibrary(%s)", header)) - logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf(" -> %s: %s", tr("candidates"), candidates)) + ctx.Info(tr("Alternatives for %[1]s: %[2]s", header, candidates)) + ctx.Info(fmt.Sprintf("ResolveLibrary(%s)", header)) + ctx.Info(fmt.Sprintf(" -> %s: %s", tr("candidates"), candidates)) } if candidates == nil || len(candidates) == 0 { diff --git a/legacy/builder/target_board_resolver.go b/legacy/builder/target_board_resolver.go index 81dada3273a..6e1f2f7d5d0 100644 --- a/legacy/builder/target_board_resolver.go +++ b/legacy/builder/target_board_resolver.go @@ -16,21 +16,18 @@ package builder import ( + "fmt" "strings" - "github.com/arduino/arduino-cli/legacy/builder/constants" - "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" ) type TargetBoardResolver struct{} func (s *TargetBoardResolver) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - targetPackage, targetPlatform, targetBoard, buildProperties, actualPlatform, err := ctx.PackageManager.ResolveFQBN(ctx.FQBN) if err != nil { - return i18n.ErrorfWithLogger(logger, tr("Error resolving FQBN: {0}"), err) + return fmt.Errorf("%s: %w", tr("Error resolving FQBN"), err) } targetBoard.Properties = buildProperties // FIXME.... @@ -43,14 +40,8 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { core = core[strings.Index(core, ":")+1:] if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, - tr("Using board '{0}' from platform in folder: {1}"), - targetBoard.BoardID, - targetPlatform.InstallDir) - logger.Println(constants.LOG_LEVEL_INFO, - tr("Using core '{0}' from platform in folder: {1}"), - core, - actualPlatform.InstallDir) + ctx.Info(tr("Using board '%[1]s' from platform in folder: %[2]s", targetBoard.BoardID, targetPlatform.InstallDir)) + ctx.Info(tr("Using core '%[1]s' from platform in folder: %[2]s", core, actualPlatform.InstallDir)) } ctx.BuildCore = core diff --git a/legacy/builder/test/builder_test.go b/legacy/builder/test/builder_test.go index 7bc35b46a39..31570f21277 100644 --- a/legacy/builder/test/builder_test.go +++ b/legacy/builder/test/builder_test.go @@ -47,7 +47,6 @@ func TestBuilderEmptySketch(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch1.ino"), "arduino:avr:uno") - ctx.DebugLevel = 10 buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() diff --git a/legacy/builder/test/create_build_options_map_test.go b/legacy/builder/test/create_build_options_map_test.go index 3abb60eca0a..9cc72379d14 100644 --- a/legacy/builder/test/create_build_options_map_test.go +++ b/legacy/builder/test/create_build_options_map_test.go @@ -34,7 +34,6 @@ func TestCreateBuildOptionsMap(t *testing.T) { ArduinoAPIVersion: "ideVersion", Verbose: true, BuildPath: paths.New("buildPath"), - DebugLevel: 5, OptimizationFlags: "-Os", } diff --git a/legacy/builder/test/i18n_test.go b/legacy/builder/test/i18n_test.go deleted file mode 100644 index f6866ca73fd..00000000000 --- a/legacy/builder/test/i18n_test.go +++ /dev/null @@ -1,59 +0,0 @@ -// This file is part of arduino-cli. -// -// Copyright 2020 ARDUINO SA (http://www.arduino.cc/) -// -// This software is released under the GNU General Public License version 3, -// which covers the main part of arduino-cli. -// The terms of this license can be found at: -// https://www.gnu.org/licenses/gpl-3.0.en.html -// -// You can be released from the requirements of the above licenses by purchasing -// a commercial license. Buying such a license is mandatory if you want to -// modify or otherwise use the software for commercial activities involving the -// Arduino software without disclosing the source code of your own applications. -// To purchase a commercial license, send an email to license@arduino.cc. - -package test - -import ( - "fmt" - "testing" - - "github.com/arduino/arduino-cli/legacy/builder/constants" - "github.com/arduino/arduino-cli/legacy/builder/i18n" - "github.com/stretchr/testify/require" -) - -func TestI18NSyntax(t *testing.T) { - require.Equal(t, "Do you want to remove %[1]v?\nIf you do so you won't be able to use %[1]v any more.", i18n.FromJavaToGoSyntax("Do you want to remove {0}?\nIf you do so you won't be able to use {0} any more.")) - require.Equal(t, "A file named \"%[1]v\" already exists in \"%[2]v\"", i18n.FromJavaToGoSyntax("A file named \"{0}\" already exists in \"{1}\"")) - require.Equal(t, "Board %[1]v:%[2]v:%[3]v doesn't define a 'build.board' preference. Auto-set to: %[4]v", i18n.FromJavaToGoSyntax("Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}")) - - require.Equal(t, "22 11\n", fmt.Sprintf("%[2]d %[1]d\n", 11, 22)) - require.Equal(t, "d c b a", i18n.Format("{3} {2} {1} {0}", "a", "b", "c", "d")) - - require.Equal(t, "e d b a", i18n.Format("{4} {3} {1} {0}", "a", "b", "c", "d", "e")) - - require.Equal(t, "a b", i18n.Format("{0} {1}", "a", "b", "c", "d", "e")) - - require.Equal(t, "%!v(BADINDEX) c b a", i18n.Format("{3} {2} {1} {0}", "a", "b", "c")) - require.Equal(t, "%!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX) %!v(BADINDEX)", i18n.Format("{3} {2} {1} {0}")) - - require.Equal(t, "I'm %[1]v%% sure", i18n.FromJavaToGoSyntax("I'm {0}%% sure")) - require.Equal(t, "I'm 100% sure", i18n.Format("I'm {0}%% sure", 100)) - - require.Equal(t, "Either in [1] or in [2]", i18n.Format("Either in [{0}] or in [{1}]", 1, 2)) - - require.Equal(t, "Using library a at version b in folder: c ", i18n.Format("Using library {0} at version {1} in folder: {2} {3}", "a", "b", "c", "")) - - require.Equal(t, "Missing 'a' from library in b", i18n.Format("Missing '{0}' from library in {1}", "a", "b")) -} - -func TestI18NInheritance(t *testing.T) { - var logger i18n.Logger - logger = &i18n.HumanLogger{} - logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!") - - logger = &i18n.MachineLogger{} - logger.Println(constants.LOG_LEVEL_INFO, "good {0} {1}", "morning", "vietnam!") -} diff --git a/legacy/builder/test/prototypes_adder_test.go b/legacy/builder/test/prototypes_adder_test.go index 1e2e706870e..5025f199d82 100644 --- a/legacy/builder/test/prototypes_adder_test.go +++ b/legacy/builder/test/prototypes_adder_test.go @@ -48,8 +48,6 @@ func TestPrototypesAdderBridgeExample(t *testing.T) { buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() - ctx.DebugLevel = 10 - commands := []types.Command{ &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, diff --git a/legacy/builder/test/store_build_options_map_test.go b/legacy/builder/test/store_build_options_map_test.go index f3aa0b7ba79..56c1913d7ee 100644 --- a/legacy/builder/test/store_build_options_map_test.go +++ b/legacy/builder/test/store_build_options_map_test.go @@ -36,7 +36,6 @@ func TestStoreBuildOptionsMap(t *testing.T) { ArduinoAPIVersion: "ideVersion", CustomBuildProperties: []string{"custom=prop"}, Verbose: true, - DebugLevel: 5, OptimizationFlags: "-Os", } diff --git a/legacy/builder/types/context.go b/legacy/builder/types/context.go index 5f8a92b2259..77610afbb8e 100644 --- a/legacy/builder/types/context.go +++ b/legacy/builder/types/context.go @@ -16,9 +16,13 @@ package types import ( + "fmt" "io" + "os" "strings" + "sync" + "github.com/arduino/arduino-cli/arduino" "github.com/arduino/arduino-cli/arduino/builder" "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/arduino-cli/arduino/cores/packagemanager" @@ -27,7 +31,6 @@ import ( "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" "github.com/arduino/arduino-cli/arduino/sketch" "github.com/arduino/arduino-cli/commands" - "github.com/arduino/arduino-cli/legacy/builder/i18n" rpc "github.com/arduino/arduino-cli/rpc/cc/arduino/cli/commands/v1" paths "github.com/arduino/go-paths-helper" properties "github.com/arduino/go-properties-orderedmap" @@ -150,10 +153,6 @@ type Context struct { // Contents of a custom build properties file (line by line) CustomBuildProperties []string - // Logging - logger i18n.Logger - DebugLevel int - // Reuse old tools since the backing storage didn't change CanUseCachedTools bool @@ -163,9 +162,10 @@ type Context struct { // Parallel processes Jobs int - // Out and Err stream to redirect all Exec commands - ExecStdout io.Writer - ExecStderr io.Writer + // Out and Err stream to redirect all output + Stdout io.Writer + Stderr io.Writer + stdLock sync.Mutex // Sizer results ExecutableSectionsSize ExecutablesFileSections @@ -238,7 +238,7 @@ func (ctx *Context) InjectBuildOptions(opts *properties.Map) { ctx.SketchLocation = opts.GetPath("sketchLocation") fqbn, err := cores.ParseFQBN(opts.Get("fqbn")) if err != nil { - i18n.ErrorfWithLogger(ctx.GetLogger(), tr("Error in FQBN: %s"), err) + fmt.Fprintln(ctx.Stderr, &arduino.InvalidFQBNError{Cause: err}) } ctx.FQBN = fqbn ctx.ArduinoAPIVersion = opts.Get("runtime.ide.version") @@ -246,19 +246,28 @@ func (ctx *Context) InjectBuildOptions(opts *properties.Map) { ctx.OptimizationFlags = opts.Get("compiler.optimization_flags") } -func (ctx *Context) GetLogger() i18n.Logger { - if ctx.logger == nil { - return &i18n.HumanLogger{} +func (ctx *Context) PushProgress() { + if ctx.ProgressCB != nil { + ctx.ProgressCB(&rpc.TaskProgress{Percent: ctx.Progress.Progress}) } - return ctx.logger } -func (ctx *Context) SetLogger(l i18n.Logger) { - ctx.logger = l +func (ctx *Context) Info(msg string) { + ctx.stdLock.Lock() + if ctx.Stdout == nil { + fmt.Fprintln(os.Stdout, msg) + } else { + fmt.Fprintln(ctx.Stdout, msg) + } + ctx.stdLock.Unlock() } -func (ctx *Context) PushProgress() { - if ctx.ProgressCB != nil { - ctx.ProgressCB(&rpc.TaskProgress{Percent: ctx.Progress.Progress}) +func (ctx *Context) Warn(msg string) { + ctx.stdLock.Lock() + if ctx.Stderr == nil { + fmt.Fprintln(os.Stderr, msg) + } else { + fmt.Fprintln(ctx.Stderr, msg) } + ctx.stdLock.Unlock() } diff --git a/legacy/builder/types/types.go b/legacy/builder/types/types.go index c4e3625e599..70ee1c34608 100644 --- a/legacy/builder/types/types.go +++ b/legacy/builder/types/types.go @@ -21,12 +21,9 @@ import ( "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/arduino-cli/arduino/sketch" - "github.com/arduino/arduino-cli/i18n" paths "github.com/arduino/go-paths-helper" ) -var tr = i18n.Tr - type SourceFile struct { // Sketch or Library pointer that this source file lives in Origin interface{} diff --git a/legacy/builder/utils/utils.go b/legacy/builder/utils/utils.go index e8feb19ddf2..2f60ff75719 100644 --- a/legacy/builder/utils/utils.go +++ b/legacy/builder/utils/utils.go @@ -175,29 +175,29 @@ const ( ) func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int) ([]byte, []byte, error) { - if ctx.ExecStdout == nil { - ctx.ExecStdout = os.Stdout + if ctx.Stdout == nil { + ctx.Stdout = os.Stdout } - if ctx.ExecStderr == nil { - ctx.ExecStderr = os.Stderr + if ctx.Stderr == nil { + ctx.Stderr = os.Stderr } if ctx.Verbose { - ctx.GetLogger().Println("info", "{0}", PrintableCommand(command.Args)) + ctx.Info(PrintableCommand(command.Args)) } if stdout == Capture { buffer := &bytes.Buffer{} command.Stdout = buffer } else if stdout == Show || stdout == ShowIfVerbose && ctx.Verbose { - command.Stdout = ctx.ExecStdout + command.Stdout = ctx.Stdout } if stderr == Capture { buffer := &bytes.Buffer{} command.Stderr = buffer } else if stderr == Show || stderr == ShowIfVerbose && ctx.Verbose { - command.Stderr = ctx.ExecStderr + command.Stderr = ctx.Stderr } err := command.Start() @@ -317,20 +317,23 @@ func MD5Sum(data []byte) string { type loggerAction struct { onlyIfVerbose bool - level string - format string - args []interface{} + warn bool + msg string } func (l *loggerAction) Run(ctx *types.Context) error { if !l.onlyIfVerbose || ctx.Verbose { - ctx.GetLogger().Println(l.level, l.format, l.args...) + if l.warn { + ctx.Warn(l.msg) + } else { + ctx.Info(l.msg) + } } return nil } -func LogIfVerbose(level string, format string, args ...interface{}) types.Command { - return &loggerAction{true, level, format, args} +func LogIfVerbose(warn bool, msg string) types.Command { + return &loggerAction{onlyIfVerbose: true, warn: warn, msg: msg} } // Returns the given string as a quoted string for use with the C diff --git a/legacy/builder/warn_about_arch_incompatible_libraries.go b/legacy/builder/warn_about_arch_incompatible_libraries.go index 72103ae8afa..712f79b2fe5 100644 --- a/legacy/builder/warn_about_arch_incompatible_libraries.go +++ b/legacy/builder/warn_about_arch_incompatible_libraries.go @@ -16,7 +16,6 @@ package builder import ( - "os" "strings" "github.com/arduino/arduino-cli/legacy/builder/constants" @@ -26,13 +25,8 @@ import ( type WarnAboutArchIncompatibleLibraries struct{} func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { - if ctx.DebugLevel < 0 { - return nil - } - targetPlatform := ctx.TargetPlatform buildProperties := ctx.BuildProperties - logger := ctx.GetLogger() archs := []string{targetPlatform.Platform.Architecture} if overrides, ok := buildProperties.GetOk(constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK); ok { @@ -41,12 +35,11 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { for _, importedLibrary := range ctx.ImportedLibraries { if !importedLibrary.SupportsAnyArchitectureIn(archs...) { - logger.Fprintln(os.Stdout, - constants.LOG_LEVEL_WARN, - tr("WARNING: library {0} claims to run on {1} architecture(s) and may be incompatible with your current board which runs on {2} architecture(s)."), - importedLibrary.Name, - strings.Join(importedLibrary.Architectures, ", "), - strings.Join(archs, ", ")) + ctx.Info( + tr("WARNING: library %[1]s claims to run on %[2]s architecture(s) and may be incompatible with your current board which runs on %[3]s architecture(s).", + importedLibrary.Name, + strings.Join(importedLibrary.Architectures, ", "), + strings.Join(archs, ", "))) } } diff --git a/legacy/builder/warn_about_platform_rewrites.go b/legacy/builder/warn_about_platform_rewrites.go index edf19a5266f..6349ff9e276 100644 --- a/legacy/builder/warn_about_platform_rewrites.go +++ b/legacy/builder/warn_about_platform_rewrites.go @@ -16,8 +16,6 @@ package builder import ( - "os" - "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/arduino-cli/legacy/builder/constants" "github.com/arduino/arduino-cli/legacy/builder/types" @@ -26,11 +24,6 @@ import ( type WarnAboutPlatformRewrites struct{} func (s *WarnAboutPlatformRewrites) Run(ctx *types.Context) error { - if ctx.DebugLevel < 0 { - return nil - } - - logger := ctx.GetLogger() hardwareRewriteResults := ctx.HardwareRewriteResults targetPlatform := ctx.TargetPlatform actualPlatform := ctx.ActualPlatform @@ -43,11 +36,11 @@ func (s *WarnAboutPlatformRewrites) Run(ctx *types.Context) error { for _, platform := range platforms { if hardwareRewriteResults[platform] != nil { for _, rewrite := range hardwareRewriteResults[platform] { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, - tr("Warning: platform.txt from core '{0}' contains deprecated {1}, automatically converted to {2}. Consider upgrading this core."), - platform.Properties.Get(constants.PLATFORM_NAME), - rewrite.Key+"="+rewrite.OldValue, - rewrite.Key+"="+rewrite.NewValue) + ctx.Info( + tr("Warning: platform.txt from core '%[1]s' contains deprecated %[2]s, automatically converted to %[3]s. Consider upgrading this core.", + platform.Properties.Get(constants.PLATFORM_NAME), + rewrite.Key+"="+rewrite.OldValue, + rewrite.Key+"="+rewrite.NewValue)) } } } diff --git a/legacy/builder/wipeout_build_path_if_build_options_changed.go b/legacy/builder/wipeout_build_path_if_build_options_changed.go index c2263ac9591..44e5207a619 100644 --- a/legacy/builder/wipeout_build_path_if_build_options_changed.go +++ b/legacy/builder/wipeout_build_path_if_build_options_changed.go @@ -46,7 +46,7 @@ func (s *WipeoutBuildPathIfBuildOptionsChanged) Run(ctx *types.Context) error { var prevOpts *properties.Map if err := json.Unmarshal([]byte(previousBuildOptionsJson), &prevOpts); err != nil || prevOpts == nil { - ctx.GetLogger().Println(constants.LOG_LEVEL_DEBUG, tr("{0} invalid, rebuilding all"), constants.BUILD_OPTIONS_FILE) + ctx.Info(tr("%[1]s invalid, rebuilding all", constants.BUILD_OPTIONS_FILE)) return doCleanup(ctx.BuildPath) } diff --git a/test/test_compile_part_4.py b/test/test_compile_part_4.py index b3ad168ca1c..7cc22813634 100644 --- a/test/test_compile_part_4.py +++ b/test/test_compile_part_4.py @@ -110,8 +110,8 @@ def test_compile_with_library_priority(run_command, data_dir): cli_installed_lib_path = Path(data_dir, "libraries", "WiFi101") expected_output = [ 'Multiple libraries were found for "WiFi101.h"', - f" Used: {manually_install_lib_path}", - f" Not used: {cli_installed_lib_path}", + f" Used: {manually_install_lib_path}", + f" Not used: {cli_installed_lib_path}", ] assert "\n".join(expected_output) in res.stdout @@ -180,8 +180,8 @@ def test_compile_with_conflicting_libraries_include(run_command, data_dir, copy_ assert res.ok expected_output = [ 'Multiple libraries were found for "OneWire.h"', - f" Used: {one_wire_lib_path}", - f" Not used: {one_wire_ng_lib_path}", + f" Used: {one_wire_lib_path}", + f" Not used: {one_wire_ng_lib_path}", ] assert "\n".join(expected_output) in res.stdout @@ -245,8 +245,8 @@ def test_compile_with_esp32_bundled_libraries(run_command, data_dir, copy_sketch cli_installed_lib_path = Path(data_dir, "libraries", "SD") expected_output = [ 'Multiple libraries were found for "SD.h"', - f" Used: {core_bundled_lib_path}", - f" Not used: {cli_installed_lib_path}", + f" Used: {core_bundled_lib_path}", + f" Not used: {cli_installed_lib_path}", ] assert "\n".join(expected_output) not in res.stdout @@ -286,8 +286,8 @@ def test_compile_with_esp8266_bundled_libraries(run_command, data_dir, copy_sket cli_installed_lib_path = Path(data_dir, "libraries", "SD") expected_output = [ 'Multiple libraries were found for "SD.h"', - f" Used: {core_bundled_lib_path}", - f" Not used: {cli_installed_lib_path}", + f" Used: {core_bundled_lib_path}", + f" Not used: {cli_installed_lib_path}", ] assert "\n".join(expected_output) not in res.stdout