From dd4da02c7d1ad8ce2ec15f77b7055b4aad8501d8 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 9 Mar 2018 09:13:19 +0100 Subject: [PATCH 01/57] fixed Preprocess container --- print_preprocessed_source.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/print_preprocessed_source.go b/print_preprocessed_source.go index c6afae14..ecf52a7d 100644 --- a/print_preprocessed_source.go +++ b/print_preprocessed_source.go @@ -30,13 +30,14 @@ package builder import ( - "github.com/arduino/arduino-builder/types" "fmt" + + "github.com/arduino/arduino-builder/types" ) type PrintPreprocessedSource struct{} func (s *PrintPreprocessedSource) Run(ctx *types.Context) error { - fmt.Println(ctx.SourceGccMinusE) + fmt.Println(ctx.Source) return nil } From 0b0988e046284bfce0946eb2bb77335abc2eacc3 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 26 Feb 2018 16:19:44 +0100 Subject: [PATCH 02/57] cli: use types from arduino-cli cores --- add_additional_entries_to_context.go | 5 +- add_build_board_property_if_missing.go | 22 ++++-- ...operties_from_parent_platform_txt_files.go | 4 +- hardware_loader.go | 68 +++++++++------- resolve_library.go | 11 +-- rewrite_hardware_keys.go | 19 +++-- setup_build_properties.go | 7 +- target_board_resolver.go | 20 ++--- .../add_additional_entries_to_context_test.go | 5 +- ...dd_build_board_property_if_missing_test.go | 15 ++-- test/hardware_loader_test.go | 77 ++++++++++--------- test/rewrite_hardware_keys_test.go | 59 +++++++++----- test/target_board_resolver_test.go | 29 +++---- types/context.go | 13 ++-- types/types.go | 25 ------ warn_about_arch_incompatible_libraries.go | 7 +- warn_about_platform_rewrites.go | 6 +- 17 files changed, 212 insertions(+), 180 deletions(-) diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index 3d6f1fa1..49fb0113 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -35,6 +35,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" + "github.com/bcmi-labs/arduino-cli/cores" ) type AddAdditionalEntriesToContext struct{} @@ -80,8 +81,8 @@ func (s *AddAdditionalEntriesToContext) Run(ctx *types.Context) error { ctx.CollectedSourceFiles = &types.UniqueSourceFileQueue{} - ctx.LibrariesResolutionResults = make(map[string]types.LibraryResolutionResult) - ctx.HardwareRewriteResults = make(map[*types.Platform][]types.PlatforKeyRewrite) + ctx.LibrariesResolutionResults = map[string]types.LibraryResolutionResult{} + ctx.HardwareRewriteResults = map[*cores.PlatformRelease][]types.PlatforKeyRewrite{} return nil } diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go index 93c06c85..38c64802 100644 --- a/add_build_board_property_if_missing.go +++ b/add_build_board_property_if_missing.go @@ -30,10 +30,11 @@ package builder import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" "os" "strings" + + "github.com/arduino/arduino-builder/constants" + "github.com/arduino/arduino-builder/types" ) type AddBuildBoardPropertyIfMissing struct{} @@ -44,10 +45,19 @@ func (s *AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { for _, aPackage := range packages.Packages { for _, platform := range aPackage.Platforms { - for _, board := range platform.Boards { - if board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] == constants.EMPTY_STRING { - board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD] = strings.ToUpper(platform.PlatformId + "_" + board.BoardId) - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_MISSING_BUILD_BOARD, aPackage.PackageId, platform.PlatformId, board.BoardId, board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + for _, platformRelease := range platform.Releases { + for _, board := range platformRelease.Boards { + if board.Properties["build.board"] == "" { + board.Properties["build.board"] = strings.ToUpper(platform.Architecture + "_" + board.BoardId) + logger.Fprintln( + os.Stdout, + constants.LOG_LEVEL_WARN, + constants.MSG_MISSING_BUILD_BOARD, + aPackage.Name, + platform.Architecture, + board.BoardId, + board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + } } } } diff --git a/add_missing_build_properties_from_parent_platform_txt_files.go b/add_missing_build_properties_from_parent_platform_txt_files.go index 558aa820..a6be7bdd 100644 --- a/add_missing_build_properties_from_parent_platform_txt_files.go +++ b/add_missing_build_properties_from_parent_platform_txt_files.go @@ -37,11 +37,11 @@ type AddMissingBuildPropertiesFromParentPlatformTxtFiles struct{} func (s *AddMissingBuildPropertiesFromParentPlatformTxtFiles) Run(ctx *types.Context) error { packages := ctx.Hardware - targetPackage := ctx.TargetPackage + // targetPackage := ctx.TargetPackage buildProperties := ctx.BuildProperties newBuildProperties := packages.Properties.Clone() - newBuildProperties.Merge(targetPackage.Properties) + // newBuildProperties.Merge(targetPackage.Properties) newBuildProperties.Merge(buildProperties) ctx.BuildProperties = newBuildProperties diff --git a/hardware_loader.go b/hardware_loader.go index 321e9d48..37b23598 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -38,6 +38,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/cores" ) type HardwareLoader struct{} @@ -45,9 +46,10 @@ type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { logger := ctx.GetLogger() - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - packages.Properties = make(map[string]string) + packages := &cores.Packages{ + Packages: map[string]*cores.Package{}, + Properties: properties.Map{}, + } folders := ctx.HardwareFolders folders, err := utils.AbsolutizePaths(folders) @@ -98,25 +100,26 @@ func (s *HardwareLoader) Run(ctx *types.Context) error { return nil } -func getOrCreatePackage(packages *types.Packages, packageId string) *types.Package { +func getOrCreatePackage(packages *cores.Packages, packageId string) *cores.Package { if _, ok := packages.Packages[packageId]; ok { return packages.Packages[packageId] } - targetPackage := types.Package{} - targetPackage.PackageId = packageId - targetPackage.Platforms = make(map[string]*types.Platform) - targetPackage.Properties = make(map[string]string) + targetPackage := cores.Package{} + targetPackage.Name = packageId + targetPackage.Platforms = map[string]*cores.Platform{} + targetPackage.Packages = packages + // targetPackage.Properties = properties.Map{} return &targetPackage } -func loadPackage(targetPackage *types.Package, folder string) error { - packagePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - targetPackage.Properties.Merge(packagePlatformTxt) +func loadPackage(targetPackage *cores.Package, folder string) error { + // packagePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) + // if err != nil { + // return i18n.WrapError(err) + // } + // targetPackage.Properties.Merge(packagePlatformTxt) subfolders, err := utils.ReadDirFiltered(folder, utils.FilterDirs) if err != nil { @@ -143,7 +146,7 @@ func loadPackage(targetPackage *types.Package, folder string) error { } platform := getOrCreatePlatform(platforms, platformId) - err = loadPlatform(platform, subfolderPath) + err = loadPlatform(platform.Releases[""], subfolderPath) if err != nil { return i18n.WrapError(err) } @@ -153,21 +156,27 @@ func loadPackage(targetPackage *types.Package, folder string) error { return nil } -func getOrCreatePlatform(platforms map[string]*types.Platform, platformId string) *types.Platform { +func getOrCreatePlatform(platforms map[string]*cores.Platform, platformId string) *cores.Platform { if _, ok := platforms[platformId]; ok { return platforms[platformId] } - targetPlatform := types.Platform{} - targetPlatform.PlatformId = platformId - targetPlatform.Boards = make(map[string]*types.Board) - targetPlatform.Properties = make(map[string]string) - targetPlatform.Programmers = make(map[string]properties.Map) + targetPlatform := &cores.Platform{ + Architecture: platformId, + Releases: map[string]*cores.PlatformRelease{}, + } + release := &cores.PlatformRelease{ + Boards: map[string]*cores.Board{}, + Properties: properties.Map{}, + Programmers: map[string]properties.Map{}, + Platform: targetPlatform, + } + targetPlatform.Releases[""] = release - return &targetPlatform + return targetPlatform } -func loadPlatform(targetPlatform *types.Platform, folder string) error { +func loadPlatform(targetPlatform *cores.PlatformRelease, folder string) error { _, err := os.Stat(filepath.Join(folder, constants.FILE_BOARDS_TXT)) if err != nil && !os.IsNotExist(err) { return i18n.WrapError(err) @@ -202,12 +211,15 @@ func loadPlatform(targetPlatform *types.Platform, folder string) error { if err != nil { return i18n.WrapError(err) } - targetPlatform.Programmers = properties.MergeMapsOfProperties(make(map[string]properties.Map), targetPlatform.Programmers, programmersProperties.FirstLevelOf()) + targetPlatform.Programmers = properties.MergeMapsOfProperties( + map[string]properties.Map{}, + targetPlatform.Programmers, + programmersProperties.FirstLevelOf()) return nil } -func loadBoards(boards map[string]*types.Board, folder string) error { +func loadBoards(boards map[string]*cores.Board, folder string) error { boardsProperties, err := properties.Load(filepath.Join(folder, constants.FILE_BOARDS_TXT)) if err != nil { return i18n.WrapError(err) @@ -233,14 +245,14 @@ func loadBoards(boards map[string]*types.Board, folder string) error { return nil } -func getOrCreateBoard(boards map[string]*types.Board, boardId string) *types.Board { +func getOrCreateBoard(boards map[string]*cores.Board, boardId string) *cores.Board { if _, ok := boards[boardId]; ok { return boards[boardId] } - board := types.Board{} + board := cores.Board{} board.BoardId = boardId - board.Properties = make(properties.Map) + board.Properties = properties.Map{} return &board } diff --git a/resolve_library.go b/resolve_library.go index dd96ab75..488fc1d3 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -36,11 +36,12 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/bcmi-labs/arduino-cli/cores" ) func ResolveLibrary(ctx *types.Context, header string) *types.Library { headerToLibraries := ctx.HeaderToLibraries - platforms := []*types.Platform{ctx.ActualPlatform, ctx.TargetPlatform} + platforms := []*cores.PlatformRelease{ctx.ActualPlatform, ctx.TargetPlatform} libraryResolutionResults := ctx.LibrariesResolutionResults importedLibraries := ctx.ImportedLibraries @@ -138,14 +139,14 @@ func findLibraryIn(libraries []*types.Library, library *types.Library) *types.Li return nil } -func libraryCompatibleWithPlatform(library *types.Library, platform *types.Platform) (bool, bool) { +func libraryCompatibleWithPlatform(library *types.Library, platform *cores.PlatformRelease) (bool, bool) { if len(library.Archs) == 0 { return true, true } if utils.SliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { return true, true } - return utils.SliceContains(library.Archs, platform.PlatformId), false + return utils.SliceContains(library.Archs, platform.Platform.Architecture), false } func libraryCompatibleWithAllPlatforms(library *types.Library) bool { @@ -155,7 +156,7 @@ func libraryCompatibleWithAllPlatforms(library *types.Library) bool { return false } -func librariesCompatibleWithPlatform(libraries []*types.Library, platform *types.Platform, reorder bool) []*types.Library { +func librariesCompatibleWithPlatform(libraries []*types.Library, platform *cores.PlatformRelease, reorder bool) []*types.Library { var compatibleLibraries []*types.Library for _, library := range libraries { compatible, generic := libraryCompatibleWithPlatform(library, platform) @@ -172,7 +173,7 @@ func librariesCompatibleWithPlatform(libraries []*types.Library, platform *types return compatibleLibraries } -func librariesWithinPlatform(libraries []*types.Library, platform *types.Platform) []*types.Library { +func librariesWithinPlatform(libraries []*types.Library, platform *cores.PlatformRelease) []*types.Library { librariesWithinSpecifiedPlatform := []*types.Library{} for _, library := range libraries { cleanPlatformFolder := filepath.Clean(platform.Folder) diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go index 97f7aef4..be5cfa53 100644 --- a/rewrite_hardware_keys.go +++ b/rewrite_hardware_keys.go @@ -32,6 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + "github.com/bcmi-labs/arduino-cli/cores" ) type RewriteHardwareKeys struct{} @@ -47,13 +48,15 @@ func (s *RewriteHardwareKeys) Run(ctx *types.Context) error { for _, aPackage := range packages.Packages { for _, platform := range aPackage.Platforms { - if platform.Properties[constants.REWRITING] != constants.REWRITING_DISABLED { - for _, rewrite := range platformKeysRewrite.Rewrites { - if platform.Properties[rewrite.Key] != constants.EMPTY_STRING && platform.Properties[rewrite.Key] == rewrite.OldValue { - platform.Properties[rewrite.Key] = rewrite.NewValue - appliedRewrites := rewritesAppliedToPlatform(platform, hardwareRewriteResults) - appliedRewrites = append(appliedRewrites, rewrite) - hardwareRewriteResults[platform] = appliedRewrites + for _, platformRelease := range platform.Releases { + if platformRelease.Properties[constants.REWRITING] != constants.REWRITING_DISABLED { + for _, rewrite := range platformKeysRewrite.Rewrites { + if platformRelease.Properties[rewrite.Key] != "" && platformRelease.Properties[rewrite.Key] == rewrite.OldValue { + platformRelease.Properties[rewrite.Key] = rewrite.NewValue + appliedRewrites := rewritesAppliedToPlatform(platformRelease, hardwareRewriteResults) + appliedRewrites = append(appliedRewrites, rewrite) + hardwareRewriteResults[platformRelease] = appliedRewrites + } } } } @@ -63,7 +66,7 @@ func (s *RewriteHardwareKeys) Run(ctx *types.Context) error { return nil } -func rewritesAppliedToPlatform(platform *types.Platform, hardwareRewriteResults map[*types.Platform][]types.PlatforKeyRewrite) []types.PlatforKeyRewrite { +func rewritesAppliedToPlatform(platform *cores.PlatformRelease, hardwareRewriteResults map[*cores.PlatformRelease][]types.PlatforKeyRewrite) []types.PlatforKeyRewrite { if hardwareRewriteResults[platform] == nil { hardwareRewriteResults[platform] = []types.PlatforKeyRewrite{} } diff --git a/setup_build_properties.go b/setup_build_properties.go index b18d643a..a07bdf10 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -40,6 +40,7 @@ import ( "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" "github.com/arduino/go-timeutils" + "github.com/bcmi-labs/arduino-cli/cores" ) type SetupBuildProperties struct{} @@ -62,7 +63,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { if ctx.Sketch != nil { buildProperties[constants.BUILD_PROPERTIES_BUILD_PROJECT_NAME] = filepath.Base(ctx.Sketch.MainFile.Name) } - buildProperties[constants.BUILD_PROPERTIES_BUILD_ARCH] = strings.ToUpper(targetPlatform.PlatformId) + buildProperties[constants.BUILD_PROPERTIES_BUILD_ARCH] = strings.ToUpper(targetPlatform.Platform.Architecture) buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE] = ctx.BuildCore buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] = filepath.Join(actualPlatform.Folder, constants.FOLDER_CORES, buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE]) @@ -78,10 +79,10 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { if variant == constants.EMPTY_STRING { buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] = constants.EMPTY_STRING } else { - var variantPlatform *types.Platform + var variantPlatform *cores.PlatformRelease variantParts := strings.Split(variant, ":") if len(variantParts) > 1 { - variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.PlatformId] + variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture].Releases[""] variant = variantParts[1] } else { variantPlatform = targetPlatform diff --git a/target_board_resolver.go b/target_board_resolver.go index 4c6d15e0..2090a2d6 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -30,11 +30,13 @@ package builder import ( + "strings" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "strings" + "github.com/bcmi-labs/arduino-cli/cores" ) type TargetBoardResolver struct{} @@ -64,13 +66,13 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) } - targetBoard := targetPlatform.Boards[targetBoardName] + targetBoard := targetPlatform.Releases[""].Boards[targetBoardName] if targetBoard == nil { return i18n.ErrorfWithLogger(logger, constants.MSG_BOARD_UNKNOWN, targetBoardName, targetPlatformName, targetPackageName) } ctx.TargetPackage = targetPackage - ctx.TargetPlatform = targetPlatform + ctx.TargetPlatform = targetPlatform.Releases[""] ctx.TargetBoard = targetBoard if len(fqbnParts) > 3 { @@ -82,7 +84,7 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { core = DEFAULT_BUILD_CORE } - var corePlatform *types.Platform + var corePlatform *cores.PlatformRelease coreParts := strings.Split(core, ":") if len(coreParts) > 1 { core = coreParts[1] @@ -90,18 +92,18 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_MISSING_CORE_FOR_BOARD, coreParts[0]) } - corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatform.PlatformId] + corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatform.Architecture].Releases[""] } - var actualPlatform *types.Platform + var actualPlatform *cores.PlatformRelease if corePlatform != nil { actualPlatform = corePlatform } else { - actualPlatform = targetPlatform + actualPlatform = targetPlatform.Releases[""] } if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Folder) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Releases[""].Folder) logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.Folder) } @@ -111,7 +113,7 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return nil } -func addAdditionalPropertiesToTargetBoard(board *types.Board, options string) { +func addAdditionalPropertiesToTargetBoard(board *cores.Board, options string) { optionsParts := strings.Split(options, ",") optionsParts = utils.Map(optionsParts, utils.TrimSpace) diff --git a/test/add_additional_entries_to_context_test.go b/test/add_additional_entries_to_context_test.go index daf31135..b85187ed 100644 --- a/test/add_additional_entries_to_context_test.go +++ b/test/add_additional_entries_to_context_test.go @@ -30,12 +30,13 @@ package test import ( + "path/filepath" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" - "path/filepath" - "testing" ) func TestAddAdditionalEntriesToContextNoBuildPath(t *testing.T) { diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index 34f74b51..e6cfb680 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -30,12 +30,13 @@ package test import ( + "path/filepath" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" - "path/filepath" - "testing" ) func TestAddBuildBoardPropertyIfMissing(t *testing.T) { @@ -58,9 +59,11 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) + require.Equal(t, "my_avr_platform", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.NotNil(t, targetPlatform) + require.NotNil(t, targetPlatform.Platform) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardId) require.Equal(t, constants.EMPTY_STRING, targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -87,9 +90,9 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) + require.Equal(t, "my_avr_platform", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardId) require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index 147396e7..9521b46c 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -30,14 +30,15 @@ package test import ( + "path/filepath" + "runtime" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/stretchr/testify/require" - "path/filepath" - "runtime" - "testing" ) func TestLoadHardware(t *testing.T) { @@ -59,29 +60,29 @@ func TestLoadHardware(t *testing.T) { require.NotNil(t, packages.Packages["arduino"]) require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].Properties[constants.ID]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties[constants.ID]) - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].BoardId) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].Properties["upload.wait_for_upload_port"]) + require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) + require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Boards["robotMotor"].Properties["build.extra_flags"]) + require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Boards["arduino_due_x"].BoardId) + require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardId) - require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Boards["diecimila"].Properties["menu.cpu.atmega123"]) + require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties["menu.cpu.atmega123"]) avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties[constants.PLATFORM_NAME]) - require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) + require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties[constants.PLATFORM_NAME]) + require.Equal(t, "-v", avrPlatform.Releases[""].Properties["tools.avrdude.bootloader.params.verbose"]) + require.Equal(t, "/my/personal/avrdude", avrPlatform.Releases[""].Properties["tools.avrdude.cmd.path"]) - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) + require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) - require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) + //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) + //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) + //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) + //require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) } func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { @@ -113,17 +114,17 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.NotNil(t, packages.Packages["arduino"]) require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Boards["uno"].Properties[constants.ID]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties[constants.ID]) - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].BoardId) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Boards["yun"].Properties["upload.wait_for_upload_port"]) + require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) + require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Boards["robotMotor"].Properties["build.extra_flags"]) + require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Boards["arduino_due_x"].BoardId) + require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardId) - avrPlatform := packages.Packages["arduino"].Platforms["avr"] + avrPlatform := packages.Packages["arduino"].Platforms["avr"].Releases[""] require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties[constants.PLATFORM_NAME]) require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) @@ -137,16 +138,16 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.NotNil(t, packages.Packages["my_avr_platform"]) myAVRPlatform := packages.Packages["my_avr_platform"] - require.Equal(t, "hello world", myAVRPlatform.Properties["example"]) - myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"] + //require.Equal(t, "hello world", myAVRPlatform.Properties["example"]) + myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"].Releases[""] require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardId) require.False(t, utils.MapStringStringHas(myAVRPlatformAvrArch.Properties, "preproc.includes.flags")) - require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) + //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) + //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) + //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) + //require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) if runtime.GOOS != "windows" { require.NotNil(t, packages.Packages["my_symlinked_avr_platform"]) @@ -177,7 +178,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.NotNil(t, packages.Packages["RFduino"]) require.Equal(t, 0, len(packages.Packages["RFduino"].Platforms)) - samdPlatform := packages.Packages["arduino"].Platforms["samd"] + samdPlatform := packages.Packages["arduino"].Platforms["samd"].Releases[""] require.Equal(t, 3, len(samdPlatform.Boards)) require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardId) @@ -194,7 +195,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"][constants.PROGRAMMER_NAME]) require.Equal(t, "openocd", samdPlatform.Programmers["edbg"]["program.tool"]) - avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"] + avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases[""] require.Equal(t, 3, len(avrRedBearPlatform.Boards)) require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardId) @@ -229,15 +230,15 @@ func TestLoadLotsOfHardware(t *testing.T) { require.NotNil(t, packages.Packages["my_avr_platform"]) require.Equal(t, 3, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, 20, len(packages.Packages["arduino"].Platforms["avr"].Boards)) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms["sam"].Boards)) - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Boards)) + require.Equal(t, 20, len(packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards)) + require.Equal(t, 2, len(packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards)) + require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Releases[""].Boards)) require.Equal(t, 1, len(packages.Packages["my_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_avr_platform"].Platforms["avr"].Boards)) + require.Equal(t, 2, len(packages.Packages["my_avr_platform"].Platforms["avr"].Releases[""].Boards)) if runtime.GOOS != "windows" { require.Equal(t, 1, len(packages.Packages["my_symlinked_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_symlinked_avr_platform"].Platforms["avr"].Boards)) + require.Equal(t, 2, len(packages.Packages["my_symlinked_avr_platform"].Platforms["avr"].Releases[""].Boards)) } } diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go index 76829e0f..dc78dddd 100644 --- a/test/rewrite_hardware_keys_test.go +++ b/test/rewrite_hardware_keys_test.go @@ -30,27 +30,37 @@ package test import ( + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + properties "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/cores" "github.com/stretchr/testify/require" - "testing" ) func TestRewriteHardwareKeys(t *testing.T) { ctx := &types.Context{} - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - aPackage := &types.Package{PackageId: "dummy"} + packages := &cores.Packages{} + packages.Packages = map[string]*cores.Package{} + aPackage := &cores.Package{Name: "dummy"} packages.Packages["dummy"] = aPackage - aPackage.Platforms = make(map[string]*types.Platform) + aPackage.Platforms = map[string]*cores.Platform{} - platform := &types.Platform{PlatformId: "dummy"} - aPackage.Platforms["dummy"] = platform - platform.Properties = make(map[string]string) - platform.Properties[constants.PLATFORM_NAME] = "A test platform" - platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH] = "{runtime.ide.path}/hardware/tools/avr/bin/" + platform := &cores.PlatformRelease{ + Properties: properties.Map{ + constants.PLATFORM_NAME: "A test platform", + constants.BUILD_PROPERTIES_COMPILER_PATH: "{runtime.ide.path}/hardware/tools/avr/bin/", + }, + } + aPackage.Platforms["dummy"] = &cores.Platform{ + Architecture: "dummy", + Releases: map[string]*cores.PlatformRelease{ + "": platform, + }, + } ctx.Hardware = packages @@ -74,18 +84,25 @@ func TestRewriteHardwareKeys(t *testing.T) { func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { ctx := &types.Context{} - packages := &types.Packages{} - packages.Packages = make(map[string]*types.Package) - aPackage := &types.Package{PackageId: "dummy"} + packages := &cores.Packages{} + packages.Packages = make(map[string]*cores.Package) + aPackage := &cores.Package{Name: "dummy"} packages.Packages["dummy"] = aPackage - aPackage.Platforms = make(map[string]*types.Platform) - - platform := &types.Platform{PlatformId: "dummy"} - aPackage.Platforms["dummy"] = platform - platform.Properties = make(map[string]string) - platform.Properties[constants.PLATFORM_NAME] = "A test platform" - platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH] = "{runtime.ide.path}/hardware/tools/avr/bin/" - platform.Properties[constants.REWRITING] = constants.REWRITING_DISABLED + aPackage.Platforms = make(map[string]*cores.Platform) + + platform := &cores.PlatformRelease{ + Properties: properties.Map{ + constants.PLATFORM_NAME: "A test platform", + constants.BUILD_PROPERTIES_COMPILER_PATH: "{runtime.ide.path}/hardware/tools/avr/bin/", + constants.REWRITING: constants.REWRITING_DISABLED, + }, + } + aPackage.Platforms["dummy"] = &cores.Platform{ + Architecture: "dummy", + Releases: map[string]*cores.PlatformRelease{ + "": platform, + }, + } ctx.Hardware = packages diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index 49e0abea..337c7416 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -30,12 +30,13 @@ package test import ( + "path/filepath" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" - "path/filepath" - "testing" ) func TestTargetBoardResolverUno(t *testing.T) { @@ -55,9 +56,9 @@ func TestTargetBoardResolverUno(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) + require.Equal(t, "arduino", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "uno", targetBoard.BoardId) require.Equal(t, "atmega328p", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -80,9 +81,9 @@ func TestTargetBoardResolverDue(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) + require.Equal(t, "arduino", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "sam", targetPlatform.PlatformId) + require.Equal(t, "sam", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "arduino_due_x", targetBoard.BoardId) require.Equal(t, "cortex-m3", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -105,9 +106,9 @@ func TestTargetBoardResolverMega1280(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) + require.Equal(t, "arduino", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardId) require.Equal(t, "atmega1280", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -131,9 +132,9 @@ func TestTargetBoardResolverMega2560(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.PackageId) + require.Equal(t, "arduino", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardId) require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -157,9 +158,9 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.PackageId) + require.Equal(t, "my_avr_platform", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "custom_yun", targetBoard.BoardId) require.Equal(t, "atmega32u4", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) @@ -183,9 +184,9 @@ func TestTargetBoardResolverCustomCore(t *testing.T) { } targetPackage := ctx.TargetPackage - require.Equal(t, "watterott", targetPackage.PackageId) + require.Equal(t, "watterott", targetPackage.Name) targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.PlatformId) + require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "attiny841", targetBoard.BoardId) require.Equal(t, "tiny841", ctx.BuildCore) diff --git a/types/context.go b/types/context.go index bc9491dd..bf772913 100644 --- a/types/context.go +++ b/types/context.go @@ -5,6 +5,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/cores" ) // Context structure @@ -23,16 +24,16 @@ type Context struct { BuildOptionsJson string BuildOptionsJsonPrevious string - Hardware *Packages + Hardware *cores.Packages Tools []*Tool - TargetBoard *Board - TargetPackage *Package - TargetPlatform *Platform - ActualPlatform *Platform + TargetBoard *cores.Board + TargetPackage *cores.Package + TargetPlatform *cores.PlatformRelease + ActualPlatform *cores.PlatformRelease USBVidPid string PlatformKeyRewrites PlatforKeysRewrite - HardwareRewriteResults map[*Platform][]PlatforKeyRewrite + HardwareRewriteResults map[*cores.PlatformRelease][]PlatforKeyRewrite BuildProperties properties.Map BuildCore string diff --git a/types/types.go b/types/types.go index d535386d..4561a3b1 100644 --- a/types/types.go +++ b/types/types.go @@ -35,7 +35,6 @@ import ( "strconv" "github.com/arduino/arduino-builder/constants" - "github.com/arduino/go-properties-map" ) type SourceFile struct { @@ -124,30 +123,6 @@ type Sketch struct { AdditionalFiles []SketchFile } -type Packages struct { - Properties properties.Map - Packages map[string]*Package -} - -type Package struct { - PackageId string - Properties properties.Map - Platforms map[string]*Platform -} - -type Platform struct { - PlatformId string - Folder string - Boards map[string]*Board - Properties properties.Map - Programmers map[string]properties.Map -} - -type Board struct { - BoardId string - Properties properties.Map -} - type Tool struct { Name string Version string diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go index 8d320717..c599fe28 100644 --- a/warn_about_arch_incompatible_libraries.go +++ b/warn_about_arch_incompatible_libraries.go @@ -30,10 +30,11 @@ package builder import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" "os" "strings" + + "github.com/arduino/arduino-builder/constants" + "github.com/arduino/arduino-builder/types" ) type WarnAboutArchIncompatibleLibraries struct{} @@ -48,7 +49,7 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { logger := ctx.GetLogger() archs := []string{} - archs = append(archs, targetPlatform.PlatformId) + archs = append(archs, targetPlatform.Platform.Architecture) if buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK] != constants.EMPTY_STRING { overrides := strings.Split(buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK], ",") diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go index 247e0256..15ca5cc5 100644 --- a/warn_about_platform_rewrites.go +++ b/warn_about_platform_rewrites.go @@ -30,9 +30,11 @@ package builder import ( + "os" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "os" + "github.com/bcmi-labs/arduino-cli/cores" ) type WarnAboutPlatformRewrites struct{} @@ -47,7 +49,7 @@ func (s *WarnAboutPlatformRewrites) Run(ctx *types.Context) error { targetPlatform := ctx.TargetPlatform actualPlatform := ctx.ActualPlatform - platforms := []*types.Platform{targetPlatform} + platforms := []*cores.PlatformRelease{targetPlatform} if actualPlatform != targetPlatform { platforms = append(platforms, actualPlatform) } From cc7d3f21576dec5e9cc3cb6ef66b6076d4083f2f Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 28 Feb 2018 11:33:08 +0100 Subject: [PATCH 03/57] Moved HardwareLoader logic into arduino-cli Access to PlatformRelease is now done through the Platform.GetInstalled() method that returns the installed PlatformRelease (or any of them if more than one is installed). --- hardware_loader.go | 207 +---------------------------------- setup_build_properties.go | 2 +- target_board_resolver.go | 16 ++- test/hardware_loader_test.go | 6 +- 4 files changed, 15 insertions(+), 216 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index 37b23598..5065d256 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -30,13 +30,8 @@ package builder import ( - "os" - "path/filepath" - - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/cores" ) @@ -44,215 +39,15 @@ import ( type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - packages := &cores.Packages{ Packages: map[string]*cores.Package{}, Properties: properties.Map{}, } folders := ctx.HardwareFolders - folders, err := utils.AbsolutizePaths(folders) - if err != nil { + if err := packages.LoadHardwareFromFolders(folders); err != nil { return i18n.WrapError(err) } - - for _, folder := range folders { - stat, err := os.Stat(folder) - if err != nil { - return i18n.WrapError(err) - } - if !stat.IsDir() { - return i18n.ErrorfWithLogger(logger, constants.MSG_MUST_BE_A_FOLDER, folder) - } - - hardwarePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - packages.Properties.Merge(hardwarePlatformTxt) - - subfolders, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - subfolders = utils.FilterOutFoldersByNames(subfolders, constants.FOLDER_TOOLS) - - for _, subfolder := range subfolders { - subfolderPath := filepath.Join(folder, subfolder.Name()) - packageId := subfolder.Name() - - if _, err := os.Stat(filepath.Join(subfolderPath, constants.FOLDER_HARDWARE)); err == nil { - subfolderPath = filepath.Join(subfolderPath, constants.FOLDER_HARDWARE) - } - - targetPackage := getOrCreatePackage(packages, packageId) - err = loadPackage(targetPackage, subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - packages.Packages[packageId] = targetPackage - } - } - ctx.Hardware = packages - - return nil -} - -func getOrCreatePackage(packages *cores.Packages, packageId string) *cores.Package { - if _, ok := packages.Packages[packageId]; ok { - return packages.Packages[packageId] - } - - targetPackage := cores.Package{} - targetPackage.Name = packageId - targetPackage.Platforms = map[string]*cores.Platform{} - targetPackage.Packages = packages - // targetPackage.Properties = properties.Map{} - - return &targetPackage -} - -func loadPackage(targetPackage *cores.Package, folder string) error { - // packagePlatformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - // if err != nil { - // return i18n.WrapError(err) - // } - // targetPackage.Properties.Merge(packagePlatformTxt) - - subfolders, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - - subfolders = utils.FilterOutFoldersByNames(subfolders, constants.FOLDER_TOOLS) - - platforms := targetPackage.Platforms - for _, subfolder := range subfolders { - subfolderPath := filepath.Join(folder, subfolder.Name()) - platformId := subfolder.Name() - - _, err := os.Stat(filepath.Join(subfolderPath, constants.FILE_BOARDS_TXT)) - if err != nil && os.IsNotExist(err) { - theOnlySubfolder, err := utils.TheOnlySubfolderOf(subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - - if theOnlySubfolder != constants.EMPTY_STRING { - subfolderPath = filepath.Join(subfolderPath, theOnlySubfolder) - } - } - - platform := getOrCreatePlatform(platforms, platformId) - err = loadPlatform(platform.Releases[""], subfolderPath) - if err != nil { - return i18n.WrapError(err) - } - platforms[platformId] = platform - } - - return nil -} - -func getOrCreatePlatform(platforms map[string]*cores.Platform, platformId string) *cores.Platform { - if _, ok := platforms[platformId]; ok { - return platforms[platformId] - } - - targetPlatform := &cores.Platform{ - Architecture: platformId, - Releases: map[string]*cores.PlatformRelease{}, - } - release := &cores.PlatformRelease{ - Boards: map[string]*cores.Board{}, - Properties: properties.Map{}, - Programmers: map[string]properties.Map{}, - Platform: targetPlatform, - } - targetPlatform.Releases[""] = release - - return targetPlatform -} - -func loadPlatform(targetPlatform *cores.PlatformRelease, folder string) error { - _, err := os.Stat(filepath.Join(folder, constants.FILE_BOARDS_TXT)) - if err != nil && !os.IsNotExist(err) { - return i18n.WrapError(err) - } - - if os.IsNotExist(err) { - return nil - } - - targetPlatform.Folder = folder - - err = loadBoards(targetPlatform.Boards, folder) - if err != nil { - return i18n.WrapError(err) - } - - platformTxt, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - localPlatformProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PLATFORM_LOCAL_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - targetPlatform.Properties = targetPlatform.Properties.Clone() - targetPlatform.Properties.Merge(platformTxt) - targetPlatform.Properties.Merge(localPlatformProperties) - - programmersProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_PROGRAMMERS_TXT)) - if err != nil { - return i18n.WrapError(err) - } - targetPlatform.Programmers = properties.MergeMapsOfProperties( - map[string]properties.Map{}, - targetPlatform.Programmers, - programmersProperties.FirstLevelOf()) - return nil } - -func loadBoards(boards map[string]*cores.Board, folder string) error { - boardsProperties, err := properties.Load(filepath.Join(folder, constants.FILE_BOARDS_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - localProperties, err := properties.SafeLoad(filepath.Join(folder, constants.FILE_BOARDS_LOCAL_TXT)) - if err != nil { - return i18n.WrapError(err) - } - - boardsProperties = boardsProperties.Merge(localProperties) - - propertiesByBoardId := boardsProperties.FirstLevelOf() - delete(propertiesByBoardId, constants.BOARD_PROPERTIES_MENU) - - for boardID, boardProperties := range propertiesByBoardId { - boardProperties[constants.ID] = boardID - board := getOrCreateBoard(boards, boardID) - board.Properties.Merge(boardProperties) - boards[boardID] = board - } - - return nil -} - -func getOrCreateBoard(boards map[string]*cores.Board, boardId string) *cores.Board { - if _, ok := boards[boardId]; ok { - return boards[boardId] - } - - board := cores.Board{} - board.BoardId = boardId - board.Properties = properties.Map{} - - return &board -} diff --git a/setup_build_properties.go b/setup_build_properties.go index a07bdf10..9e2f1d15 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -82,7 +82,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { var variantPlatform *cores.PlatformRelease variantParts := strings.Split(variant, ":") if len(variantParts) > 1 { - variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture].Releases[""] + variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture].GetInstalled() variant = variantParts[1] } else { variantPlatform = targetPlatform diff --git a/target_board_resolver.go b/target_board_resolver.go index 2090a2d6..4df79ef0 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -61,18 +61,22 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_PACKAGE_UNKNOWN, targetPackageName) } - targetPlatform := targetPackage.Platforms[targetPlatformName] + targetPlatforms := targetPackage.Platforms[targetPlatformName] + if targetPlatforms == nil { + return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) + } + targetPlatform := targetPlatforms.GetInstalled() if targetPlatform == nil { return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) } - targetBoard := targetPlatform.Releases[""].Boards[targetBoardName] + targetBoard := targetPlatform.Boards[targetBoardName] if targetBoard == nil { return i18n.ErrorfWithLogger(logger, constants.MSG_BOARD_UNKNOWN, targetBoardName, targetPlatformName, targetPackageName) } + ctx.TargetPlatform = targetPlatform ctx.TargetPackage = targetPackage - ctx.TargetPlatform = targetPlatform.Releases[""] ctx.TargetBoard = targetBoard if len(fqbnParts) > 3 { @@ -92,18 +96,18 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_MISSING_CORE_FOR_BOARD, coreParts[0]) } - corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatform.Architecture].Releases[""] + corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatforms.Architecture].GetInstalled() } var actualPlatform *cores.PlatformRelease if corePlatform != nil { actualPlatform = corePlatform } else { - actualPlatform = targetPlatform.Releases[""] + actualPlatform = targetPlatform } if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Releases[""].Folder) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Folder) logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.Folder) } diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index 9521b46c..71a6cb75 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -178,7 +178,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.NotNil(t, packages.Packages["RFduino"]) require.Equal(t, 0, len(packages.Packages["RFduino"].Platforms)) - samdPlatform := packages.Packages["arduino"].Platforms["samd"].Releases[""] + samdPlatform := packages.Packages["arduino"].Platforms["samd"].Releases["1.6.5"] require.Equal(t, 3, len(samdPlatform.Boards)) require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardId) @@ -195,7 +195,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"][constants.PROGRAMMER_NAME]) require.Equal(t, "openocd", samdPlatform.Programmers["edbg"]["program.tool"]) - avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases[""] + avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases["1.0.0"] require.Equal(t, 3, len(avrRedBearPlatform.Boards)) require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardId) @@ -232,7 +232,7 @@ func TestLoadLotsOfHardware(t *testing.T) { require.Equal(t, 3, len(packages.Packages["arduino"].Platforms)) require.Equal(t, 20, len(packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards)) require.Equal(t, 2, len(packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards)) - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Releases[""].Boards)) + require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Releases["1.6.5"].Boards)) require.Equal(t, 1, len(packages.Packages["my_avr_platform"].Platforms)) require.Equal(t, 2, len(packages.Packages["my_avr_platform"].Platforms["avr"].Releases[""].Boards)) From 8f387ed7b03e203c52da1b7055680941434d7509 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 5 Mar 2018 22:28:35 +0100 Subject: [PATCH 04/57] Use packagemanager from arduino-cli --- hardware_loader.go | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index 5065d256..15f04e61 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -32,22 +32,17 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/cores/packagemanager" ) type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { - packages := &cores.Packages{ - Packages: map[string]*cores.Package{}, - Properties: properties.Map{}, - } - - folders := ctx.HardwareFolders - if err := packages.LoadHardwareFromFolders(folders); err != nil { + pm := packagemanager.PackageManager() + pm.Clear() + if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { return i18n.WrapError(err) } - ctx.Hardware = packages + ctx.Hardware = pm.GetPackages() return nil } From cc8f694faffd50bf6aab27d55723b3341fc25d66 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 7 Mar 2018 18:31:05 +0100 Subject: [PATCH 05/57] Removed a bunch of constants --- constants/constants.go | 29 -------- setup_build_properties.go | 55 ++++++++-------- test/ctags_runner_test.go | 11 ++-- test/hardware_loader_test.go | 25 ++++--- test/load_vid_pid_specific_properties_test.go | 7 +- test/platform_keys_rewrite_loader_test.go | 10 +-- test/rewrite_hardware_keys_test.go | 19 +++--- test/setup_build_properties_test.go | 66 +++++++++---------- test/target_board_resolver_test.go | 19 +++--- tools_loader.go | 12 ++-- 10 files changed, 110 insertions(+), 143 deletions(-) diff --git a/constants/constants.go b/constants/constants.go index d83ee273..a4a39117 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -37,25 +37,15 @@ const BUILD_PROPERTIES_ARCHIVE_FILE_PATH = "archive_file_path" const BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK = "architecture.override_check" const BUILD_PROPERTIES_BOOTLOADER_FILE = "bootloader.file" const BUILD_PROPERTIES_BOOTLOADER_NOBLINK = "bootloader.noblink" -const BUILD_PROPERTIES_BUILD_ARCH = "build.arch" const BUILD_PROPERTIES_BUILD_BOARD = "build.board" const BUILD_PROPERTIES_BUILD_CORE = "build.core" const BUILD_PROPERTIES_BUILD_CORE_PATH = "build.core.path" const BUILD_PROPERTIES_BUILD_MCU = "build.mcu" -const BUILD_PROPERTIES_BUILD_PATH = "build.path" -const BUILD_PROPERTIES_BUILD_PROJECT_NAME = "build.project_name" -const BUILD_PROPERTIES_BUILD_SYSTEM_PATH = "build.system.path" -const BUILD_PROPERTIES_BUILD_VARIANT = "build.variant" const BUILD_PROPERTIES_BUILD_VARIANT_PATH = "build.variant.path" const BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS = "compiler.c.elf.flags" const BUILD_PROPERTIES_COMPILER_C_ELF_EXTRAFLAGS = "compiler.c.elf.extra_flags" const BUILD_PROPERTIES_COMPILER_CPP_FLAGS = "compiler.cpp.flags" -const BUILD_PROPERTIES_COMPILER_PATH = "compiler.path" const BUILD_PROPERTIES_COMPILER_WARNING_FLAGS = "compiler.warning_flags" -const BUILD_PROPERTIES_EXTRA_TIME_DST = "extra.time.dst" -const BUILD_PROPERTIES_EXTRA_TIME_LOCAL = "extra.time.local" -const BUILD_PROPERTIES_EXTRA_TIME_UTC = "extra.time.utc" -const BUILD_PROPERTIES_EXTRA_TIME_ZONE = "extra.time.zone" const BUILD_PROPERTIES_FQBN = "build.fqbn" const BUILD_PROPERTIES_INCLUDES = "includes" const BUILD_PROPERTIES_OBJECT_FILE = "object_file" @@ -63,40 +53,23 @@ const BUILD_PROPERTIES_OBJECT_FILES = "object_files" const BUILD_PROPERTIES_PATTERN = "pattern" const BUILD_PROPERTIES_PID = "pid" const BUILD_PROPERTIES_PREPROCESSED_FILE_PATH = "preprocessed_file_path" -const BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH = "runtime.hardware.path" -const BUILD_PROPERTIES_RUNTIME_OS = "runtime.os" const BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH = "runtime.platform.path" -const BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX = "runtime.tools." -const BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX = ".path" -const BUILD_PROPERTIES_RUNTIME_IDE_VERSION = "runtime.ide.version" -const BUILD_PROPERTIES_SOFTWARE = "software" const BUILD_PROPERTIES_SOURCE_FILE = "source_file" -const BUILD_PROPERTIES_SOURCE_PATH = "build.source.path" const BUILD_PROPERTIES_TOOLS_KEY = "tools" const BUILD_PROPERTIES_VID = "vid" const CTAGS = "ctags" const EMPTY_STRING = "" -const FILE_BOARDS_LOCAL_TXT = "boards.local.txt" -const FILE_BOARDS_TXT = "boards.txt" const FILE_BUILTIN_TOOLS_VERSIONS_TXT = "builtin_tools_versions.txt" -const FILE_CTAGS_TARGET = "ctags_target.cpp" const FILE_CTAGS_TARGET_FOR_GCC_MINUS_E = "ctags_target_for_gcc_minus_e.cpp" const FILE_GCC_PREPROC_TARGET = "gcc_preproc_target.cpp" const FILE_PLATFORM_KEYS_REWRITE_TXT = "platform.keys.rewrite.txt" -const FILE_PLATFORM_LOCAL_TXT = "platform.local.txt" -const FILE_PLATFORM_TXT = "platform.txt" -const FILE_PROGRAMMERS_TXT = "programmers.txt" const FILE_INCLUDES_CACHE = "includes.cache" const FOLDER_BOOTLOADERS = "bootloaders" const FOLDER_CORE = "core" -const FOLDER_CORES = "cores" -const FOLDER_HARDWARE = "hardware" const FOLDER_LIBRARIES = "libraries" const FOLDER_PREPROC = "preproc" const FOLDER_SKETCH = "sketch" -const FOLDER_SYSTEM = "system" const FOLDER_TOOLS = "tools" -const FOLDER_VARIANTS = "variants" const hooks_core = hooks + ".core" const HOOKS_CORE_POSTBUILD = hooks_core + hooks_postbuild_suffix const HOOKS_CORE_PREBUILD = hooks_core + hooks_prebuild_suffix @@ -122,8 +95,6 @@ const hooks = "recipe.hooks" const hooks_sketch = hooks + ".sketch" const HOOKS_SKETCH_POSTBUILD = hooks_sketch + hooks_postbuild_suffix const HOOKS_SKETCH_PREBUILD = hooks_sketch + hooks_prebuild_suffix -const IDE_VERSION = "ide_version" -const ID = "_id" const LIB_CATEGORY_UNCATEGORIZED = "Uncategorized" const LIB_LICENSE_UNSPECIFIED = "Unspecified" const LIBRARY_ALL_ARCHS = "*" diff --git a/setup_build_properties.go b/setup_build_properties.go index 9e2f1d15..337026f4 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -35,7 +35,6 @@ import ( "strings" "time" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" @@ -58,26 +57,26 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties.Merge(targetBoard.Properties) if ctx.BuildPath != "" { - buildProperties[constants.BUILD_PROPERTIES_BUILD_PATH] = ctx.BuildPath + buildProperties["build.path"] = ctx.BuildPath } if ctx.Sketch != nil { - buildProperties[constants.BUILD_PROPERTIES_BUILD_PROJECT_NAME] = filepath.Base(ctx.Sketch.MainFile.Name) + buildProperties["build.project_name"] = filepath.Base(ctx.Sketch.MainFile.Name) } - buildProperties[constants.BUILD_PROPERTIES_BUILD_ARCH] = strings.ToUpper(targetPlatform.Platform.Architecture) - - buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE] = ctx.BuildCore - buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] = filepath.Join(actualPlatform.Folder, constants.FOLDER_CORES, buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE]) - buildProperties[constants.BUILD_PROPERTIES_BUILD_SYSTEM_PATH] = filepath.Join(actualPlatform.Folder, constants.FOLDER_SYSTEM) - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] = targetPlatform.Folder - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH] = filepath.Join(targetPlatform.Folder, "..") - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION] = ctx.ArduinoAPIVersion - buildProperties[constants.BUILD_PROPERTIES_FQBN] = ctx.FQBN - buildProperties[constants.IDE_VERSION] = ctx.ArduinoAPIVersion - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS] = utils.PrettyOSName() - - variant := buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT] - if variant == constants.EMPTY_STRING { - buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] = constants.EMPTY_STRING + buildProperties["build.arch"] = strings.ToUpper(targetPlatform.Platform.Architecture) + + buildProperties["build.core"] = ctx.BuildCore + buildProperties["build.core.path"] = filepath.Join(actualPlatform.Folder, "cores", buildProperties["build.core"]) + buildProperties["build.system.path"] = filepath.Join(actualPlatform.Folder, "system") + buildProperties["runtime.platform.path"] = targetPlatform.Folder + buildProperties["runtime.hardware.path"] = filepath.Join(targetPlatform.Folder, "..") + buildProperties["runtime.ide.version"] = ctx.ArduinoAPIVersion + buildProperties["build.fqbn"] = ctx.FQBN + buildProperties["ide_version"] = ctx.ArduinoAPIVersion + buildProperties["runtime.os"] = utils.PrettyOSName() + + variant := buildProperties["build.variant"] + if variant == "" { + buildProperties["build.variant.path"] = "" } else { var variantPlatform *cores.PlatformRelease variantParts := strings.Split(variant, ":") @@ -87,17 +86,17 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } else { variantPlatform = targetPlatform } - buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] = filepath.Join(variantPlatform.Folder, constants.FOLDER_VARIANTS, variant) + buildProperties["build.variant.path"] = filepath.Join(variantPlatform.Folder, "variants", variant) } tools := ctx.Tools for _, tool := range tools { - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX+tool.Name+constants.BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX] = tool.Folder - buildProperties[constants.BUILD_PROPERTIES_RUNTIME_TOOLS_PREFIX+tool.Name+"-"+tool.Version+constants.BUILD_PROPERTIES_RUNTIME_TOOLS_SUFFIX] = tool.Folder + buildProperties["runtime.tools."+tool.Name+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Name+"-"+tool.Version+".path"] = tool.Folder } - if !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_SOFTWARE) { - buildProperties[constants.BUILD_PROPERTIES_SOFTWARE] = DEFAULT_SOFTWARE + if !utils.MapStringStringHas(buildProperties, "software") { + buildProperties["software"] = DEFAULT_SOFTWARE } if ctx.SketchLocation != "" { @@ -106,14 +105,14 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { return err } sourcePath = filepath.Dir(sourcePath) - buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH] = sourcePath + buildProperties["build.source.path"] = sourcePath } now := time.Now() - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_UTC] = strconv.FormatInt(now.Unix(), 10) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL] = strconv.FormatInt(timeutils.LocalUnix(now), 10) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE] = strconv.Itoa(timeutils.TimezoneOffsetNoDST(now)) - buildProperties[constants.BUILD_PROPERTIES_EXTRA_TIME_DST] = strconv.Itoa(timeutils.DaylightSavingsOffset(now)) + buildProperties["extra.time.utc"] = strconv.FormatInt(now.Unix(), 10) + buildProperties["extra.time.local"] = strconv.FormatInt(timeutils.LocalUnix(now), 10) + buildProperties["extra.time.zone"] = strconv.Itoa(timeutils.TimezoneOffsetNoDST(now)) + buildProperties["extra.time.dst"] = strconv.Itoa(timeutils.DaylightSavingsOffset(now)) ctx.BuildProperties = buildProperties diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go index ddd56dc7..45a51260 100644 --- a/test/ctags_runner_test.go +++ b/test/ctags_runner_test.go @@ -36,7 +36,6 @@ import ( "testing" "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" ) @@ -70,7 +69,7 @@ func TestCTagsRunner(t *testing.T) { &builder.PrintUsedLibrariesIfVerbose{}, &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, + &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, &builder.CTagsRunner{}, } @@ -120,7 +119,7 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { &builder.PrintUsedLibrariesIfVerbose{}, &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, + &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, &builder.CTagsRunner{}, } @@ -168,7 +167,7 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { &builder.PrintUsedLibrariesIfVerbose{}, &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, + &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, &builder.CTagsRunner{}, } @@ -215,7 +214,7 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { &builder.PrintUsedLibrariesIfVerbose{}, &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, + &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, &builder.CTagsRunner{}, } @@ -261,7 +260,7 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { &builder.PrintUsedLibrariesIfVerbose{}, &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: constants.FILE_CTAGS_TARGET}, + &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, &builder.CTagsRunner{}, } diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index 71a6cb75..a3e31ac7 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -35,7 +35,6 @@ import ( "testing" "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/stretchr/testify/require" @@ -61,7 +60,7 @@ func TestLoadHardware(t *testing.T) { require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties[constants.ID]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) @@ -73,11 +72,11 @@ func TestLoadHardware(t *testing.T) { require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties["menu.cpu.atmega123"]) avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties[constants.PLATFORM_NAME]) + require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties["name"]) require.Equal(t, "-v", avrPlatform.Releases[""].Properties["tools.avrdude.bootloader.params.verbose"]) require.Equal(t, "/my/personal/avrdude", avrPlatform.Releases[""].Properties["tools.avrdude.cmd.path"]) - require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) + require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"]["name"]) //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) @@ -115,7 +114,7 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties[constants.ID]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) @@ -125,15 +124,15 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardId) avrPlatform := packages.Packages["arduino"].Platforms["avr"].Releases[""] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties[constants.PLATFORM_NAME]) + require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties["name"]) require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"][constants.PROGRAMMER_NAME]) + require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"]["name"]) require.Equal(t, "-w -x c++ -M -MG -MP", avrPlatform.Properties["preproc.includes.flags"]) require.Equal(t, "-w -x c++ -E -CC", avrPlatform.Properties["preproc.macros.flags"]) - require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties[constants.RECIPE_PREPROC_INCLUDES]) + require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties["recipe.preproc.includes"]) require.False(t, utils.MapStringStringHas(avrPlatform.Properties, "preproc.macros.compatibility_flags")) require.NotNil(t, packages.Packages["my_avr_platform"]) @@ -182,25 +181,25 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.Equal(t, 3, len(samdPlatform.Boards)) require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardId) - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties[constants.ID]) + require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties["_id"]) require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties["build.variant"]) require.Equal(t, "-D__SAMD21G18A__ {build.usb_flags}", samdPlatform.Boards["arduino_zero_native"].Properties["build.extra_flags"]) - require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties[constants.PLATFORM_NAME]) + require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties["name"]) require.Equal(t, "-d3", samdPlatform.Properties["tools.openocd.erase.params.verbose"]) require.Equal(t, 3, len(samdPlatform.Programmers)) - require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"][constants.PROGRAMMER_NAME]) + require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"]["name"]) require.Equal(t, "openocd", samdPlatform.Programmers["edbg"]["program.tool"]) avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases["1.0.0"] require.Equal(t, 3, len(avrRedBearPlatform.Boards)) require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardId) - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties[constants.ID]) - require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties[constants.BUILD_PROPERTIES_BUILD_CORE]) + require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties["_id"]) + require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties["build.core"]) } func TestLoadLotsOfHardware(t *testing.T) { diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go index 05fbf80f..ad3ea6f7 100644 --- a/test/load_vid_pid_specific_properties_test.go +++ b/test/load_vid_pid_specific_properties_test.go @@ -30,12 +30,13 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" "os" "path/filepath" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + "github.com/stretchr/testify/require" ) func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { diff --git a/test/platform_keys_rewrite_loader_test.go b/test/platform_keys_rewrite_loader_test.go index 914f5f75..3d69bf79 100644 --- a/test/platform_keys_rewrite_loader_test.go +++ b/test/platform_keys_rewrite_loader_test.go @@ -30,12 +30,12 @@ package test import ( + "path/filepath" + "testing" + "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" - "path/filepath" - "testing" ) func TestLoadPlatformKeysRewrite(t *testing.T) { @@ -55,7 +55,7 @@ func TestLoadPlatformKeysRewrite(t *testing.T) { platformKeysRewrite := ctx.PlatformKeyRewrites require.Equal(t, 13, len(platformKeysRewrite.Rewrites)) - require.Equal(t, constants.BUILD_PROPERTIES_COMPILER_PATH, platformKeysRewrite.Rewrites[0].Key) + require.Equal(t, "compiler.path", platformKeysRewrite.Rewrites[0].Key) require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platformKeysRewrite.Rewrites[0].OldValue) require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platformKeysRewrite.Rewrites[0].NewValue) @@ -63,7 +63,7 @@ func TestLoadPlatformKeysRewrite(t *testing.T) { require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/avrdude", platformKeysRewrite.Rewrites[1].OldValue) require.Equal(t, "{path}/bin/avrdude", platformKeysRewrite.Rewrites[1].NewValue) - require.Equal(t, constants.BUILD_PROPERTIES_COMPILER_PATH, platformKeysRewrite.Rewrites[3].Key) + require.Equal(t, "compiler.path", platformKeysRewrite.Rewrites[3].Key) require.Equal(t, "{runtime.ide.path}/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/", platformKeysRewrite.Rewrites[3].OldValue) require.Equal(t, "{runtime.tools.arm-none-eabi-gcc.path}/bin/", platformKeysRewrite.Rewrites[3].NewValue) diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go index dc78dddd..a2623429 100644 --- a/test/rewrite_hardware_keys_test.go +++ b/test/rewrite_hardware_keys_test.go @@ -33,7 +33,6 @@ import ( "testing" "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" properties "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/cores" @@ -51,8 +50,8 @@ func TestRewriteHardwareKeys(t *testing.T) { platform := &cores.PlatformRelease{ Properties: properties.Map{ - constants.PLATFORM_NAME: "A test platform", - constants.BUILD_PROPERTIES_COMPILER_PATH: "{runtime.ide.path}/hardware/tools/avr/bin/", + "name": "A test platform", + "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", }, } aPackage.Platforms["dummy"] = &cores.Platform{ @@ -64,7 +63,7 @@ func TestRewriteHardwareKeys(t *testing.T) { ctx.Hardware = packages - rewrite := types.PlatforKeyRewrite{Key: constants.BUILD_PROPERTIES_COMPILER_PATH, OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} + rewrite := types.PlatforKeyRewrite{Key: "compiler.path", OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} ctx.PlatformKeyRewrites = platformKeysRewrite @@ -78,7 +77,7 @@ func TestRewriteHardwareKeys(t *testing.T) { NoError(t, err) } - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH]) + require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties["compiler.path"]) } func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { @@ -92,9 +91,9 @@ func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { platform := &cores.PlatformRelease{ Properties: properties.Map{ - constants.PLATFORM_NAME: "A test platform", - constants.BUILD_PROPERTIES_COMPILER_PATH: "{runtime.ide.path}/hardware/tools/avr/bin/", - constants.REWRITING: constants.REWRITING_DISABLED, + "name": "A test platform", + "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", + "rewriting": "disabled", }, } aPackage.Platforms["dummy"] = &cores.Platform{ @@ -106,7 +105,7 @@ func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { ctx.Hardware = packages - rewrite := types.PlatforKeyRewrite{Key: constants.BUILD_PROPERTIES_COMPILER_PATH, OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} + rewrite := types.PlatforKeyRewrite{Key: "compiler.path", OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} ctx.PlatformKeyRewrites = platformKeysRewrite @@ -121,5 +120,5 @@ func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { NoError(t, err) } - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties[constants.BUILD_PROPERTIES_COMPILER_PATH]) + require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties["compiler.path"]) } diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index c8d39a91..6818d883 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -30,14 +30,14 @@ package test import ( + "os" + "path/filepath" + "testing" + "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" ) func TestSetupBuildProperties(t *testing.T) { @@ -70,18 +70,18 @@ func TestSetupBuildProperties(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) + require.Equal(t, "ARDUINO", buildProperties["software"]) - require.Equal(t, "uno", buildProperties[constants.ID]) + require.Equal(t, "uno", buildProperties["_id"]) require.Equal(t, "Arduino/Genuino Uno", buildProperties["name"]) require.Equal(t, "0x2341", buildProperties["vid.0"]) require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) - require.Equal(t, "10600", buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION]) - require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS]) + require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties["runtime.platform.path"]) + require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties["runtime.hardware.path"]) + require.Equal(t, "10600", buildProperties["runtime.ide.version"]) + require.NotEmpty(t, buildProperties["runtime.os"]) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) @@ -93,12 +93,12 @@ func TestSetupBuildProperties(t *testing.T) { require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) - require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH]) + require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST)) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.zone")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.dst")) } func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { @@ -134,9 +134,9 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) + require.Equal(t, "ARDUINO", buildProperties["software"]) - require.Equal(t, "uno", buildProperties[constants.ID]) + require.Equal(t, "uno", buildProperties["_id"]) require.Equal(t, "fake name", buildProperties["name"]) require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) require.Equal(t, "non existent path with space and a =", buildProperties["tools.avrdude.config.path"]) @@ -172,12 +172,12 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) + require.Equal(t, "ARDUINO", buildProperties["software"]) - require.Equal(t, "custom_yun", buildProperties[constants.ID]) - require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_FILE]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr")), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform")), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) + require.Equal(t, "custom_yun", buildProperties["_id"]) + require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties["bootloader.file"]) + require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr")), buildProperties["runtime.platform.path"]) + require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform")), buildProperties["runtime.hardware.path"]) } func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) { @@ -205,18 +205,18 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties[constants.BUILD_PROPERTIES_SOFTWARE]) + require.Equal(t, "ARDUINO", buildProperties["software"]) - require.Equal(t, "custom_yun", buildProperties[constants.ID]) + require.Equal(t, "custom_yun", buildProperties["_id"]) require.Equal(t, "Arduino Yún", buildProperties["name"]) require.Equal(t, "0x2341", buildProperties["vid.0"]) require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - require.Equal(t, Abs(t, "user_hardware/my_avr_platform/avr"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) - require.Equal(t, Abs(t, "user_hardware/my_avr_platform"), buildProperties[constants.BUILD_PROPERTIES_RUNTIME_HARDWARE_PATH]) - require.Equal(t, "10600", buildProperties[constants.BUILD_PROPERTIES_RUNTIME_IDE_VERSION]) - require.NotEmpty(t, buildProperties[constants.BUILD_PROPERTIES_RUNTIME_OS]) + require.Equal(t, Abs(t, "user_hardware/my_avr_platform/avr"), buildProperties["runtime.platform.path"]) + require.Equal(t, Abs(t, "user_hardware/my_avr_platform"), buildProperties["runtime.hardware.path"]) + require.Equal(t, "10600", buildProperties["runtime.ide.version"]) + require.NotEmpty(t, buildProperties["runtime.os"]) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) @@ -228,10 +228,10 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) - require.Equal(t, Abs(t, "sketch1"), buildProperties[constants.BUILD_PROPERTIES_SOURCE_PATH]) + require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_UTC)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_LOCAL)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_ZONE)) - require.True(t, utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_EXTRA_TIME_DST)) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.zone")) + require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.dst")) } diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index 337c7416..d896c5fb 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -34,7 +34,6 @@ import ( "testing" "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" ) @@ -61,7 +60,7 @@ func TestTargetBoardResolverUno(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "uno", targetBoard.BoardId) - require.Equal(t, "atmega328p", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) + require.Equal(t, "atmega328p", targetBoard.Properties["build.mcu"]) } func TestTargetBoardResolverDue(t *testing.T) { @@ -86,7 +85,7 @@ func TestTargetBoardResolverDue(t *testing.T) { require.Equal(t, "sam", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "arduino_due_x", targetBoard.BoardId) - require.Equal(t, "cortex-m3", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) + require.Equal(t, "cortex-m3", targetBoard.Properties["build.mcu"]) } func TestTargetBoardResolverMega1280(t *testing.T) { @@ -111,8 +110,8 @@ func TestTargetBoardResolverMega1280(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardId) - require.Equal(t, "atmega1280", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + require.Equal(t, "atmega1280", targetBoard.Properties["build.mcu"]) + require.Equal(t, "AVR_MEGA", targetBoard.Properties["build.board"]) } func TestTargetBoardResolverMega2560(t *testing.T) { @@ -137,8 +136,8 @@ func TestTargetBoardResolverMega2560(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardId) - require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + require.Equal(t, "atmega2560", targetBoard.Properties["build.mcu"]) + require.Equal(t, "AVR_MEGA2560", targetBoard.Properties["build.board"]) } func TestTargetBoardResolverCustomYun(t *testing.T) { @@ -163,8 +162,8 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "custom_yun", targetBoard.BoardId) - require.Equal(t, "atmega32u4", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_YUN", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + require.Equal(t, "atmega32u4", targetBoard.Properties["build.mcu"]) + require.Equal(t, "AVR_YUN", targetBoard.Properties["build.board"]) } func TestTargetBoardResolverCustomCore(t *testing.T) { @@ -190,5 +189,5 @@ func TestTargetBoardResolverCustomCore(t *testing.T) { targetBoard := ctx.TargetBoard require.Equal(t, "attiny841", targetBoard.BoardId) require.Equal(t, "tiny841", ctx.BuildCore) - require.Equal(t, "tiny14", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_VARIANT]) + require.Equal(t, "tiny14", targetBoard.Properties["build.variant"]) } diff --git a/tools_loader.go b/tools_loader.go index 2d9ee00a..f586a142 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -57,12 +57,12 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { builtinHardwareFolder, err = filepath.Abs(filepath.Join(ctx.BuiltInLibrariesFolders[0], "..")) } - if builtinToolsVersionsFile != constants.EMPTY_STRING && !strings.Contains(builtinToolsVersionsFile, builtinHardwareFolder) { + if builtinToolsVersionsFile != "" && !strings.Contains(builtinToolsVersionsFile, builtinHardwareFolder) { ctx.GetLogger().Println(constants.LOG_LEVEL_WARN, constants.MSG_IGNORED_BUILTIN_TOOLS_TXT, builtinToolsVersionsFile) - builtinToolsVersionsFile = constants.EMPTY_STRING + builtinToolsVersionsFile = "" } - if builtinToolsVersionsFile != constants.EMPTY_STRING { + if builtinToolsVersionsFile != "" { err = loadToolsFrom(&tools, builtinToolsVersionsFile) if err != nil { return i18n.WrapError(err) @@ -143,7 +143,7 @@ func loadToolsFrom(tools *[]*types.Tool, builtinToolsVersionsFilePath string) er for _, row := range rows { row = strings.TrimSpace(row) - if row != constants.EMPTY_STRING { + if row != "" { rowParts := strings.Split(row, "=") toolName := strings.Split(rowParts[0], ".")[1] toolVersion := rowParts[1] @@ -157,13 +157,13 @@ func loadToolsFrom(tools *[]*types.Tool, builtinToolsVersionsFilePath string) er } func findBuiltinToolsVersionsFile(folder string) (string, error) { - builtinToolsVersionsFilePath := constants.EMPTY_STRING + builtinToolsVersionsFilePath := "" findBuiltInToolsVersionsTxt := func(currentPath string, info os.FileInfo, err error) error { if err != nil { return nil } - if builtinToolsVersionsFilePath != constants.EMPTY_STRING { + if builtinToolsVersionsFilePath != "" { return nil } if filepath.Base(currentPath) == constants.FILE_BUILTIN_TOOLS_VERSIONS_TXT { From c2146d4857ad598ecf3aa8b822ce88be02f34502 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 7 Mar 2018 18:31:41 +0100 Subject: [PATCH 06/57] Using cores.Tool/ToolRelease and removed types.Tool --- setup_build_properties.go | 4 ++-- test/tools_loader_test.go | 46 ++++++++++++++++++++------------------- tools_loader.go | 30 ++++++++++++++++--------- types/context.go | 2 +- types/types.go | 6 ----- 5 files changed, 47 insertions(+), 41 deletions(-) diff --git a/setup_build_properties.go b/setup_build_properties.go index 337026f4..ff23fc4e 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -91,8 +91,8 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { tools := ctx.Tools for _, tool := range tools { - buildProperties["runtime.tools."+tool.Name+".path"] = tool.Folder - buildProperties["runtime.tools."+tool.Name+"-"+tool.Version+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder } if !utils.MapStringStringHas(buildProperties, "software") { diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 3507afe8..e5484929 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -30,14 +30,16 @@ package test import ( + "sort" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/bcmi-labs/arduino-cli/cores" "github.com/stretchr/testify/require" - "sort" - "testing" ) -type ByToolIDAndVersion []*types.Tool +type ByToolIDAndVersion []*cores.ToolRelease func (s ByToolIDAndVersion) Len() int { return len(s) @@ -46,10 +48,10 @@ func (s ByToolIDAndVersion) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByToolIDAndVersion) Less(i, j int) bool { - if s[i].Name == s[j].Name { + if s[i].Tool.Name == s[j].Tool.Name { return s[i].Version < s[j].Version } - return s[i].Name < s[j].Name + return s[i].Tool.Name < s[j].Tool.Name } func TestLoadTools(t *testing.T) { @@ -69,27 +71,27 @@ func TestLoadTools(t *testing.T) { sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) + require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) require.Equal(t, "4.8.3-2014q1", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "avr-gcc", tools[idx].Name) + require.Equal(t, "avr-gcc", tools[idx].Tool.Name) require.Equal(t, "4.8.1-arduino5", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "avrdude", tools[idx].Name) + require.Equal(t, "avrdude", tools[idx].Tool.Name) require.Equal(t, "6.0.1-arduino5", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Name) + require.Equal(t, "bossac", tools[idx].Tool.Name) require.Equal(t, "1.5-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Name) + require.Equal(t, "bossac", tools[idx].Tool.Name) require.Equal(t, "1.6.1-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "ctags", tools[idx].Name) + require.Equal(t, "ctags", tools[idx].Tool.Name) require.Equal(t, "5.8-arduino11", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) } @@ -111,15 +113,15 @@ func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "CMSIS", tools[idx].Name) + require.Equal(t, "CMSIS", tools[idx].Tool.Name) require.Equal(t, "4.0.0-atmel", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) + require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) require.Equal(t, "4.8.3-2014q1", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "openocd", tools[idx].Name) + require.Equal(t, "openocd", tools[idx].Tool.Name) require.Equal(t, "0.9.0-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) } @@ -141,35 +143,35 @@ func TestLoadLotsOfTools(t *testing.T) { sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "CMSIS", tools[idx].Name) + require.Equal(t, "CMSIS", tools[idx].Tool.Name) require.Equal(t, "4.0.0-atmel", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Name) + require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) require.Equal(t, "4.8.3-2014q1", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "avr-gcc", tools[idx].Name) + require.Equal(t, "avr-gcc", tools[idx].Tool.Name) require.Equal(t, "4.8.1-arduino5", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "avrdude", tools[idx].Name) + require.Equal(t, "avrdude", tools[idx].Tool.Name) require.Equal(t, "6.0.1-arduino5", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Name) + require.Equal(t, "bossac", tools[idx].Tool.Name) require.Equal(t, "1.5-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Name) + require.Equal(t, "bossac", tools[idx].Tool.Name) require.Equal(t, "1.6.1-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "ctags", tools[idx].Name) + require.Equal(t, "ctags", tools[idx].Tool.Name) require.Equal(t, "5.8-arduino11", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) idx++ - require.Equal(t, "openocd", tools[idx].Name) + require.Equal(t, "openocd", tools[idx].Tool.Name) require.Equal(t, "0.9.0-arduino", tools[idx].Version) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) } diff --git a/tools_loader.go b/tools_loader.go index f586a142..bc33ab65 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -30,14 +30,16 @@ package builder import ( + "os" + "path/filepath" + "strings" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" - "strings" + "github.com/bcmi-labs/arduino-cli/cores" ) type ToolsLoader struct{} @@ -45,7 +47,7 @@ type ToolsLoader struct{} func (s *ToolsLoader) Run(ctx *types.Context) error { folders := ctx.ToolsFolders - tools := []*types.Tool{} + tools := []*cores.ToolRelease{} for _, folder := range folders { builtinToolsVersionsFile, err := findBuiltinToolsVersionsFile(folder) @@ -121,16 +123,16 @@ func collectAllToolsFolders(from string) ([]string, error) { return folders, i18n.WrapError(err) } -func toolsSliceContains(tools *[]*types.Tool, name, version string) bool { +func toolsSliceContains(tools *[]*cores.ToolRelease, name, version string) bool { for _, tool := range *tools { - if name == tool.Name && version == tool.Version { + if name == tool.Tool.Name && version == tool.Version { return true } } return false } -func loadToolsFrom(tools *[]*types.Tool, builtinToolsVersionsFilePath string) error { +func loadToolsFrom(tools *[]*cores.ToolRelease, builtinToolsVersionsFilePath string) error { rows, err := utils.ReadFileToRows(builtinToolsVersionsFilePath) if err != nil { return i18n.WrapError(err) @@ -148,7 +150,11 @@ func loadToolsFrom(tools *[]*types.Tool, builtinToolsVersionsFilePath string) er toolName := strings.Split(rowParts[0], ".")[1] toolVersion := rowParts[1] if !toolsSliceContains(tools, toolName, toolVersion) { - *tools = append(*tools, &types.Tool{Name: toolName, Version: toolVersion, Folder: folder}) + *tools = append(*tools, + &cores.ToolRelease{ + Tool: &cores.Tool{Name: toolName}, + Version: toolVersion, + Folder: folder}) } } } @@ -175,7 +181,7 @@ func findBuiltinToolsVersionsFile(folder string) (string, error) { return builtinToolsVersionsFilePath, i18n.WrapError(err) } -func loadToolsFromFolderStructure(tools *[]*types.Tool, folder string) error { +func loadToolsFromFolderStructure(tools *[]*cores.ToolRelease, folder string) error { toolsNames, err := utils.ReadDirFiltered(folder, utils.FilterDirs) if err != nil { return i18n.WrapError(err) @@ -191,7 +197,11 @@ func loadToolsFromFolderStructure(tools *[]*types.Tool, folder string) error { return i18n.WrapError(err) } if !toolsSliceContains(tools, toolName.Name(), toolVersion.Name()) { - *tools = append(*tools, &types.Tool{Name: toolName.Name(), Version: toolVersion.Name(), Folder: toolFolder}) + *tools = append(*tools, + &cores.ToolRelease{ + Tool: &cores.Tool{Name: toolName.Name()}, + Version: toolVersion.Name(), + Folder: toolFolder}) } } } diff --git a/types/context.go b/types/context.go index bf772913..0dc82a39 100644 --- a/types/context.go +++ b/types/context.go @@ -25,7 +25,7 @@ type Context struct { BuildOptionsJsonPrevious string Hardware *cores.Packages - Tools []*Tool + Tools []*cores.ToolRelease TargetBoard *cores.Board TargetPackage *cores.Package TargetPlatform *cores.PlatformRelease diff --git a/types/types.go b/types/types.go index 4561a3b1..83e49c8e 100644 --- a/types/types.go +++ b/types/types.go @@ -123,12 +123,6 @@ type Sketch struct { AdditionalFiles []SketchFile } -type Tool struct { - Name string - Version string - Folder string -} - type LibraryLayout uint16 const ( From a11ea7b05ad7366e05e0228b797b1966fc4b1f79 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 8 Mar 2018 11:13:37 +0100 Subject: [PATCH 07/57] WIP: Refactoring builtin_tools_versions.txt detection --- setup_build_properties.go | 2 +- test/tools_loader_test.go | 6 ++-- tools_loader.go | 67 +++++++++++++++++++++++++-------------- types/context.go | 3 +- 4 files changed, 49 insertions(+), 29 deletions(-) diff --git a/setup_build_properties.go b/setup_build_properties.go index ff23fc4e..653f5f21 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -89,7 +89,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties["build.variant.path"] = filepath.Join(variantPlatform.Folder, "variants", variant) } - tools := ctx.Tools + tools := ctx.RequiredTools for _, tool := range tools { buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index e5484929..dbd8d2f5 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -65,7 +65,7 @@ func TestLoadTools(t *testing.T) { err := loader.Run(ctx) NoError(t, err) - tools := ctx.Tools + tools := ctx.RequiredTools require.Equal(t, 6, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) @@ -107,7 +107,7 @@ func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { err := loader.Run(ctx) NoError(t, err) - tools := ctx.Tools + tools := ctx.RequiredTools require.Equal(t, 3, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) @@ -137,7 +137,7 @@ func TestLoadLotsOfTools(t *testing.T) { err := loader.Run(ctx) NoError(t, err) - tools := ctx.Tools + tools := ctx.RequiredTools require.Equal(t, 8, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) diff --git a/tools_loader.go b/tools_loader.go index bc33ab65..9aa065b1 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -30,6 +30,7 @@ package builder import ( + "fmt" "os" "path/filepath" "strings" @@ -45,46 +46,64 @@ import ( type ToolsLoader struct{} func (s *ToolsLoader) Run(ctx *types.Context) error { - folders := ctx.ToolsFolders + folders := []string{} + builtinFolders := []string{} + + if ctx.BuiltInToolsFolders != nil || len(ctx.BuiltInLibrariesFolders) == 0 { + folders = ctx.ToolsFolders + builtinFolders = ctx.BuiltInToolsFolders + } else { + // Auto-detect built-in tools folders (for arduino-builder backward compatibility) + // this is a deprecated feature and will be removed in the future + builtinHardwareFolder, err := filepath.Abs(filepath.Join(ctx.BuiltInLibrariesFolders[0], "..")) + if err != nil { + fmt.Println("Error detecting ") + } + + builtinFolders = []string{} + for _, folder := range ctx.ToolsFolders { + if !strings.Contains(folder, builtinHardwareFolder) { + folders = append(folders, folder) + } else { + builtinFolders = append(builtinFolders, folder) + } + } + } tools := []*cores.ToolRelease{} - for _, folder := range folders { + for _, folder := range builtinFolders { builtinToolsVersionsFile, err := findBuiltinToolsVersionsFile(folder) if err != nil { return i18n.WrapError(err) } - builtinHardwareFolder := "" - if len(ctx.BuiltInLibrariesFolders) > 0 { - builtinHardwareFolder, err = filepath.Abs(filepath.Join(ctx.BuiltInLibrariesFolders[0], "..")) + + if builtinToolsVersionsFile == "" { + folders = append(folders, folder) + continue + } + + err = loadToolsFrom(&tools, builtinToolsVersionsFile) + if err != nil { + return i18n.WrapError(err) } + } - if builtinToolsVersionsFile != "" && !strings.Contains(builtinToolsVersionsFile, builtinHardwareFolder) { - ctx.GetLogger().Println(constants.LOG_LEVEL_WARN, constants.MSG_IGNORED_BUILTIN_TOOLS_TXT, builtinToolsVersionsFile) - builtinToolsVersionsFile = "" + for _, folder := range folders { + subfolders, err := collectAllToolsFolders(folder) + if err != nil { + return i18n.WrapError(err) } - if builtinToolsVersionsFile != "" { - err = loadToolsFrom(&tools, builtinToolsVersionsFile) + for _, subfolder := range subfolders { + err = loadToolsFromFolderStructure(&tools, subfolder) if err != nil { return i18n.WrapError(err) } - } else { - subfolders, err := collectAllToolsFolders(folder) - if err != nil { - return i18n.WrapError(err) - } - - for _, subfolder := range subfolders { - err = loadToolsFromFolderStructure(&tools, subfolder) - if err != nil { - return i18n.WrapError(err) - } - } } } - ctx.Tools = tools + ctx.RequiredTools = tools return nil } @@ -172,7 +191,7 @@ func findBuiltinToolsVersionsFile(folder string) (string, error) { if builtinToolsVersionsFilePath != "" { return nil } - if filepath.Base(currentPath) == constants.FILE_BUILTIN_TOOLS_VERSIONS_TXT { + if filepath.Base(currentPath) == "builtin_tools_versions.txt" { builtinToolsVersionsFilePath = currentPath } return nil diff --git a/types/context.go b/types/context.go index 0dc82a39..fa0a17f9 100644 --- a/types/context.go +++ b/types/context.go @@ -13,6 +13,7 @@ type Context struct { // Build options HardwareFolders []string ToolsFolders []string + BuiltInToolsFolders []string LibrariesFolders []string BuiltInLibrariesFolders []string OtherLibrariesFolders []string @@ -25,7 +26,7 @@ type Context struct { BuildOptionsJsonPrevious string Hardware *cores.Packages - Tools []*cores.ToolRelease + RequiredTools []*cores.ToolRelease TargetBoard *cores.Board TargetPackage *cores.Package TargetPlatform *cores.PlatformRelease From a21828b5ab25e9e6305649823765da8c213e8a29 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 12 Mar 2018 23:14:50 +0100 Subject: [PATCH 08/57] Now using tools loader from arduino-cli --- container_setup.go | 2 +- setup_build_properties.go | 7 +- test/builder_test.go | 2 +- test/ctags_runner_test.go | 10 +- test/helper_tools_downloader.go | 6 + test/includes_to_include_folders_test.go | 23 +-- test/prototypes_adder_test.go | 61 +++---- test/setup_build_properties_test.go | 69 ++++---- test/tools_loader_test.go | 101 ++++++------ test/try_build_of_problematic_sketch_test.go | 7 +- tools_loader.go | 164 +------------------ types/context.go | 1 + 12 files changed, 162 insertions(+), 291 deletions(-) diff --git a/container_setup.go b/container_setup.go index 93ee6d73..0b8d5b00 100644 --- a/container_setup.go +++ b/container_setup.go @@ -43,8 +43,8 @@ func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context) &HardwareLoader{}, &PlatformKeysRewriteLoader{}, &RewriteHardwareKeys{}, - &ToolsLoader{}, &TargetBoardResolver{}, + &ToolsLoader{}, &AddBuildBoardPropertyIfMissing{}, &LibrariesLoader{}, &SketchLoader{}, diff --git a/setup_build_properties.go b/setup_build_properties.go index 653f5f21..7e5c2948 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -89,8 +89,11 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties["build.variant.path"] = filepath.Join(variantPlatform.Folder, "variants", variant) } - tools := ctx.RequiredTools - for _, tool := range tools { + for _, tool := range ctx.AllTools { + buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder + } + for _, tool := range ctx.RequiredTools { buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder } diff --git a/test/builder_test.go b/test/builder_test.go index da51844e..2e913cd7 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -48,7 +48,7 @@ func prepareBuilderTestContext(sketchPath, fqbn string) *types.Context { SketchLocation: sketchPath, FQBN: fqbn, HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, ArduinoAPIVersion: "10600", diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go index 45a51260..c5d6e6b5 100644 --- a/test/ctags_runner_test.go +++ b/test/ctags_runner_test.go @@ -47,7 +47,7 @@ func TestCTagsRunner(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -97,7 +97,7 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -145,7 +145,7 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -192,7 +192,7 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -238,7 +238,7 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index cfce881c..efe9db45 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -42,6 +42,8 @@ import ( "strings" "testing" + "github.com/bcmi-labs/arduino-cli/cores/packagemanager" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" @@ -83,6 +85,10 @@ type Core struct { } func DownloadCoresAndToolsAndLibraries(t *testing.T) { + pm := packagemanager.PackageManager() + pm.Clear() + pm.DisableDebugOutput() + cores := []Core{ Core{Maintainer: "arduino", Arch: "avr", Version: "1.6.10"}, Core{Maintainer: "arduino", Arch: "sam", Version: "1.6.7"}, diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index 29f26d06..fafa3ff2 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -30,14 +30,15 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" "fmt" - "github.com/stretchr/testify/require" "os" "path/filepath" "sort" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + "github.com/stretchr/testify/require" ) func TestIncludesToIncludeFolders(t *testing.T) { @@ -45,7 +46,7 @@ func TestIncludesToIncludeFolders(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), @@ -81,7 +82,7 @@ func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), @@ -116,7 +117,7 @@ func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch9", "sketch.ino"), @@ -154,7 +155,7 @@ func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch10", "sketch.ino"), @@ -192,7 +193,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), FQBN: "my_avr_platform:avr:custom_yun", @@ -229,7 +230,7 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), @@ -267,7 +268,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - ToolsFolders: []string{"downloaded_tools", "downloaded_board_manager_stuff"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch_usbhost", "sketch_usbhost.ino"), @@ -305,7 +306,7 @@ func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch_with_subfolders", "sketch_with_subfolders.ino"), diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go index 7c281461..18b8c2a6 100644 --- a/test/prototypes_adder_test.go +++ b/test/prototypes_adder_test.go @@ -31,14 +31,15 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" "os" "path/filepath" "strings" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-builder/utils" + "github.com/stretchr/testify/require" ) func TestPrototypesAdderBridgeExample(t *testing.T) { @@ -49,7 +50,7 @@ func TestPrototypesAdderBridgeExample(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -91,7 +92,7 @@ func TestPrototypesAdderSketchWithIfDef(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), @@ -131,7 +132,7 @@ func TestPrototypesAdderBaladuino(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch3", "Baladuino.ino"), @@ -171,7 +172,7 @@ func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch4", "CharWithEscapedDoubleQuote.ino"), @@ -211,7 +212,7 @@ func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch5", "IncludeBetweenMultilineComment.ino"), @@ -251,7 +252,7 @@ func TestPrototypesAdderLineContinuations(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch6", "/LineContinuations.ino"), @@ -291,7 +292,7 @@ func TestPrototypesAdderStringWithComment(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch7", "StringWithComment.ino"), @@ -331,7 +332,7 @@ func TestPrototypesAdderSketchWithStruct(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch8", "SketchWithStruct.ino"), @@ -379,7 +380,7 @@ func TestPrototypesAdderSketchWithConfig(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -425,7 +426,7 @@ func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch_no_functions_two_files", "main.ino"), @@ -465,7 +466,7 @@ func TestPrototypesAdderSketchNoFunctions(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("sketch_no_functions", "main.ino"), @@ -511,7 +512,7 @@ func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -554,7 +555,7 @@ func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -608,7 +609,7 @@ func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -651,7 +652,7 @@ func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, OtherLibrariesFolders: []string{"libraries"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, SketchLocation: sketchLocation, @@ -693,13 +694,13 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - LibrariesFolders: []string{"libraries", "downloaded_libraries"}, - ToolsFolders: []string{"downloaded_tools"}, - SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + LibrariesFolders: []string{"libraries", "downloaded_libraries"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, + SketchLocation: sketchLocation, + FQBN: "arduino:avr:leonardo", + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -742,7 +743,7 @@ func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -788,7 +789,7 @@ func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -834,7 +835,7 @@ func TestPrototypesAdderSketchWithConst(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: sketchLocation, @@ -874,7 +875,7 @@ func TestPrototypesAdderSketchWithDosEol(t *testing.T) { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, SketchLocation: filepath.Join("eol_processing", "sketch.ino"), diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index 6818d883..4f0b7c58 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -44,11 +44,11 @@ func TestSetupBuildProperties(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", + HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, + SketchLocation: filepath.Join("sketch1", "sketch.ino"), + FQBN: "arduino:avr:uno", + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -57,8 +57,8 @@ func TestSetupBuildProperties(t *testing.T) { commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, &builder.HardwareLoader{}, - &builder.ToolsLoader{}, &builder.TargetBoardResolver{}, + &builder.ToolsLoader{}, &builder.SketchLoader{}, &builder.SetupBuildProperties{}, } @@ -87,11 +87,12 @@ func TestSetupBuildProperties(t *testing.T) { require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) - require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) + bossacPath := buildProperties["runtime.tools.bossac.path"] + require.True(t, bossacPath == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || bossacPath == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) + avrdudePath := buildProperties["runtime.tools.avrdude.path"] + require.True(t, avrdudePath == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath == Abs(t, "./tools_builtin/avr")) + avrgccPath := buildProperties["runtime.tools.avr-gcc.path"] + require.True(t, avrgccPath == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath == Abs(t, "./tools_builtin/avr")) require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) @@ -105,11 +106,11 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", - ArduinoAPIVersion: "10600", + HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, + SketchLocation: filepath.Join("sketch1", "sketch.ino"), + FQBN: "arduino:avr:uno", + ArduinoAPIVersion: "10600", CustomBuildProperties: []string{"name=fake name", "tools.avrdude.config.path=non existent path with space and a ="}, } @@ -120,8 +121,8 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, &builder.HardwareLoader{}, - &builder.ToolsLoader{}, &builder.TargetBoardResolver{}, + &builder.ToolsLoader{}, &builder.SketchLoader{}, &builder.SetupBuildProperties{}, &builder.SetCustomBuildProperties{}, @@ -146,11 +147,11 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", + HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, + SketchLocation: filepath.Join("sketch1", "sketch.ino"), + FQBN: "my_avr_platform:avr:custom_yun", + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -159,8 +160,8 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, &builder.HardwareLoader{}, - &builder.ToolsLoader{}, &builder.TargetBoardResolver{}, + &builder.ToolsLoader{}, &builder.SketchLoader{}, &builder.SetupBuildProperties{}, } @@ -184,11 +185,11 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", - ArduinoAPIVersion: "10600", + HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, + SketchLocation: filepath.Join("sketch1", "sketch.ino"), + FQBN: "my_avr_platform:avr:custom_yun", + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -223,10 +224,14 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"]) + avrdudePath := buildProperties["runtime.tools.avrdude.path"] + require.True(t, avrdudePath == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath == Abs(t, "./tools_builtin/avr")) + avrdudePath601 := buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"] + require.True(t, avrdudePath601 == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath601 == Abs(t, "./tools_builtin/avr")) + avrgccPath := buildProperties["runtime.tools.avr-gcc.path"] + require.True(t, avrgccPath == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath == Abs(t, "./tools_builtin/avr")) + avrgccPath481 := buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"] + require.True(t, avrgccPath481 == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath481 == Abs(t, "./tools_builtin/avr")) require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index dbd8d2f5..55a49900 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -48,81 +48,79 @@ func (s ByToolIDAndVersion) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s ByToolIDAndVersion) Less(i, j int) bool { - if s[i].Tool.Name == s[j].Tool.Name { + if s[i].Tool.Name != s[j].Tool.Name { + return s[i].Tool.Name < s[j].Tool.Name + } + if s[i].Version != s[j].Version { return s[i].Version < s[j].Version } - return s[i].Tool.Name < s[j].Tool.Name + return s[i].Folder < s[j].Folder } func TestLoadTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - ToolsFolders: []string{"downloaded_tools", "tools_builtin"}, + BuiltInToolsFolders: []string{"downloaded_tools", "tools_builtin"}, } loader := builder.ToolsLoader{} err := loader.Run(ctx) NoError(t, err) - tools := ctx.RequiredTools - require.Equal(t, 6, len(tools)) + tools := ctx.AllTools + require.Equal(t, 8, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) + require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "avr-gcc", tools[idx].Tool.Name) - require.Equal(t, "4.8.1-arduino5", tools[idx].Version) + require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "avrdude", tools[idx].Tool.Name) - require.Equal(t, "6.0.1-arduino5", tools[idx].Version) + require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) + require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + idx++ + require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Tool.Name) - require.Equal(t, "1.5-arduino", tools[idx].Version) + require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) + require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + idx++ + require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Tool.Name) - require.Equal(t, "1.6.1-arduino", tools[idx].Version) + require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "ctags", tools[idx].Tool.Name) - require.Equal(t, "5.8-arduino11", tools[idx].Version) + require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) } func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := &types.Context{ - ToolsFolders: []string{"downloaded_board_manager_stuff"}, + HardwareFolders: []string{"downloaded_board_manager_stuff"}, } - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) + NoError(t, (&builder.HardwareLoader{}).Run(ctx)) + NoError(t, (&builder.ToolsLoader{}).Run(ctx)) - tools := ctx.RequiredTools + tools := ctx.AllTools require.Equal(t, 3, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "CMSIS", tools[idx].Tool.Name) - require.Equal(t, "4.0.0-atmel", tools[idx].Version) + require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) + require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "openocd", tools[idx].Tool.Name) - require.Equal(t, "0.9.0-arduino", tools[idx].Version) + require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) } @@ -130,48 +128,49 @@ func TestLoadLotsOfTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - ToolsFolders: []string{"downloaded_tools", "tools_builtin", "downloaded_board_manager_stuff"}, + HardwareFolders: []string{"downloaded_board_manager_stuff"}, + BuiltInToolsFolders: []string{"downloaded_tools", "tools_builtin"}, } - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) + NoError(t, (&builder.HardwareLoader{}).Run(ctx)) + NoError(t, (&builder.ToolsLoader{}).Run(ctx)) - tools := ctx.RequiredTools - require.Equal(t, 8, len(tools)) + tools := ctx.AllTools + require.Equal(t, 11, len(tools)) sort.Sort(ByToolIDAndVersion(tools)) idx := 0 - require.Equal(t, "CMSIS", tools[idx].Tool.Name) - require.Equal(t, "4.0.0-atmel", tools[idx].Version) + require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) idx++ - require.Equal(t, "arm-none-eabi-gcc", tools[idx].Tool.Name) - require.Equal(t, "4.8.3-2014q1", tools[idx].Version) + require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) + require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) + idx++ + require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) idx++ - require.Equal(t, "avr-gcc", tools[idx].Tool.Name) - require.Equal(t, "4.8.1-arduino5", tools[idx].Version) + require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "avrdude", tools[idx].Tool.Name) - require.Equal(t, "6.0.1-arduino5", tools[idx].Version) + require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) + require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + idx++ + require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Tool.Name) - require.Equal(t, "1.5-arduino", tools[idx].Version) + require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) + require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + idx++ + require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "bossac", tools[idx].Tool.Name) - require.Equal(t, "1.6.1-arduino", tools[idx].Version) + require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) idx++ - require.Equal(t, "ctags", tools[idx].Tool.Name) - require.Equal(t, "5.8-arduino11", tools[idx].Version) + require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) idx++ - require.Equal(t, "openocd", tools[idx].Tool.Name) - require.Equal(t, "0.9.0-arduino", tools[idx].Version) + require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) } diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go index b604d6e0..fd5bcf9e 100644 --- a/test/try_build_of_problematic_sketch_test.go +++ b/test/try_build_of_problematic_sketch_test.go @@ -31,11 +31,12 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" "os" "path/filepath" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" ) func TestTryBuild001(t *testing.T) { @@ -222,7 +223,7 @@ func makeDefaultContext(t *testing.T) *types.Context { ctx := &types.Context{ HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - ToolsFolders: []string{"downloaded_tools", "downloaded_board_manager_stuff"}, + BuiltInToolsFolders: []string{"downloaded_tools"}, BuiltInLibrariesFolders: []string{"downloaded_libraries"}, OtherLibrariesFolders: []string{"libraries"}, FQBN: "arduino:avr:leonardo", diff --git a/tools_loader.go b/tools_loader.go index 9aa065b1..4f3903d4 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -31,16 +31,12 @@ package builder import ( "fmt" - "os" "path/filepath" "strings" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" + "github.com/bcmi-labs/arduino-cli/cores/packagemanager" + "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/bcmi-labs/arduino-cli/cores" ) type ToolsLoader struct{} @@ -70,159 +66,17 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { } } - tools := []*cores.ToolRelease{} - - for _, folder := range builtinFolders { - builtinToolsVersionsFile, err := findBuiltinToolsVersionsFile(folder) - if err != nil { - return i18n.WrapError(err) - } - - if builtinToolsVersionsFile == "" { - folders = append(folders, folder) - continue - } - - err = loadToolsFrom(&tools, builtinToolsVersionsFile) - if err != nil { - return i18n.WrapError(err) - } - } - - for _, folder := range folders { - subfolders, err := collectAllToolsFolders(folder) - if err != nil { - return i18n.WrapError(err) - } - - for _, subfolder := range subfolders { - err = loadToolsFromFolderStructure(&tools, subfolder) - if err != nil { - return i18n.WrapError(err) - } - } - } - - ctx.RequiredTools = tools - - return nil -} - -func collectAllToolsFolders(from string) ([]string, error) { - folders := []string{} - walkFunc := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return nil - } - - if !info.IsDir() { - return nil - } - - rel, err := filepath.Rel(from, currentPath) - if err != nil { - return i18n.WrapError(err) - } - depth := len(strings.Split(rel, string(os.PathSeparator))) - - if info.Name() == constants.FOLDER_TOOLS && depth == 2 { - folders = append(folders, currentPath) - } else if depth > 2 { - return filepath.SkipDir - } - - return nil - } - err := gohasissues.Walk(from, walkFunc) - - if len(folders) == 0 { - folders = append(folders, from) - } - - return folders, i18n.WrapError(err) -} - -func toolsSliceContains(tools *[]*cores.ToolRelease, name, version string) bool { - for _, tool := range *tools { - if name == tool.Tool.Name && version == tool.Version { - return true - } - } - return false -} - -func loadToolsFrom(tools *[]*cores.ToolRelease, builtinToolsVersionsFilePath string) error { - rows, err := utils.ReadFileToRows(builtinToolsVersionsFilePath) - if err != nil { - return i18n.WrapError(err) - } - - folder, err := filepath.Abs(filepath.Dir(builtinToolsVersionsFilePath)) - if err != nil { - return i18n.WrapError(err) - } - - for _, row := range rows { - row = strings.TrimSpace(row) - if row != "" { - rowParts := strings.Split(row, "=") - toolName := strings.Split(rowParts[0], ".")[1] - toolVersion := rowParts[1] - if !toolsSliceContains(tools, toolName, toolVersion) { - *tools = append(*tools, - &cores.ToolRelease{ - Tool: &cores.Tool{Name: toolName}, - Version: toolVersion, - Folder: folder}) - } - } - } - - return nil -} - -func findBuiltinToolsVersionsFile(folder string) (string, error) { - builtinToolsVersionsFilePath := "" - findBuiltInToolsVersionsTxt := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return nil - } + pm := packagemanager.PackageManager() + pm.LoadToolsFromBundleDirectories(builtinFolders) - if builtinToolsVersionsFilePath != "" { - return nil - } - if filepath.Base(currentPath) == "builtin_tools_versions.txt" { - builtinToolsVersionsFilePath = currentPath - } - return nil - } - err := gohasissues.Walk(folder, findBuiltInToolsVersionsTxt) - return builtinToolsVersionsFilePath, i18n.WrapError(err) -} + ctx.AllTools = pm.GetAllInstalledToolsReleases() -func loadToolsFromFolderStructure(tools *[]*cores.ToolRelease, folder string) error { - toolsNames, err := utils.ReadDirFiltered(folder, utils.FilterDirs) - if err != nil { - return i18n.WrapError(err) - } - for _, toolName := range toolsNames { - toolVersions, err := utils.ReadDirFiltered(filepath.Join(folder, toolName.Name()), utils.FilterDirs) + if ctx.TargetBoard != nil { + requiredTools, err := pm.FindToolsRequiredForBoard(ctx.TargetBoard) if err != nil { - return i18n.WrapError(err) - } - for _, toolVersion := range toolVersions { - toolFolder, err := filepath.Abs(filepath.Join(folder, toolName.Name(), toolVersion.Name())) - if err != nil { - return i18n.WrapError(err) - } - if !toolsSliceContains(tools, toolName.Name(), toolVersion.Name()) { - *tools = append(*tools, - &cores.ToolRelease{ - Tool: &cores.Tool{Name: toolName.Name()}, - Version: toolVersion.Name(), - Folder: toolFolder}) - } + return err } + ctx.RequiredTools = requiredTools } return nil diff --git a/types/context.go b/types/context.go index fa0a17f9..de8a1ca8 100644 --- a/types/context.go +++ b/types/context.go @@ -26,6 +26,7 @@ type Context struct { BuildOptionsJsonPrevious string Hardware *cores.Packages + AllTools []*cores.ToolRelease RequiredTools []*cores.ToolRelease TargetBoard *cores.Board TargetPackage *cores.Package From d203490d9a6494912b1e1dcd32f6a79617346eb9 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 13 Mar 2018 12:07:28 +0100 Subject: [PATCH 09/57] PackageManager is no more a singleton --- hardware_loader.go | 4 ++-- test/helper_tools_downloader.go | 6 ------ test/tools_loader_test.go | 5 ++--- tools_loader.go | 4 +--- types/context.go | 3 +++ 5 files changed, 8 insertions(+), 14 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index 15f04e61..9452b6bf 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -38,11 +38,11 @@ import ( type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { - pm := packagemanager.PackageManager() - pm.Clear() + pm := packagemanager.NewPackageManager() if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { return i18n.WrapError(err) } + ctx.PackageManager = pm ctx.Hardware = pm.GetPackages() return nil } diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index efe9db45..cfce881c 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -42,8 +42,6 @@ import ( "strings" "testing" - "github.com/bcmi-labs/arduino-cli/cores/packagemanager" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" @@ -85,10 +83,6 @@ type Core struct { } func DownloadCoresAndToolsAndLibraries(t *testing.T) { - pm := packagemanager.PackageManager() - pm.Clear() - pm.DisableDebugOutput() - cores := []Core{ Core{Maintainer: "arduino", Arch: "avr", Version: "1.6.10"}, Core{Maintainer: "arduino", Arch: "sam", Version: "1.6.7"}, diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 55a49900..252c0868 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -64,9 +64,8 @@ func TestLoadTools(t *testing.T) { BuiltInToolsFolders: []string{"downloaded_tools", "tools_builtin"}, } - loader := builder.ToolsLoader{} - err := loader.Run(ctx) - NoError(t, err) + NoError(t, (&builder.HardwareLoader{}).Run(ctx)) + NoError(t, (&builder.ToolsLoader{}).Run(ctx)) tools := ctx.AllTools require.Equal(t, 8, len(tools)) diff --git a/tools_loader.go b/tools_loader.go index 4f3903d4..42cf3426 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -34,8 +34,6 @@ import ( "path/filepath" "strings" - "github.com/bcmi-labs/arduino-cli/cores/packagemanager" - "github.com/arduino/arduino-builder/types" ) @@ -66,7 +64,7 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { } } - pm := packagemanager.PackageManager() + pm := ctx.PackageManager pm.LoadToolsFromBundleDirectories(builtinFolders) ctx.AllTools = pm.GetAllInstalledToolsReleases() diff --git a/types/context.go b/types/context.go index de8a1ca8..60325f20 100644 --- a/types/context.go +++ b/types/context.go @@ -3,6 +3,8 @@ package types import ( "strings" + "github.com/bcmi-labs/arduino-cli/cores/packagemanager" + "github.com/arduino/arduino-builder/i18n" "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/cores" @@ -25,6 +27,7 @@ type Context struct { BuildOptionsJson string BuildOptionsJsonPrevious string + PackageManager *packagemanager.PackageManager Hardware *cores.Packages AllTools []*cores.ToolRelease RequiredTools []*cores.ToolRelease From d9b4541259ac280608abc0191ed806631f516cec Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 14 Mar 2018 18:27:01 +0100 Subject: [PATCH 10/57] Removed a bunch of unused functions/identifiers --- add_additional_entries_to_context.go | 2 +- add_build_board_property_if_missing.go | 2 +- arduino-builder/main.go | 8 ---- builder_utils/utils.go | 8 ++-- constants/constants.go | 14 ------- gcc_preproc_runner.go | 2 +- gcc_preproc_source_saver.go | 53 -------------------------- print_used_libraries_if_verbose.go | 3 +- resolve_library.go | 23 ----------- types/context.go | 1 - types/types.go | 6 --- utils/utils.go | 51 ------------------------- 12 files changed, 9 insertions(+), 164 deletions(-) delete mode 100644 gcc_preproc_source_saver.go diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index 49fb0113..bc277f4c 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -40,7 +40,7 @@ import ( type AddAdditionalEntriesToContext struct{} -func (s *AddAdditionalEntriesToContext) Run(ctx *types.Context) error { +func (*AddAdditionalEntriesToContext) Run(ctx *types.Context) error { if ctx.BuildPath != "" { buildPath := ctx.BuildPath preprocPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_PREPROC)) diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go index 38c64802..8c19e15a 100644 --- a/add_build_board_property_if_missing.go +++ b/add_build_board_property_if_missing.go @@ -39,7 +39,7 @@ import ( type AddBuildBoardPropertyIfMissing struct{} -func (s *AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { +func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { packages := ctx.Hardware logger := ctx.GetLogger() diff --git a/arduino-builder/main.go b/arduino-builder/main.go index d2ca98c4..174c6666 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -375,14 +375,6 @@ func toSliceOfUnquoted(value []string) ([]string, error) { return values, nil } -func printError(err error, printStackTrace bool) { - if printStackTrace { - printCompleteError(err) - } else { - printErrorMessageAndFlagUsage(err) - } -} - func printCompleteError(err error) { err = i18n.WrapError(err) fmt.Fprintln(os.Stderr, err.(*errors.Error).ErrorStack()) diff --git a/builder_utils/utils.go b/builder_utils/utils.go index 139ad770..5be3b483 100644 --- a/builder_utils/utils.go +++ b/builder_utils/utils.go @@ -355,7 +355,7 @@ func ArchiveCompiledFiles(buildPath string, archiveFile string, objectFiles []st } func ExecRecipe(properties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, echoOutput bool, logger i18n.Logger) ([]byte, error) { - command, err := PrepareCommandForRecipe(properties, recipe, removeUnsetProperties, echoCommandLine, echoOutput, logger) + command, err := PrepareCommandForRecipe(properties, recipe, removeUnsetProperties, echoCommandLine, logger) if err != nil { return nil, i18n.WrapError(err) } @@ -375,7 +375,7 @@ func ExecRecipe(properties properties.Map, recipe string, removeUnsetProperties return bytes, i18n.WrapError(err) } -func PrepareCommandForRecipe(buildProperties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, echoOutput bool, logger i18n.Logger) (*exec.Cmd, error) { +func PrepareCommandForRecipe(buildProperties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, logger i18n.Logger) (*exec.Cmd, error) { pattern := buildProperties[recipe] if pattern == constants.EMPTY_STRING { return nil, i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, recipe) @@ -399,8 +399,8 @@ func PrepareCommandForRecipe(buildProperties properties.Map, recipe string, remo return command, nil } -func ExecRecipeCollectStdErr(buildProperties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, echoOutput bool, logger i18n.Logger) (string, error) { - command, err := PrepareCommandForRecipe(buildProperties, recipe, removeUnsetProperties, echoCommandLine, echoOutput, logger) +func ExecRecipeCollectStdErr(buildProperties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, logger i18n.Logger) (string, error) { + command, err := PrepareCommandForRecipe(buildProperties, recipe, removeUnsetProperties, echoCommandLine, logger) if err != nil { return "", i18n.WrapError(err) } diff --git a/constants/constants.go b/constants/constants.go index a4a39117..0c464865 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -59,9 +59,7 @@ const BUILD_PROPERTIES_TOOLS_KEY = "tools" const BUILD_PROPERTIES_VID = "vid" const CTAGS = "ctags" const EMPTY_STRING = "" -const FILE_BUILTIN_TOOLS_VERSIONS_TXT = "builtin_tools_versions.txt" const FILE_CTAGS_TARGET_FOR_GCC_MINUS_E = "ctags_target_for_gcc_minus_e.cpp" -const FILE_GCC_PREPROC_TARGET = "gcc_preproc_target.cpp" const FILE_PLATFORM_KEYS_REWRITE_TXT = "platform.keys.rewrite.txt" const FILE_INCLUDES_CACHE = "includes.cache" const FOLDER_BOOTLOADERS = "bootloaders" @@ -128,7 +126,6 @@ const MSG_BUILD_OPTIONS_CHANGED = "Build options changed, rebuilding all" const MSG_CANT_FIND_SKETCH_IN_PATH = "Unable to find {0} in {1}" const MSG_FQBN_INVALID = "{0} is not a valid fully qualified board name. Required format is targetPackageName:targetPlatformName:targetBoardName." const MSG_INVALID_QUOTING = "Invalid quoting: no closing [{0}] char found." -const MSG_IGNORED_BUILTIN_TOOLS_TXT = "Skipping {0}; please consider removing that file since it may hurt older Arduino installations" const MSG_LIB_LEGACY = "(legacy)" const MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR = "Multiple libraries were found for \"{0}\"" const MSG_LIBRARIES_NOT_USED = " Not used: {0}" @@ -138,7 +135,6 @@ const MSG_LIBRARY_INCOMPATIBLE_ARCH = "WARNING: library {0} claims to run on {1} const MSG_LOOKING_FOR_RECIPES = "Looking for recipes like {0}*{1}" const MSG_MISSING_BUILD_BOARD = "Warning: Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}" const MSG_MISSING_CORE_FOR_BOARD = "Selected board depends on '{0}' core (not installed)." -const MSG_MUST_BE_A_FOLDER = "{0} must be a folder" const MSG_PACKAGE_UNKNOWN = "{0}: Unknown package" const MSG_PATTERN_MISSING = "{0} pattern is missing" const MSG_PLATFORM_UNKNOWN = "Platform {0} (package {1}) is unknown" @@ -155,10 +151,6 @@ const MSG_SIZER_DATA_TOO_BIG = "Not enough memory; see http://www.arduino.cc/en/ const MSG_SIZER_LOW_MEMORY = "Low memory available, stability problems may occur." const MSG_SIZER_ERROR_NO_RULE = "Couldn't determine program size" const MSG_SKETCH_CANT_BE_IN_BUILDPATH = "Sketch cannot be located in build path. Please specify a different build path" -const MSG_SKIPPING_TAG_ALREADY_DEFINED = "Skipping tag {0} because prototype is already defined" -const MSG_SKIPPING_TAG_BECAUSE_HAS_FIELD = "Skipping tag {0} because it has field {0}" -const MSG_SKIPPING_TAG_WITH_REASON = "Skipping tag {0}. Reason: {1}" -const MSG_UNHANDLED_TYPE_IN_CONTEXT = "Unhandled type {0} in context key {1}" const MSG_UNKNOWN_SKETCH_EXT = "Unknown sketch file extension: {0}" const MSG_USING_LIBRARY_AT_VERSION = "Using library {0} at version {1} in folder: {2} {3}" const MSG_USING_LIBRARY = "Using library {0} in folder: {1} {2}" @@ -167,16 +159,12 @@ const MSG_USING_CORE = "Using core '{0}' from platform in folder: {1}" const MSG_USING_PREVIOUS_COMPILED_FILE = "Using previously compiled file: {0}" const MSG_USING_CACHED_INCLUDES = "Using cached library dependencies for file: {0}" const MSG_WARNING_LIB_INVALID_CATEGORY = "WARNING: Category '{0}' in library {1} is not valid. Setting to '{2}'" -const MSG_WARNING_PLATFORM_MISSING_VALUE = "Warning: platform.txt from core '{0}' misses property '{1}', using default value '{2}'. Consider upgrading this core." const MSG_WARNING_PLATFORM_OLD_VALUES = "Warning: platform.txt from core '{0}' contains deprecated {1}, automatically converted to {2}. Consider upgrading this core." const MSG_WARNING_SPURIOUS_FILE_IN_LIB = "WARNING: Spurious {0} folder in '{1}' library" -const MSG_WRONG_PROPERTIES_FILE = "Property line '{0}' in file {1} is invalid" -const MSG_WRONG_PROPERTIES = "Property line '{0}' is invalid" const PACKAGE_NAME = "name" const PACKAGE_TOOLS = "tools" const PLATFORM_ARCHITECTURE = "architecture" const PLATFORM_NAME = "name" -const PLATFORM_REWRITE_ADDED = "added" const PLATFORM_REWRITE_NEW = "new" const PLATFORM_REWRITE_OLD = "old" const PLATFORM_URL = "url" @@ -184,13 +172,11 @@ const PLATFORM_VERSION = "version" const PROPERTY_WARN_DATA_PERCENT = "build.warn_data_percentage" const PROPERTY_UPLOAD_MAX_SIZE = "upload.maximum_size" const PROPERTY_UPLOAD_MAX_DATA_SIZE = "upload.maximum_data_size" -const PROGRAMMER_NAME = "name" const RECIPE_AR_PATTERN = "recipe.ar.pattern" const RECIPE_C_COMBINE_PATTERN = "recipe.c.combine.pattern" const RECIPE_C_PATTERN = "recipe.c.o.pattern" const RECIPE_CPP_PATTERN = "recipe.cpp.o.pattern" const RECIPE_SIZE_PATTERN = "recipe.size.pattern" -const RECIPE_PREPROC_INCLUDES = "recipe.preproc.includes" const RECIPE_PREPROC_MACROS = "recipe.preproc.macros" const RECIPE_S_PATTERN = "recipe.S.o.pattern" const RECIPE_SIZE_REGEXP = "recipe.size.regex" diff --git a/gcc_preproc_runner.go b/gcc_preproc_runner.go index b571cacc..40ff59e7 100644 --- a/gcc_preproc_runner.go +++ b/gcc_preproc_runner.go @@ -90,7 +90,7 @@ func (s *GCCPreprocRunnerForDiscoveringIncludes) Run(ctx *types.Context) error { properties[constants.RECIPE_PREPROC_MACROS] = GeneratePreprocPatternFromCompile(properties[constants.RECIPE_CPP_PATTERN]) } - stderr, err := builder_utils.ExecRecipeCollectStdErr(properties, constants.RECIPE_PREPROC_MACROS, true, verbose, false, logger) + stderr, err := builder_utils.ExecRecipeCollectStdErr(properties, constants.RECIPE_PREPROC_MACROS, true, verbose, logger) if err != nil { return i18n.WrapError(err) } diff --git a/gcc_preproc_source_saver.go b/gcc_preproc_source_saver.go deleted file mode 100644 index 556cd276..00000000 --- a/gcc_preproc_source_saver.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -// XXX: OBSOLETE? - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" -) - -type GCCPreprocSourceSaver struct{} - -func (s *GCCPreprocSourceSaver) Run(ctx *types.Context) error { - preprocPath := ctx.PreprocPath - err := utils.EnsureFolderExists(preprocPath) - if err != nil { - return i18n.WrapError(err) - } - - err = utils.WriteFile(filepath.Join(preprocPath, constants.FILE_GCC_PREPROC_TARGET), ctx.Source) - return i18n.WrapError(err) -} diff --git a/print_used_libraries_if_verbose.go b/print_used_libraries_if_verbose.go index 3489c9a0..3cd4a8dc 100644 --- a/print_used_libraries_if_verbose.go +++ b/print_used_libraries_if_verbose.go @@ -30,9 +30,10 @@ package builder import ( + "time" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "time" ) type PrintUsedLibrariesIfVerbose struct{} diff --git a/resolve_library.go b/resolve_library.go index 488fc1d3..ef217a1e 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -130,15 +130,6 @@ func filterOutLibraryFrom(libraries []*types.Library, libraryToRemove *types.Lib return filteredOutLibraries } -func findLibraryIn(libraries []*types.Library, library *types.Library) *types.Library { - for _, lib := range libraries { - if lib == library { - return lib - } - } - return nil -} - func libraryCompatibleWithPlatform(library *types.Library, platform *cores.PlatformRelease) (bool, bool) { if len(library.Archs) == 0 { return true, true @@ -173,20 +164,6 @@ func librariesCompatibleWithPlatform(libraries []*types.Library, platform *cores return compatibleLibraries } -func librariesWithinPlatform(libraries []*types.Library, platform *cores.PlatformRelease) []*types.Library { - librariesWithinSpecifiedPlatform := []*types.Library{} - for _, library := range libraries { - cleanPlatformFolder := filepath.Clean(platform.Folder) - cleanLibraryFolder := filepath.Clean(library.SrcFolder) - if strings.Contains(cleanLibraryFolder, cleanPlatformFolder) { - librariesWithinSpecifiedPlatform = append(librariesWithinSpecifiedPlatform, library) - } - } - - return librariesWithinSpecifiedPlatform - -} - func findBestLibraryWithHeader(header string, libraries []*types.Library) *types.Library { headerName := strings.Replace(header, filepath.Ext(header), constants.EMPTY_STRING, -1) diff --git a/types/context.go b/types/context.go index 60325f20..03774ccd 100644 --- a/types/context.go +++ b/types/context.go @@ -69,7 +69,6 @@ type Context struct { LibrariesResolutionResults map[string]LibraryResolutionResult IncludeJustFound string IncludeFolders []string - OutputGccMinusM string // C++ Parsing CTagsOutput string diff --git a/types/types.go b/types/types.go index 83e49c8e..d36586be 100644 --- a/types/types.go +++ b/types/types.go @@ -185,11 +185,6 @@ type PlatforKeyRewrite struct { NewValue string } -type KeyValuePair struct { - Key string - Value string -} - type Prototype struct { FunctionName string File string @@ -226,7 +221,6 @@ type CTag struct { Signature string Prototype string - Function string PrototypeModifiers string } diff --git a/utils/utils.go b/utils/utils.go index 318b3984..9b85850d 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -46,14 +46,6 @@ import ( "github.com/arduino/arduino-builder/types" ) -func KeysOfMapOfStringInterface(input map[string]interface{}) []string { - var keys []string - for key, _ := range input { - keys = append(keys, key) - } - return keys -} - func KeysOfMapOfString(input map[string]string) []string { var keys []string for key, _ := range input { @@ -254,24 +246,11 @@ func PrepareCommand(pattern string, logger i18n.Logger) (*exec.Cmd, error) { return PrepareCommandFilteredArgs(pattern, filterEmptyArg, logger) } -func MapHas(aMap map[string]interface{}, key string) bool { - _, ok := aMap[key] - return ok -} - func MapStringStringHas(aMap map[string]string, key string) bool { _, ok := aMap[key] return ok } -func SliceToMapStringBool(keys []string, value bool) map[string]bool { - aMap := make(map[string]bool) - for _, key := range keys { - aMap[key] = value - } - return aMap -} - func AbsolutizePaths(files []string) ([]string, error) { for idx, file := range files { absFile, err := filepath.Abs(file) @@ -295,32 +274,6 @@ func ReadFileToRows(file string) ([]string, error) { return strings.Split(txt, "\n"), nil } -func TheOnlySubfolderOf(folder string) (string, error) { - subfolders, err := ReadDirFiltered(folder, FilterDirs) - if err != nil { - return constants.EMPTY_STRING, i18n.WrapError(err) - } - - if len(subfolders) != 1 { - return constants.EMPTY_STRING, nil - } - - return subfolders[0].Name(), nil -} - -func FilterOutFoldersByNames(folders []os.FileInfo, names ...string) []os.FileInfo { - filterNames := SliceToMapStringBool(names, true) - - var filtered []os.FileInfo - for _, folder := range folders { - if !filterNames[folder.Name()] { - filtered = append(filtered, folder) - } - } - - return filtered -} - type CheckExtensionFunc func(ext string) bool func FindFilesInFolder(files *[]string, folder string, extensions CheckExtensionFunc, recurse bool) error { @@ -430,10 +383,6 @@ func LogIfVerbose(level string, format string, args ...interface{}) types.Comman return &loggerAction{true, level, format, args} } -func LogThis(level string, format string, args ...interface{}) types.Command { - return &loggerAction{false, level, format, args} -} - // Returns the given string as a quoted string for use with the C // preprocessor. This adds double quotes around it and escapes any // double quotes and backslashes in the string. From 6c1d8536e3019e7fe4ec3c2f7ab6baed76106aa6 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 15 Mar 2018 19:04:04 +0100 Subject: [PATCH 11/57] Moved addAdditionalPropertiesToTargetBoard function in arduino-cli --- builder.go | 1 - constants/constants.go | 2 -- target_board_resolver.go | 38 ++++++++------------------------------ 3 files changed, 8 insertions(+), 33 deletions(-) diff --git a/builder.go b/builder.go index d5b8eff7..745566d1 100644 --- a/builder.go +++ b/builder.go @@ -64,7 +64,6 @@ var LIBRARY_CATEGORIES = map[string]bool{ const DEFAULT_DEBUG_LEVEL = 5 const DEFAULT_WARNINGS_LEVEL = "none" const DEFAULT_SOFTWARE = "ARDUINO" -const DEFAULT_BUILD_CORE = "arduino" type Builder struct{} diff --git a/constants/constants.go b/constants/constants.go index 0c464865..de9ecb28 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -30,7 +30,6 @@ package constants -const BOARD_PROPERTIES_MENU = "menu" const BUILD_OPTIONS_FILE = "build.options.json" const BUILD_PROPERTIES_ARCHIVE_FILE = "archive_file" const BUILD_PROPERTIES_ARCHIVE_FILE_PATH = "archive_file_path" @@ -38,7 +37,6 @@ const BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK = "architecture.override_check" const BUILD_PROPERTIES_BOOTLOADER_FILE = "bootloader.file" const BUILD_PROPERTIES_BOOTLOADER_NOBLINK = "bootloader.noblink" const BUILD_PROPERTIES_BUILD_BOARD = "build.board" -const BUILD_PROPERTIES_BUILD_CORE = "build.core" const BUILD_PROPERTIES_BUILD_CORE_PATH = "build.core.path" const BUILD_PROPERTIES_BUILD_MCU = "build.mcu" const BUILD_PROPERTIES_BUILD_VARIANT_PATH = "build.variant.path" diff --git a/target_board_resolver.go b/target_board_resolver.go index 4df79ef0..2643fb15 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -35,7 +35,6 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/bcmi-labs/arduino-cli/cores" ) @@ -80,12 +79,16 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { ctx.TargetBoard = targetBoard if len(fqbnParts) > 3 { - addAdditionalPropertiesToTargetBoard(targetBoard, fqbnParts[3]) + if props, err := targetBoard.GeneratePropertiesForConfiguration(fqbnParts[3]); err != nil { + i18n.ErrorfWithLogger(logger, "Error in FQBN: %s", err) + } else { + targetBoard.Properties = props + } } - core := targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_CORE] - if core == constants.EMPTY_STRING { - core = DEFAULT_BUILD_CORE + core := targetBoard.Properties["build.core"] + if core == "" { + core = "arduino" } var corePlatform *cores.PlatformRelease @@ -116,28 +119,3 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { return nil } - -func addAdditionalPropertiesToTargetBoard(board *cores.Board, options string) { - optionsParts := strings.Split(options, ",") - optionsParts = utils.Map(optionsParts, utils.TrimSpace) - - for _, optionPart := range optionsParts { - parts := strings.Split(optionPart, "=") - parts = utils.Map(parts, utils.TrimSpace) - - key := parts[0] - value := parts[1] - if key != constants.EMPTY_STRING && value != constants.EMPTY_STRING { - menu := board.Properties.SubTree(constants.BOARD_PROPERTIES_MENU) - if len(menu) == 0 { - return - } - propertiesOfKey := menu.SubTree(key) - if len(propertiesOfKey) == 0 { - return - } - propertiesOfKeyValue := propertiesOfKey.SubTree(value) - board.Properties.Merge(propertiesOfKeyValue) - } - } -} From 85c6dd0bb90d0953dcd59a04ba5350856f2ba667 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 23 Mar 2018 11:28:19 +0100 Subject: [PATCH 12/57] Now ctags has his own properties hardcoded This avoid the overly complex properties-map handling with the ctags specific platforms.txt hanging around. --- ...operties_from_parent_platform_txt_files.go | 7 +-- ctags/ctags_properties.go | 47 +++++++++++++++++++ hardware/platform.txt | 12 ----- 3 files changed, 49 insertions(+), 17 deletions(-) create mode 100644 ctags/ctags_properties.go delete mode 100644 hardware/platform.txt diff --git a/add_missing_build_properties_from_parent_platform_txt_files.go b/add_missing_build_properties_from_parent_platform_txt_files.go index a6be7bdd..9c5cb7c1 100644 --- a/add_missing_build_properties_from_parent_platform_txt_files.go +++ b/add_missing_build_properties_from_parent_platform_txt_files.go @@ -30,20 +30,17 @@ package builder import ( + "github.com/arduino/arduino-builder/ctags" "github.com/arduino/arduino-builder/types" ) type AddMissingBuildPropertiesFromParentPlatformTxtFiles struct{} func (s *AddMissingBuildPropertiesFromParentPlatformTxtFiles) Run(ctx *types.Context) error { - packages := ctx.Hardware - // targetPackage := ctx.TargetPackage buildProperties := ctx.BuildProperties - newBuildProperties := packages.Properties.Clone() - // newBuildProperties.Merge(targetPackage.Properties) + newBuildProperties := ctags.CtagsProperties.Clone() newBuildProperties.Merge(buildProperties) - ctx.BuildProperties = newBuildProperties return nil diff --git a/ctags/ctags_properties.go b/ctags/ctags_properties.go new file mode 100644 index 00000000..897e36a8 --- /dev/null +++ b/ctags/ctags_properties.go @@ -0,0 +1,47 @@ +/* + * This file is part of Arduino Builder. + * + * Arduino Builder is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * As a special exception, you may use this file as part of a free software + * library without restriction. Specifically, if other files instantiate + * templates or use macros or inline functions from this file, or you compile + * this file and link it with other files to produce an executable, this + * file does not by itself cause the resulting executable to be covered by + * the GNU General Public License. This exception does not however + * invalidate any other reasons why the executable file might be covered by + * the GNU General Public License. + * + * Copyright 2015-2018 Arduino LLC (http://www.arduino.cc/) + */ + +package ctags + +import properties "github.com/arduino/go-properties-map" + +// CtagsProperties are the platform properties needed to run ctags +var CtagsProperties = properties.Map{ + // Ctags + "tools.ctags.path": "{runtime.tools.ctags.path}", + "tools.ctags.cmd.path": "{path}/ctags", + "tools.ctags.pattern": `"{cmd.path}" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "{source_file}"`, + + // additional entries + "tools.avrdude.path": "{runtime.tools.avrdude.path}", + + "preproc.macros.flags": "-w -x c++ -E -CC", + //"preproc.macros.compatibility_flags": `{build.mbed_api_include} {build.nRF51822_api_include} {build.ble_api_include} {compiler.libsam.c.flags} {compiler.arm.cmsis.path} {build.variant_system_include}`, + //"recipe.preproc.macros": `"{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} {preproc.macros.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {preproc.macros.compatibility_flags} {includes} "{source_file}" -o "{preprocessed_file_path}"`, +} diff --git a/hardware/platform.txt b/hardware/platform.txt deleted file mode 100644 index ca8df1f7..00000000 --- a/hardware/platform.txt +++ /dev/null @@ -1,12 +0,0 @@ -# ctags -# ------------------------------ -tools.ctags.path={runtime.tools.ctags.path} -tools.ctags.cmd.path={path}/ctags -tools.ctags.pattern="{cmd.path}" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "{source_file}" - -# additional entries -tools.avrdude.path={runtime.tools.avrdude.path} - -preproc.macros.flags=-w -x c++ -E -CC -#preproc.macros.compatibility_flags={build.mbed_api_include} {build.nRF51822_api_include} {build.ble_api_include} {compiler.libsam.c.flags} {compiler.arm.cmsis.path} {build.variant_system_include} -#recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} {preproc.macros.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {preproc.macros.compatibility_flags} {includes} "{source_file}" -o "{preprocessed_file_path}" From e62ce9a4a9f02f9e88a98517cf655d0440b03c0a Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 17 Apr 2018 16:34:48 +0200 Subject: [PATCH 13/57] Updated imports for arduino-cli package --- add_additional_entries_to_context.go | 2 +- hardware_loader.go | 2 +- resolve_library.go | 2 +- rewrite_hardware_keys.go | 2 +- setup_build_properties.go | 2 +- target_board_resolver.go | 2 +- test/rewrite_hardware_keys_test.go | 2 +- test/tools_loader_test.go | 2 +- types/context.go | 5 ++--- warn_about_platform_rewrites.go | 2 +- 10 files changed, 11 insertions(+), 12 deletions(-) diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index bc277f4c..256a33f7 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type AddAdditionalEntriesToContext struct{} diff --git a/hardware_loader.go b/hardware_loader.go index 9452b6bf..4283af50 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -32,7 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores/packagemanager" + "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" ) type HardwareLoader struct{} diff --git a/resolve_library.go b/resolve_library.go index ef217a1e..ee81fb20 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -36,7 +36,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) func ResolveLibrary(ctx *types.Context, header string) *types.Library { diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go index be5cfa53..5f3ce87a 100644 --- a/rewrite_hardware_keys.go +++ b/rewrite_hardware_keys.go @@ -32,7 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type RewriteHardwareKeys struct{} diff --git a/setup_build_properties.go b/setup_build_properties.go index 7e5c2948..f965165f 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -39,7 +39,7 @@ import ( "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" "github.com/arduino/go-timeutils" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type SetupBuildProperties struct{} diff --git a/target_board_resolver.go b/target_board_resolver.go index 2643fb15..0010c59f 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type TargetBoardResolver struct{} diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go index a2623429..1bb25ecb 100644 --- a/test/rewrite_hardware_keys_test.go +++ b/test/rewrite_hardware_keys_test.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" properties "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/stretchr/testify/require" ) diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 252c0868..14a6bcf7 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/stretchr/testify/require" ) diff --git a/types/context.go b/types/context.go index 03774ccd..599decae 100644 --- a/types/context.go +++ b/types/context.go @@ -3,11 +3,10 @@ package types import ( "strings" - "github.com/bcmi-labs/arduino-cli/cores/packagemanager" - "github.com/arduino/arduino-builder/i18n" "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" ) // Context structure diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go index 15ca5cc5..7ff2c5fa 100644 --- a/warn_about_platform_rewrites.go +++ b/warn_about_platform_rewrites.go @@ -34,7 +34,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/cores" + "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type WarnAboutPlatformRewrites struct{} From 84387d2d0f9f378b0eef8c71a627caa6bb5bad30 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Sat, 12 May 2018 00:24:06 +0200 Subject: [PATCH 14/57] Moved Library type to arduino-cli --- container_find_includes.go | 3 +- fail_if_imported_library_is_wrong.go | 8 +- libraries_loader.go | 45 ++++++----- phases/libraries_builder.go | 9 ++- resolve_library.go | 81 ++++++++++--------- resolve_library_test.go | 26 +++--- test/helper.go | 3 +- test/libraries_loader_test.go | 68 ++++++++-------- test/sketch_source_merger_test.go | 7 +- .../unused_compiled_libraries_remover_test.go | 14 ++-- types/context.go | 7 +- types/types.go | 62 ++------------ unused_compiled_libraries_remover.go | 10 ++- warn_about_arch_incompatible_libraries.go | 2 +- 14 files changed, 155 insertions(+), 190 deletions(-) diff --git a/container_find_includes.go b/container_find_includes.go index dbd31c71..fd76eef5 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -118,6 +118,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type ContainerFindIncludes struct{} @@ -314,7 +315,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t cache.ExpectFile(sourcePath) includes := ctx.IncludeFolders - if library, ok := sourceFile.Origin.(*types.Library); ok && library.UtilityFolder != "" { + if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityFolder != "" { includes = append(includes, library.UtilityFolder) } if unchanged && cache.valid { diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 2620560c..13ba1394 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -30,11 +30,13 @@ package builder import ( + "os" + "path/filepath" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "os" - "path/filepath" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type FailIfImportedLibraryIsWrong struct{} @@ -56,7 +58,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.Folder) } } - if library.Layout == types.LIBRARY_RECURSIVE { + if library.Layout == libraries.LIBRARY_RECURSIVE { if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY)); err == nil && stat.IsDir() { return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) } diff --git a/libraries_loader.go b/libraries_loader.go index 1730bf44..7cc3fa83 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -39,6 +39,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type LibrariesLoader struct{} @@ -72,7 +73,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { ctx.LibrariesFolders = sortedLibrariesFolders - var libraries []*types.Library + var libs []*libraries.Library for _, libraryFolder := range sortedLibrariesFolders { subFolders, err := utils.ReadDirFiltered(libraryFolder, utils.FilterDirs) if err != nil { @@ -83,14 +84,14 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { if err != nil { return i18n.WrapError(err) } - libraries = append(libraries, library) + libs = append(libs, library) } } - ctx.Libraries = libraries + ctx.Libraries = libs - headerToLibraries := make(map[string][]*types.Library) - for _, library := range libraries { + headerToLibraries := make(map[string][]*libraries.Library) + for _, library := range libs { headers, err := utils.ReadDirFiltered(library.SrcFolder, utils.FilterFilesWithExtensions(".h", ".hpp", ".hh")) if err != nil { return i18n.WrapError(err) @@ -106,14 +107,14 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { return nil } -func makeLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*types.Library, error) { +func makeLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { if _, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)); os.IsNotExist(err) { return makeLegacyLibrary(libraryFolder) } return makeNewLibrary(libraryFolder, debugLevel, logger) } -func addUtilityFolder(library *types.Library) { +func addUtilityFolder(library *libraries.Library) { utilitySourcePath := filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY) stat, err := os.Stat(utilitySourcePath) if err == nil && stat.IsDir() { @@ -121,7 +122,7 @@ func addUtilityFolder(library *types.Library) { } } -func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*types.Library, error) { +func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { libProperties, err := properties.Load(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)) if err != nil { return nil, i18n.WrapError(err) @@ -137,13 +138,13 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* } } - library := &types.Library{} + library := &libraries.Library{} library.Folder = libraryFolder if stat, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC)); err == nil && stat.IsDir() { - library.Layout = types.LIBRARY_RECURSIVE + library.Layout = libraries.LIBRARY_RECURSIVE library.SrcFolder = filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC) } else { - library.Layout = types.LIBRARY_FLAT + library.Layout = libraries.LIBRARY_FLAT library.SrcFolder = libraryFolder addUtilityFolder(library) } @@ -166,9 +167,9 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* if libProperties[constants.LIBRARY_ARCHITECTURES] == constants.EMPTY_STRING { libProperties[constants.LIBRARY_ARCHITECTURES] = constants.LIBRARY_ALL_ARCHS } - library.Archs = []string{} + library.Architectures = []string{} for _, arch := range strings.Split(libProperties[constants.LIBRARY_ARCHITECTURES], ",") { - library.Archs = append(library.Archs, strings.TrimSpace(arch)) + library.Architectures = append(library.Architectures, strings.TrimSpace(arch)) } libProperties[constants.LIBRARY_CATEGORY] = strings.TrimSpace(libProperties[constants.LIBRARY_CATEGORY]) @@ -190,7 +191,7 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* library.Maintainer = strings.TrimSpace(libProperties[constants.LIBRARY_MAINTAINER]) library.Sentence = strings.TrimSpace(libProperties[constants.LIBRARY_SENTENCE]) library.Paragraph = strings.TrimSpace(libProperties[constants.LIBRARY_PARAGRAPH]) - library.URL = strings.TrimSpace(libProperties[constants.LIBRARY_URL]) + library.Website = strings.TrimSpace(libProperties[constants.LIBRARY_URL]) library.IsLegacy = false library.DotALinkage = strings.TrimSpace(libProperties[constants.LIBRARY_DOT_A_LINKAGE]) == "true" library.Precompiled = strings.TrimSpace(libProperties[constants.LIBRARY_PRECOMPILED]) == "true" @@ -200,14 +201,14 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* return library, nil } -func makeLegacyLibrary(libraryFolder string) (*types.Library, error) { - library := &types.Library{ - Folder: libraryFolder, - SrcFolder: libraryFolder, - Layout: types.LIBRARY_FLAT, - Name: filepath.Base(libraryFolder), - Archs: []string{constants.LIBRARY_ALL_ARCHS}, - IsLegacy: true, +func makeLegacyLibrary(libraryFolder string) (*libraries.Library, error) { + library := &libraries.Library{ + Folder: libraryFolder, + SrcFolder: libraryFolder, + Layout: libraries.LIBRARY_FLAT, + Name: filepath.Base(libraryFolder), + Architectures: []string{constants.LIBRARY_ALL_ARCHS}, + IsLegacy: true, } addUtilityFolder(library) return library, nil diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index fda56b80..28cc5834 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -39,6 +39,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC = map[string]bool{".a": true} @@ -74,7 +75,7 @@ func (s *LibrariesBuilder) Run(ctx *types.Context) error { return nil } -func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*types.Library) error { +func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*libraries.Library) error { for _, library := range libraries { if library.Precompiled { @@ -99,7 +100,7 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*types.Lib return nil } -func compileLibraries(libraries []*types.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { +func compileLibraries(libraries []*libraries.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { objectFiles := []string{} for _, library := range libraries { libraryObjectFiles, err := compileLibrary(library, buildPath, buildProperties, includes, verbose, warningsLevel, logger) @@ -113,7 +114,7 @@ func compileLibraries(libraries []*types.Library, buildPath string, buildPropert } -func compileLibrary(library *types.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { +func compileLibrary(library *libraries.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { if verbose { logger.Println(constants.LOG_LEVEL_INFO, "Compiling library \"{0}\"", library.Name) } @@ -143,7 +144,7 @@ func compileLibrary(library *types.Library, buildPath string, buildProperties pr } } - if library.Layout == types.LIBRARY_RECURSIVE { + if library.Layout == libraries.LIBRARY_RECURSIVE { objectFiles, err = builder_utils.CompileFilesRecursive(objectFiles, library.SrcFolder, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) diff --git a/resolve_library.go b/resolve_library.go index ee81fb20..82e867d3 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -37,70 +37,71 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/bcmi-labs/arduino-cli/arduino/cores" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) -func ResolveLibrary(ctx *types.Context, header string) *types.Library { +func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { headerToLibraries := ctx.HeaderToLibraries platforms := []*cores.PlatformRelease{ctx.ActualPlatform, ctx.TargetPlatform} libraryResolutionResults := ctx.LibrariesResolutionResults importedLibraries := ctx.ImportedLibraries - libraries := append([]*types.Library{}, headerToLibraries[header]...) + libs := append([]*libraries.Library{}, headerToLibraries[header]...) - if libraries == nil || len(libraries) == 0 { + if libs == nil || len(libs) == 0 { return nil } - if importedLibraryContainsOneOfCandidates(importedLibraries, libraries) { + if importedLibraryContainsOneOfCandidates(importedLibraries, libs) { return nil } - if len(libraries) == 1 { - return libraries[0] + if len(libs) == 1 { + return libs[0] } - reverse(libraries) + reverse(libs) - var library *types.Library + var library *libraries.Library for _, platform := range platforms { if platform != nil { - library = findBestLibraryWithHeader(header, librariesCompatibleWithPlatform(libraries, platform, true)) + library = findBestLibraryWithHeader(header, librariesCompatibleWithPlatform(libs, platform, true)) } } if library == nil { - library = findBestLibraryWithHeader(header, libraries) + library = findBestLibraryWithHeader(header, libs) } if library == nil { // reorder libraries to promote fully compatible ones for _, platform := range platforms { if platform != nil { - libraries = append(librariesCompatibleWithPlatform(libraries, platform, false), libraries...) + libs = append(librariesCompatibleWithPlatform(libs, platform, false), libs...) } } - library = libraries[0] + library = libs[0] } library = useAlreadyImportedLibraryWithSameNameIfExists(library, importedLibraries) libraryResolutionResults[header] = types.LibraryResolutionResult{ Library: library, - NotUsedLibraries: filterOutLibraryFrom(libraries, library), + NotUsedLibraries: filterOutLibraryFrom(libs, library), } return library } //facepalm. sort.Reverse needs an Interface that implements Len/Less/Swap. It's a slice! What else for reversing it?!? -func reverse(data []*types.Library) { +func reverse(data []*libraries.Library) { for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 { data[i], data[j] = data[j], data[i] } } -func importedLibraryContainsOneOfCandidates(imported []*types.Library, candidates []*types.Library) bool { +func importedLibraryContainsOneOfCandidates(imported []*libraries.Library, candidates []*libraries.Library) bool { for _, i := range imported { for _, j := range candidates { if i == j { @@ -111,7 +112,7 @@ func importedLibraryContainsOneOfCandidates(imported []*types.Library, candidate return false } -func useAlreadyImportedLibraryWithSameNameIfExists(library *types.Library, imported []*types.Library) *types.Library { +func useAlreadyImportedLibraryWithSameNameIfExists(library *libraries.Library, imported []*libraries.Library) *libraries.Library { for _, lib := range imported { if lib.Name == library.Name { return lib @@ -120,9 +121,9 @@ func useAlreadyImportedLibraryWithSameNameIfExists(library *types.Library, impor return library } -func filterOutLibraryFrom(libraries []*types.Library, libraryToRemove *types.Library) []*types.Library { - filteredOutLibraries := []*types.Library{} - for _, lib := range libraries { +func filterOutLibraryFrom(libs []*libraries.Library, libraryToRemove *libraries.Library) []*libraries.Library { + filteredOutLibraries := []*libraries.Library{} + for _, lib := range libs { if lib != libraryToRemove { filteredOutLibraries = append(filteredOutLibraries, lib) } @@ -130,31 +131,31 @@ func filterOutLibraryFrom(libraries []*types.Library, libraryToRemove *types.Lib return filteredOutLibraries } -func libraryCompatibleWithPlatform(library *types.Library, platform *cores.PlatformRelease) (bool, bool) { - if len(library.Archs) == 0 { +func libraryCompatibleWithPlatform(library *libraries.Library, platform *cores.PlatformRelease) (bool, bool) { + if len(library.Architectures) == 0 { return true, true } - if utils.SliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { + if utils.SliceContains(library.Architectures, constants.LIBRARY_ALL_ARCHS) { return true, true } - return utils.SliceContains(library.Archs, platform.Platform.Architecture), false + return utils.SliceContains(library.Architectures, platform.Platform.Architecture), false } -func libraryCompatibleWithAllPlatforms(library *types.Library) bool { - if utils.SliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { +func libraryCompatibleWithAllPlatforms(library *libraries.Library) bool { + if utils.SliceContains(library.Architectures, constants.LIBRARY_ALL_ARCHS) { return true } return false } -func librariesCompatibleWithPlatform(libraries []*types.Library, platform *cores.PlatformRelease, reorder bool) []*types.Library { - var compatibleLibraries []*types.Library - for _, library := range libraries { +func librariesCompatibleWithPlatform(libs []*libraries.Library, platform *cores.PlatformRelease, reorder bool) []*libraries.Library { + var compatibleLibraries []*libraries.Library + for _, library := range libs { compatible, generic := libraryCompatibleWithPlatform(library, platform) if compatible { if !generic && len(compatibleLibraries) != 0 && libraryCompatibleWithAllPlatforms(compatibleLibraries[0]) && reorder == true { //priority inversion - compatibleLibraries = append([]*types.Library{library}, compatibleLibraries...) + compatibleLibraries = append([]*libraries.Library{library}, compatibleLibraries...) } else { compatibleLibraries = append(compatibleLibraries, library) } @@ -164,28 +165,28 @@ func librariesCompatibleWithPlatform(libraries []*types.Library, platform *cores return compatibleLibraries } -func findBestLibraryWithHeader(header string, libraries []*types.Library) *types.Library { +func findBestLibraryWithHeader(header string, libs []*libraries.Library) *libraries.Library { headerName := strings.Replace(header, filepath.Ext(header), constants.EMPTY_STRING, -1) - var library *types.Library + var library *libraries.Library for _, headerName := range []string{headerName, strings.ToLower(headerName)} { - library = findLibWithName(headerName, libraries) + library = findLibWithName(headerName, libs) if library != nil { return library } - library = findLibWithName(headerName+"-master", libraries) + library = findLibWithName(headerName+"-master", libs) if library != nil { return library } - library = findLibWithNameStartingWith(headerName, libraries) + library = findLibWithNameStartingWith(headerName, libs) if library != nil { return library } - library = findLibWithNameEndingWith(headerName, libraries) + library = findLibWithNameEndingWith(headerName, libs) if library != nil { return library } - library = findLibWithNameContaining(headerName, libraries) + library = findLibWithNameContaining(headerName, libs) if library != nil { return library } @@ -194,7 +195,7 @@ func findBestLibraryWithHeader(header string, libraries []*types.Library) *types return nil } -func findLibWithName(name string, libraries []*types.Library) *types.Library { +func findLibWithName(name string, libraries []*libraries.Library) *libraries.Library { for _, library := range libraries { if simplifyName(library.Name) == simplifyName(name) { return library @@ -203,7 +204,7 @@ func findLibWithName(name string, libraries []*types.Library) *types.Library { return nil } -func findLibWithNameStartingWith(name string, libraries []*types.Library) *types.Library { +func findLibWithNameStartingWith(name string, libraries []*libraries.Library) *libraries.Library { for _, library := range libraries { if strings.HasPrefix(simplifyName(library.Name), simplifyName(name)) { return library @@ -212,7 +213,7 @@ func findLibWithNameStartingWith(name string, libraries []*types.Library) *types return nil } -func findLibWithNameEndingWith(name string, libraries []*types.Library) *types.Library { +func findLibWithNameEndingWith(name string, libraries []*libraries.Library) *libraries.Library { for _, library := range libraries { if strings.HasSuffix(simplifyName(library.Name), simplifyName(name)) { return library @@ -221,7 +222,7 @@ func findLibWithNameEndingWith(name string, libraries []*types.Library) *types.L return nil } -func findLibWithNameContaining(name string, libraries []*types.Library) *types.Library { +func findLibWithNameContaining(name string, libraries []*libraries.Library) *libraries.Library { for _, library := range libraries { if strings.Contains(simplifyName(library.Name), simplifyName(name)) { return library diff --git a/resolve_library_test.go b/resolve_library_test.go index 5d421216..0566073d 100644 --- a/resolve_library_test.go +++ b/resolve_library_test.go @@ -32,40 +32,40 @@ package builder import ( "testing" - "github.com/arduino/arduino-builder/types" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/stretchr/testify/require" ) func TestFindBestLibraryWithHeader(t *testing.T) { - l1 := &types.Library{Name: "Calculus Lib"} - l2 := &types.Library{Name: "Calculus Lib-master"} - l3 := &types.Library{Name: "Calculus Lib Improved"} - l4 := &types.Library{Name: "Another Calculus Lib"} - l5 := &types.Library{Name: "Yet Another Calculus Lib Improved"} - l6 := &types.Library{Name: "AnotherLib"} + l1 := &libraries.Library{Name: "Calculus Lib"} + l2 := &libraries.Library{Name: "Calculus Lib-master"} + l3 := &libraries.Library{Name: "Calculus Lib Improved"} + l4 := &libraries.Library{Name: "Another Calculus Lib"} + l5 := &libraries.Library{Name: "Yet Another Calculus Lib Improved"} + l6 := &libraries.Library{Name: "AnotherLib"} // Test exact name matching - res := findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l5, l4, l3, l2, l1}) + res := findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3, l2, l1}) require.Equal(t, l1.Name, res.Name) // Test exact name with "-master" postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l5, l4, l3, l2}) + res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3, l2}) require.Equal(t, l2.Name, res.Name) // Test prefix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l5, l4, l3}) + res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3}) require.Equal(t, l3.Name, res.Name) // Test postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l5, l4}) + res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4}) require.Equal(t, l4.Name, res.Name) // Test "contains"" matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6, l5}) + res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5}) require.Equal(t, l5.Name, res.Name) // Test none matching - res = findBestLibraryWithHeader("calculus_lib.h", []*types.Library{l6}) + res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6}) require.Nil(t, res) } diff --git a/test/helper.go b/test/helper.go index b3452c7e..72e21589 100644 --- a/test/helper.go +++ b/test/helper.go @@ -41,6 +41,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/go-errors/errors" "github.com/stretchr/testify/assert" ) @@ -92,7 +93,7 @@ func SetupBuildCachePath(t *testing.T, ctx *types.Context) string { return buildCachePath } -type ByLibraryName []*types.Library +type ByLibraryName []*libraries.Library func (s ByLibraryName) Len() int { return len(s) diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 1908d4de..e153caa7 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -68,68 +68,68 @@ func TestLoadLibrariesAVR(t *testing.T) { require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) - libraries := ctx.Libraries - require.Equal(t, 24, len(libraries)) + libs := ctx.Libraries + require.Equal(t, 24, len(libs)) - sort.Sort(ByLibraryName(libraries)) + sort.Sort(ByLibraryName(libs)) idx := 0 - require.Equal(t, "ANewLibrary-master", libraries[idx].Name) + require.Equal(t, "ANewLibrary-master", libs[idx].Name) idx++ - require.Equal(t, "Adafruit_PN532", libraries[idx].Name) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libraries[idx].Folder) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libraries[idx].SrcFolder) - require.Equal(t, 1, len(libraries[idx].Archs)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, libraries[idx].Archs[0]) - require.False(t, libraries[idx].IsLegacy) + require.Equal(t, "Adafruit_PN532", libs[idx].Name) + require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].Folder) + require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].SrcFolder) + require.Equal(t, 1, len(libs[idx].Architectures)) + require.Equal(t, constants.LIBRARY_ALL_ARCHS, libs[idx].Architectures[0]) + require.False(t, libs[idx].IsLegacy) idx++ - require.Equal(t, "Audio", libraries[idx].Name) + require.Equal(t, "Audio", libs[idx].Name) idx++ - require.Equal(t, "Balanduino", libraries[idx].Name) - require.True(t, libraries[idx].IsLegacy) + require.Equal(t, "Balanduino", libs[idx].Name) + require.True(t, libs[idx].IsLegacy) idx++ - bridgeLib := libraries[idx] + bridgeLib := libs[idx] require.Equal(t, "Bridge", bridgeLib.Name) require.Equal(t, Abs(t, "downloaded_libraries/Bridge"), bridgeLib.Folder) require.Equal(t, Abs(t, "downloaded_libraries/Bridge/src"), bridgeLib.SrcFolder) - require.Equal(t, 1, len(bridgeLib.Archs)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Archs[0]) + require.Equal(t, 1, len(bridgeLib.Architectures)) + require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Architectures[0]) require.Equal(t, "Arduino", bridgeLib.Author) require.Equal(t, "Arduino ", bridgeLib.Maintainer) idx++ - require.Equal(t, "CapacitiveSensor", libraries[idx].Name) + require.Equal(t, "CapacitiveSensor", libs[idx].Name) idx++ - require.Equal(t, "EEPROM", libraries[idx].Name) + require.Equal(t, "EEPROM", libs[idx].Name) idx++ - require.Equal(t, "Ethernet", libraries[idx].Name) + require.Equal(t, "Ethernet", libs[idx].Name) idx++ - require.Equal(t, "FakeAudio", libraries[idx].Name) + require.Equal(t, "FakeAudio", libs[idx].Name) idx++ - require.Equal(t, "FastLED", libraries[idx].Name) + require.Equal(t, "FastLED", libs[idx].Name) idx++ - require.Equal(t, "HID", libraries[idx].Name) + require.Equal(t, "HID", libs[idx].Name) idx++ - require.Equal(t, "IRremote", libraries[idx].Name) + require.Equal(t, "IRremote", libs[idx].Name) idx++ - require.Equal(t, "Robot_IR_Remote", libraries[idx].Name) + require.Equal(t, "Robot_IR_Remote", libs[idx].Name) idx++ - require.Equal(t, "SPI", libraries[idx].Name) + require.Equal(t, "SPI", libs[idx].Name) idx++ - require.Equal(t, "SPI", libraries[idx].Name) + require.Equal(t, "SPI", libs[idx].Name) idx++ - require.Equal(t, "ShouldNotRecurseWithOldLibs", libraries[idx].Name) + require.Equal(t, "ShouldNotRecurseWithOldLibs", libs[idx].Name) idx++ - require.Equal(t, "SoftwareSerial", libraries[idx].Name) + require.Equal(t, "SoftwareSerial", libs[idx].Name) idx++ - require.Equal(t, "USBHost", libraries[idx].Name) + require.Equal(t, "USBHost", libs[idx].Name) idx++ - require.Equal(t, "Wire", libraries[idx].Name) + require.Equal(t, "Wire", libs[idx].Name) headerToLibraries := ctx.HeaderToLibraries require.Equal(t, 2, len(headerToLibraries["Audio.h"])) @@ -142,11 +142,11 @@ func TestLoadLibrariesAVR(t *testing.T) { require.Equal(t, 2, len(headerToLibraries["IRremote.h"])) - libraries = headerToLibraries["IRremote.h"] - sort.Sort(ByLibraryName(libraries)) + libs = headerToLibraries["IRremote.h"] + sort.Sort(ByLibraryName(libs)) - require.Equal(t, "IRremote", libraries[0].Name) - require.Equal(t, "Robot_IR_Remote", libraries[1].Name) + require.Equal(t, "IRremote", libs[0].Name) + require.Equal(t, "Robot_IR_Remote", libs[1].Name) } func TestLoadLibrariesSAM(t *testing.T) { diff --git a/test/sketch_source_merger_test.go b/test/sketch_source_merger_test.go index 8708db7b..5edfc35d 100644 --- a/test/sketch_source_merger_test.go +++ b/test/sketch_source_merger_test.go @@ -31,12 +31,13 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" "path/filepath" "strings" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + "github.com/stretchr/testify/require" ) func TestMergeSketch(t *testing.T) { diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go index 83847dee..2a797e45 100644 --- a/test/unused_compiled_libraries_remover_test.go +++ b/test/unused_compiled_libraries_remover_test.go @@ -30,13 +30,15 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" "io/ioutil" "os" "path/filepath" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/stretchr/testify/require" ) func TestUnusedCompiledLibrariesRemover(t *testing.T) { @@ -50,7 +52,7 @@ func TestUnusedCompiledLibrariesRemover(t *testing.T) { ctx := &types.Context{} ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*types.Library{&types.Library{Name: "Bridge"}} + ctx.ImportedLibraries = []*libraries.Library{&libraries.Library{Name: "Bridge"}} cmd := builder.UnusedCompiledLibrariesRemover{} err = cmd.Run(ctx) @@ -68,7 +70,7 @@ func TestUnusedCompiledLibrariesRemover(t *testing.T) { func TestUnusedCompiledLibrariesRemoverLibDoesNotExist(t *testing.T) { ctx := &types.Context{} ctx.LibrariesBuildPath = filepath.Join(os.TempDir(), "test") - ctx.ImportedLibraries = []*types.Library{&types.Library{Name: "Bridge"}} + ctx.ImportedLibraries = []*libraries.Library{&libraries.Library{Name: "Bridge"}} cmd := builder.UnusedCompiledLibrariesRemover{} err := cmd.Run(ctx) @@ -86,7 +88,7 @@ func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { ctx := &types.Context{} ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*types.Library{} + ctx.ImportedLibraries = []*libraries.Library{} cmd := builder.UnusedCompiledLibrariesRemover{} err = cmd.Run(ctx) diff --git a/types/context.go b/types/context.go index 599decae..6046c400 100644 --- a/types/context.go +++ b/types/context.go @@ -7,6 +7,7 @@ import ( "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) // Context structure @@ -62,9 +63,9 @@ type Context struct { WarningsLevel string // Libraries handling - Libraries []*Library - HeaderToLibraries map[string][]*Library - ImportedLibraries []*Library + Libraries []*libraries.Library + HeaderToLibraries map[string][]*libraries.Library + ImportedLibraries []*libraries.Library LibrariesResolutionResults map[string]LibraryResolutionResult IncludeJustFound string IncludeFolders []string diff --git a/types/types.go b/types/types.go index d36586be..4403e434 100644 --- a/types/types.go +++ b/types/types.go @@ -34,7 +34,7 @@ import ( "path/filepath" "strconv" - "github.com/arduino/arduino-builder/constants" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type SourceFile struct { @@ -65,7 +65,7 @@ func buildRoot(ctx *Context, origin interface{}) string { switch o := origin.(type) { case *Sketch: return ctx.SketchBuildPath - case *Library: + case *libraries.Library: return filepath.Join(ctx.LibrariesBuildPath, o.Name) default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) @@ -79,7 +79,7 @@ func sourceRoot(ctx *Context, origin interface{}) string { switch o := origin.(type) { case *Sketch: return ctx.SketchBuildPath - case *Library: + case *libraries.Library: return o.SrcFolder default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) @@ -123,54 +123,6 @@ type Sketch struct { AdditionalFiles []SketchFile } -type LibraryLayout uint16 - -const ( - LIBRARY_FLAT LibraryLayout = 1 << iota - LIBRARY_RECURSIVE -) - -type Library struct { - Folder string - SrcFolder string - UtilityFolder string - Layout LibraryLayout - Name string - RealName string - Archs []string - DotALinkage bool - Precompiled bool - LDflags string - IsLegacy bool - Version string - Author string - Maintainer string - Sentence string - Paragraph string - URL string - Category string - License string - Properties map[string]string -} - -func (library *Library) String() string { - return library.Name + " : " + library.SrcFolder -} - -func (library *Library) SupportsArchitectures(archs []string) bool { - if sliceContains(archs, constants.LIBRARY_ALL_ARCHS) || sliceContains(library.Archs, constants.LIBRARY_ALL_ARCHS) { - return true - } - - for _, libraryArch := range library.Archs { - if sliceContains(archs, libraryArch) { - return true - } - } - - return false -} - type PlatforKeysRewrite struct { Rewrites []PlatforKeyRewrite } @@ -203,8 +155,8 @@ type SourceFolder struct { } type LibraryResolutionResult struct { - Library *Library - NotUsedLibraries []*Library + Library *libraries.Library + NotUsedLibraries []*libraries.Library } type CTag struct { @@ -224,9 +176,9 @@ type CTag struct { PrototypeModifiers string } -func LibraryToSourceFolder(library *Library) []SourceFolder { +func LibraryToSourceFolder(library *libraries.Library) []SourceFolder { sourceFolders := []SourceFolder{} - recurse := library.Layout == LIBRARY_RECURSIVE + recurse := library.Layout == libraries.LIBRARY_RECURSIVE sourceFolders = append(sourceFolders, SourceFolder{Folder: library.SrcFolder, Recurse: recurse}) if library.UtilityFolder != "" { sourceFolders = append(sourceFolders, SourceFolder{Folder: library.UtilityFolder, Recurse: false}) diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go index f163efbb..299dc207 100644 --- a/unused_compiled_libraries_remover.go +++ b/unused_compiled_libraries_remover.go @@ -30,12 +30,14 @@ package builder import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "io/ioutil" "os" "path/filepath" + + "github.com/arduino/arduino-builder/i18n" + "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-builder/utils" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type UnusedCompiledLibrariesRemover struct{} @@ -68,7 +70,7 @@ func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { return nil } -func toLibraryNames(libraries []*types.Library) []string { +func toLibraryNames(libraries []*libraries.Library) []string { libraryNames := []string{} for _, library := range libraries { libraryNames = append(libraryNames, library.Name) diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go index c599fe28..482d8468 100644 --- a/warn_about_arch_incompatible_libraries.go +++ b/warn_about_arch_incompatible_libraries.go @@ -60,7 +60,7 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { for _, importedLibrary := range ctx.ImportedLibraries { if !importedLibrary.SupportsArchitectures(archs) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, importedLibrary.Name, sliceToCommaSeparatedString(importedLibrary.Archs), sliceToCommaSeparatedString(archs)) + logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, importedLibrary.Name, sliceToCommaSeparatedString(importedLibrary.Architectures), sliceToCommaSeparatedString(archs)) } } From 0124195318f9ffbb1e30a97368428a73c814eb2f Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 15 May 2018 14:03:57 +0200 Subject: [PATCH 15/57] Removed dependency from costants in LibrariesLoader --- add_additional_entries_to_context.go | 2 +- builder.go | 4 +- constants/constants.go | 17 ----- fail_if_imported_library_is_wrong.go | 2 +- libraries_loader.go | 71 ++++++++++--------- phases/libraries_builder.go | 2 +- .../add_additional_entries_to_context_test.go | 2 +- test/builder_test.go | 16 ++--- 8 files changed, 51 insertions(+), 65 deletions(-) diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index 256a33f7..cc55138a 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -51,7 +51,7 @@ func (*AddAdditionalEntriesToContext) Run(ctx *types.Context) error { if err != nil { return i18n.WrapError(err) } - librariesBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_LIBRARIES)) + librariesBuildPath, err := filepath.Abs(filepath.Join(buildPath, "libraries")) if err != nil { return i18n.WrapError(err) } diff --git a/builder.go b/builder.go index 745566d1..72adeca0 100644 --- a/builder.go +++ b/builder.go @@ -46,8 +46,8 @@ var MAIN_FILE_VALID_EXTENSIONS = map[string]bool{".ino": true, ".pde": true} var ADDITIONAL_FILE_VALID_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true} var ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS = map[string]bool{".c": true, ".cpp": true, ".s": true} -var LIBRARY_MANDATORY_PROPERTIES = []string{constants.LIBRARY_NAME, constants.LIBRARY_VERSION, constants.LIBRARY_AUTHOR, constants.LIBRARY_MAINTAINER} -var LIBRARY_NOT_SO_MANDATORY_PROPERTIES = []string{constants.LIBRARY_SENTENCE, constants.LIBRARY_PARAGRAPH, constants.LIBRARY_URL} +var LIBRARY_MANDATORY_PROPERTIES = []string{"name", "version", "author", constants.LIBRARY_MAINTAINER} +var LIBRARY_NOT_SO_MANDATORY_PROPERTIES = []string{"sentence", "paragraph", "url"} var LIBRARY_CATEGORIES = map[string]bool{ "Display": true, "Communication": true, diff --git a/constants/constants.go b/constants/constants.go index de9ecb28..a661da0d 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -62,7 +62,6 @@ const FILE_PLATFORM_KEYS_REWRITE_TXT = "platform.keys.rewrite.txt" const FILE_INCLUDES_CACHE = "includes.cache" const FOLDER_BOOTLOADERS = "bootloaders" const FOLDER_CORE = "core" -const FOLDER_LIBRARIES = "libraries" const FOLDER_PREPROC = "preproc" const FOLDER_SKETCH = "sketch" const FOLDER_TOOLS = "tools" @@ -91,27 +90,11 @@ const hooks = "recipe.hooks" const hooks_sketch = hooks + ".sketch" const HOOKS_SKETCH_POSTBUILD = hooks_sketch + hooks_postbuild_suffix const HOOKS_SKETCH_PREBUILD = hooks_sketch + hooks_prebuild_suffix -const LIB_CATEGORY_UNCATEGORIZED = "Uncategorized" -const LIB_LICENSE_UNSPECIFIED = "Unspecified" const LIBRARY_ALL_ARCHS = "*" -const LIBRARY_ARCHITECTURES = "architectures" -const LIBRARY_AUTHOR = "author" -const LIBRARY_CATEGORY = "category" -const LIBRARY_DOT_A_LINKAGE = "dot_a_linkage" const LIBRARY_EMAIL = "email" const LIBRARY_FOLDER_ARCH = "arch" const LIBRARY_FOLDER_SRC = "src" -const LIBRARY_FOLDER_UTILITY = "utility" -const LIBRARY_LICENSE = "license" const LIBRARY_MAINTAINER = "maintainer" -const LIBRARY_NAME = "name" -const LIBRARY_PARAGRAPH = "paragraph" -const LIBRARY_PRECOMPILED = "precompiled" -const LIBRARY_LDFLAGS = "ldflags" -const LIBRARY_PROPERTIES = "library.properties" -const LIBRARY_SENTENCE = "sentence" -const LIBRARY_URL = "url" -const LIBRARY_VERSION = "version" const LOG_LEVEL_DEBUG = "debug" const LOG_LEVEL_ERROR = "error" const LOG_LEVEL_INFO = "info" diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 13ba1394..73d37c9f 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -59,7 +59,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { } } if library.Layout == libraries.LIBRARY_RECURSIVE { - if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY)); err == nil && stat.IsDir() { + if stat, err := os.Stat(filepath.Join(library.Folder, "utility")); err == nil && stat.IsDir() { return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) } } diff --git a/libraries_loader.go b/libraries_loader.go index 7cc3fa83..b8383ee4 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -34,7 +34,6 @@ import ( "path/filepath" "strings" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" @@ -59,10 +58,10 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { actualPlatform := ctx.ActualPlatform if actualPlatform != platform { - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(actualPlatform.Folder, constants.FOLDER_LIBRARIES)) + sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(actualPlatform.Folder, "libraries")) } - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(platform.Folder, constants.FOLDER_LIBRARIES)) + sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(platform.Folder, "libraries")) librariesFolders := ctx.OtherLibrariesFolders librariesFolders, err = utils.AbsolutizePaths(librariesFolders) @@ -108,14 +107,14 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } func makeLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { - if _, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)); os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(libraryFolder, "library.properties")); os.IsNotExist(err) { return makeLegacyLibrary(libraryFolder) } return makeNewLibrary(libraryFolder, debugLevel, logger) } func addUtilityFolder(library *libraries.Library) { - utilitySourcePath := filepath.Join(library.Folder, constants.LIBRARY_FOLDER_UTILITY) + utilitySourcePath := filepath.Join(library.Folder, "utility") stat, err := os.Stat(utilitySourcePath) if err == nil && stat.IsDir() { library.UtilityFolder = utilitySourcePath @@ -123,26 +122,26 @@ func addUtilityFolder(library *libraries.Library) { } func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { - libProperties, err := properties.Load(filepath.Join(libraryFolder, constants.LIBRARY_PROPERTIES)) + libProperties, err := properties.Load(filepath.Join(libraryFolder, "library.properties")) if err != nil { return nil, i18n.WrapError(err) } - if libProperties[constants.LIBRARY_MAINTAINER] == constants.EMPTY_STRING && libProperties[constants.LIBRARY_EMAIL] != constants.EMPTY_STRING { - libProperties[constants.LIBRARY_MAINTAINER] = libProperties[constants.LIBRARY_EMAIL] + if libProperties["maintainer"] == "" && libProperties["email"] != "" { + libProperties["maintainer"] = libProperties["email"] } for _, propName := range LIBRARY_NOT_SO_MANDATORY_PROPERTIES { - if libProperties[propName] == constants.EMPTY_STRING { + if libProperties[propName] == "" { libProperties[propName] = "-" } } library := &libraries.Library{} library.Folder = libraryFolder - if stat, err := os.Stat(filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC)); err == nil && stat.IsDir() { + if stat, err := os.Stat(filepath.Join(libraryFolder, "src")); err == nil && stat.IsDir() { library.Layout = libraries.LIBRARY_RECURSIVE - library.SrcFolder = filepath.Join(libraryFolder, constants.LIBRARY_FOLDER_SRC) + library.SrcFolder = filepath.Join(libraryFolder, "src") } else { library.Layout = libraries.LIBRARY_FLAT library.SrcFolder = libraryFolder @@ -158,44 +157,48 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* for _, subFolder := range subFolders { if utils.IsSCCSOrHiddenFile(subFolder) { if !utils.IsSCCSFile(subFolder) && utils.IsHiddenFile(subFolder) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_WARNING_SPURIOUS_FILE_IN_LIB, filepath.Base(subFolder.Name()), libProperties[constants.LIBRARY_NAME]) + logger.Fprintln(os.Stdout, "warn", + "WARNING: Spurious {0} folder in '{1}' library", + filepath.Base(subFolder.Name()), libProperties["name"]) } } } } - if libProperties[constants.LIBRARY_ARCHITECTURES] == constants.EMPTY_STRING { - libProperties[constants.LIBRARY_ARCHITECTURES] = constants.LIBRARY_ALL_ARCHS + if libProperties["architectures"] == "" { + libProperties["architectures"] = "*" } library.Architectures = []string{} - for _, arch := range strings.Split(libProperties[constants.LIBRARY_ARCHITECTURES], ",") { + for _, arch := range strings.Split(libProperties["architectures"], ",") { library.Architectures = append(library.Architectures, strings.TrimSpace(arch)) } - libProperties[constants.LIBRARY_CATEGORY] = strings.TrimSpace(libProperties[constants.LIBRARY_CATEGORY]) - if !LIBRARY_CATEGORIES[libProperties[constants.LIBRARY_CATEGORY]] { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_WARNING_LIB_INVALID_CATEGORY, libProperties[constants.LIBRARY_CATEGORY], libProperties[constants.LIBRARY_NAME], constants.LIB_CATEGORY_UNCATEGORIZED) - libProperties[constants.LIBRARY_CATEGORY] = constants.LIB_CATEGORY_UNCATEGORIZED + libProperties["category"] = strings.TrimSpace(libProperties["category"]) + if !LIBRARY_CATEGORIES[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" } - library.Category = libProperties[constants.LIBRARY_CATEGORY] + library.Category = libProperties["category"] - if libProperties[constants.LIBRARY_LICENSE] == constants.EMPTY_STRING { - libProperties[constants.LIBRARY_LICENSE] = constants.LIB_LICENSE_UNSPECIFIED + if libProperties["license"] == "" { + libProperties["license"] = "Unspecified" } - library.License = libProperties[constants.LIBRARY_LICENSE] + library.License = libProperties["license"] library.Name = filepath.Base(libraryFolder) - library.RealName = strings.TrimSpace(libProperties[constants.LIBRARY_NAME]) - library.Version = strings.TrimSpace(libProperties[constants.LIBRARY_VERSION]) - library.Author = strings.TrimSpace(libProperties[constants.LIBRARY_AUTHOR]) - library.Maintainer = strings.TrimSpace(libProperties[constants.LIBRARY_MAINTAINER]) - library.Sentence = strings.TrimSpace(libProperties[constants.LIBRARY_SENTENCE]) - library.Paragraph = strings.TrimSpace(libProperties[constants.LIBRARY_PARAGRAPH]) - library.Website = strings.TrimSpace(libProperties[constants.LIBRARY_URL]) + library.RealName = strings.TrimSpace(libProperties["name"]) + library.Version = strings.TrimSpace(libProperties["version"]) + library.Author = strings.TrimSpace(libProperties["author"]) + library.Maintainer = strings.TrimSpace(libProperties["maintainer"]) + library.Sentence = strings.TrimSpace(libProperties["sentence"]) + library.Paragraph = strings.TrimSpace(libProperties["paragraph"]) + library.Website = strings.TrimSpace(libProperties["url"]) library.IsLegacy = false - library.DotALinkage = strings.TrimSpace(libProperties[constants.LIBRARY_DOT_A_LINKAGE]) == "true" - library.Precompiled = strings.TrimSpace(libProperties[constants.LIBRARY_PRECOMPILED]) == "true" - library.LDflags = strings.TrimSpace(libProperties[constants.LIBRARY_LDFLAGS]) + library.DotALinkage = strings.TrimSpace(libProperties["dot_a_linkage"]) == "true" + library.Precompiled = strings.TrimSpace(libProperties["precompiled"]) == "true" + library.LDflags = strings.TrimSpace(libProperties["ldflags"]) library.Properties = libProperties return library, nil @@ -207,7 +210,7 @@ func makeLegacyLibrary(libraryFolder string) (*libraries.Library, error) { SrcFolder: libraryFolder, Layout: libraries.LIBRARY_FLAT, Name: filepath.Base(libraryFolder), - Architectures: []string{constants.LIBRARY_ALL_ARCHS}, + Architectures: []string{"*"}, IsLegacy: true, } addUtilityFolder(library) diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 28cc5834..8af981d9 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -166,7 +166,7 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie } if library.UtilityFolder != "" { - utilityBuildPath := filepath.Join(libraryBuildPath, constants.LIBRARY_FOLDER_UTILITY) + utilityBuildPath := filepath.Join(libraryBuildPath, "utility") objectFiles, err = builder_utils.CompileFiles(objectFiles, library.UtilityFolder, false, utilityBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) diff --git a/test/add_additional_entries_to_context_test.go b/test/add_additional_entries_to_context_test.go index b85187ed..ca7bb0e1 100644 --- a/test/add_additional_entries_to_context_test.go +++ b/test/add_additional_entries_to_context_test.go @@ -66,7 +66,7 @@ func TestAddAdditionalEntriesToContextWithBuildPath(t *testing.T) { require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_PREPROC)), ctx.PreprocPath) require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_SKETCH)), ctx.SketchBuildPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_LIBRARIES)), ctx.LibrariesBuildPath) + require.Equal(t, Abs(t, filepath.Join("folder", "libraries")), ctx.LibrariesBuildPath) require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_CORE)), ctx.CoreBuildPath) require.NotNil(t, ctx.WarningsLevel) diff --git a/test/builder_test.go b/test/builder_test.go index 2e913cd7..3b36c104 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -105,7 +105,7 @@ func TestBuilderBridge(t *testing.T) { NoError(t, err) _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) NoError(t, err) } @@ -132,7 +132,7 @@ func TestBuilderSketchWithConfig(t *testing.T) { NoError(t, err) _, err = os.Stat(filepath.Join(buildPath, "sketch_with_config.ino.hex")) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) NoError(t, err) } @@ -164,7 +164,7 @@ func TestBuilderBridgeTwice(t *testing.T) { NoError(t, err) _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) NoError(t, err) } @@ -196,7 +196,7 @@ func TestBuilderBridgeSAM(t *testing.T) { NoError(t, err) _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.bin")) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) NoError(t, err) cmd := exec.Command(filepath.Join("downloaded_tools", "arm-none-eabi-gcc", "4.8.3-2014q1", "bin", "arm-none-eabi-objdump"), "-f", filepath.Join(buildPath, constants.FOLDER_CORE, "core.a")) @@ -230,7 +230,7 @@ func TestBuilderBridgeRedBearLab(t *testing.T) { NoError(t, err) _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge", "Mailbox.cpp.o")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) NoError(t, err) } @@ -302,17 +302,17 @@ func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testin buildPath := SetupBuildPath(t, ctx) defer os.RemoveAll(buildPath) - NoError(t, os.MkdirAll(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "SPI"), os.FileMode(0755))) + NoError(t, os.MkdirAll(filepath.Join(buildPath, "libraries", "SPI"), os.FileMode(0755))) // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "SPI")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "SPI")) require.Error(t, err) require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_LIBRARIES, "Bridge")) + _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge")) NoError(t, err) } From cc5b5b5fd0051d54e2bb34994ba116c5f098bcf8 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 15 May 2018 16:49:17 +0200 Subject: [PATCH 16/57] renamed some properties --- builder.go | 15 --------------- constants/constants.go | 1 - fail_if_imported_library_is_wrong.go | 4 ++-- libraries_loader.go | 10 +++++----- phases/libraries_builder.go | 2 +- types/types.go | 2 +- 6 files changed, 9 insertions(+), 25 deletions(-) diff --git a/builder.go b/builder.go index 72adeca0..6439b1f8 100644 --- a/builder.go +++ b/builder.go @@ -46,21 +46,6 @@ var MAIN_FILE_VALID_EXTENSIONS = map[string]bool{".ino": true, ".pde": true} var ADDITIONAL_FILE_VALID_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true} var ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS = map[string]bool{".c": true, ".cpp": true, ".s": true} -var LIBRARY_MANDATORY_PROPERTIES = []string{"name", "version", "author", constants.LIBRARY_MAINTAINER} -var LIBRARY_NOT_SO_MANDATORY_PROPERTIES = []string{"sentence", "paragraph", "url"} -var LIBRARY_CATEGORIES = map[string]bool{ - "Display": true, - "Communication": true, - "Signal Input/Output": true, - "Sensors": true, - "Device Control": true, - "Timing": true, - "Data Storage": true, - "Data Processing": true, - "Other": true, - "Uncategorized": true, -} - const DEFAULT_DEBUG_LEVEL = 5 const DEFAULT_WARNINGS_LEVEL = "none" const DEFAULT_SOFTWARE = "ARDUINO" diff --git a/constants/constants.go b/constants/constants.go index a661da0d..ca17d701 100644 --- a/constants/constants.go +++ b/constants/constants.go @@ -94,7 +94,6 @@ const LIBRARY_ALL_ARCHS = "*" const LIBRARY_EMAIL = "email" const LIBRARY_FOLDER_ARCH = "arch" const LIBRARY_FOLDER_SRC = "src" -const LIBRARY_MAINTAINER = "maintainer" const LOG_LEVEL_DEBUG = "debug" const LOG_LEVEL_ERROR = "error" const LOG_LEVEL_INFO = "info" diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 73d37c9f..472fa565 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -53,12 +53,12 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_ARCH)); err == nil && stat.IsDir() { return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) } - for _, propName := range LIBRARY_MANDATORY_PROPERTIES { + for _, propName := range libraries.MandatoryProperties { if _, ok := library.Properties[propName]; !ok { return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.Folder) } } - if library.Layout == libraries.LIBRARY_RECURSIVE { + if library.Layout == libraries.RecursiveLayout { if stat, err := os.Stat(filepath.Join(library.Folder, "utility")); err == nil && stat.IsDir() { return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) } diff --git a/libraries_loader.go b/libraries_loader.go index b8383ee4..c6a402de 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -131,7 +131,7 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* libProperties["maintainer"] = libProperties["email"] } - for _, propName := range LIBRARY_NOT_SO_MANDATORY_PROPERTIES { + for _, propName := range libraries.MandatoryProperties { if libProperties[propName] == "" { libProperties[propName] = "-" } @@ -140,10 +140,10 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* library := &libraries.Library{} library.Folder = libraryFolder if stat, err := os.Stat(filepath.Join(libraryFolder, "src")); err == nil && stat.IsDir() { - library.Layout = libraries.LIBRARY_RECURSIVE + library.Layout = libraries.RecursiveLayout library.SrcFolder = filepath.Join(libraryFolder, "src") } else { - library.Layout = libraries.LIBRARY_FLAT + library.Layout = libraries.FlatLayout library.SrcFolder = libraryFolder addUtilityFolder(library) } @@ -174,7 +174,7 @@ func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (* } libProperties["category"] = strings.TrimSpace(libProperties["category"]) - if !LIBRARY_CATEGORIES[libProperties["category"]] { + if !libraries.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") @@ -208,7 +208,7 @@ func makeLegacyLibrary(libraryFolder string) (*libraries.Library, error) { library := &libraries.Library{ Folder: libraryFolder, SrcFolder: libraryFolder, - Layout: libraries.LIBRARY_FLAT, + Layout: libraries.FlatLayout, Name: filepath.Base(libraryFolder), Architectures: []string{"*"}, IsLegacy: true, diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 8af981d9..3d12fcf1 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -144,7 +144,7 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie } } - if library.Layout == libraries.LIBRARY_RECURSIVE { + if library.Layout == libraries.RecursiveLayout { objectFiles, err = builder_utils.CompileFilesRecursive(objectFiles, library.SrcFolder, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) diff --git a/types/types.go b/types/types.go index 4403e434..83e38acc 100644 --- a/types/types.go +++ b/types/types.go @@ -178,7 +178,7 @@ type CTag struct { func LibraryToSourceFolder(library *libraries.Library) []SourceFolder { sourceFolders := []SourceFolder{} - recurse := library.Layout == libraries.LIBRARY_RECURSIVE + recurse := library.Layout == libraries.RecursiveLayout sourceFolders = append(sourceFolders, SourceFolder{Folder: library.SrcFolder, Recurse: recurse}) if library.UtilityFolder != "" { sourceFolders = append(sourceFolders, SourceFolder{Folder: library.UtilityFolder, Recurse: false}) From f0a93727cc5c65664548b7905457751083db5fcb Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 15 May 2018 21:05:29 +0200 Subject: [PATCH 17/57] moved library loader in arduino-cli --- libraries_loader.go | 124 ++++---------------------------------------- 1 file changed, 10 insertions(+), 114 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index c6a402de..d781844d 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -32,12 +32,10 @@ package builder import ( "os" "path/filepath" - "strings" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) @@ -79,7 +77,16 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { return i18n.WrapError(err) } for _, subFolder := range subFolders { - library, err := makeLibrary(filepath.Join(libraryFolder, subFolder.Name()), debugLevel, logger) + library, err := libraries.Load(filepath.Join(libraryFolder, subFolder.Name())) + if debugLevel > 0 { + if warnings, err := library.Lint(); err != nil { + return i18n.WrapError(err) + } else { + for _, warning := range warnings { + logger.Fprintln(os.Stdout, "warn", warning) + } + } + } if err != nil { return i18n.WrapError(err) } @@ -106,117 +113,6 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { return nil } -func makeLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { - if _, err := os.Stat(filepath.Join(libraryFolder, "library.properties")); os.IsNotExist(err) { - return makeLegacyLibrary(libraryFolder) - } - return makeNewLibrary(libraryFolder, debugLevel, logger) -} - -func addUtilityFolder(library *libraries.Library) { - utilitySourcePath := filepath.Join(library.Folder, "utility") - stat, err := os.Stat(utilitySourcePath) - if err == nil && stat.IsDir() { - library.UtilityFolder = utilitySourcePath - } -} - -func makeNewLibrary(libraryFolder string, debugLevel int, logger i18n.Logger) (*libraries.Library, error) { - libProperties, err := properties.Load(filepath.Join(libraryFolder, "library.properties")) - if err != nil { - return nil, i18n.WrapError(err) - } - - if libProperties["maintainer"] == "" && libProperties["email"] != "" { - libProperties["maintainer"] = libProperties["email"] - } - - for _, propName := range libraries.MandatoryProperties { - if libProperties[propName] == "" { - libProperties[propName] = "-" - } - } - - library := &libraries.Library{} - library.Folder = libraryFolder - if stat, err := os.Stat(filepath.Join(libraryFolder, "src")); err == nil && stat.IsDir() { - library.Layout = libraries.RecursiveLayout - library.SrcFolder = filepath.Join(libraryFolder, "src") - } else { - library.Layout = libraries.FlatLayout - library.SrcFolder = libraryFolder - addUtilityFolder(library) - } - - subFolders, err := utils.ReadDirFiltered(libraryFolder, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - if debugLevel >= 0 { - for _, subFolder := range subFolders { - if utils.IsSCCSOrHiddenFile(subFolder) { - if !utils.IsSCCSFile(subFolder) && utils.IsHiddenFile(subFolder) { - logger.Fprintln(os.Stdout, "warn", - "WARNING: Spurious {0} folder in '{1}' library", - filepath.Base(subFolder.Name()), libProperties["name"]) - } - } - } - } - - if libProperties["architectures"] == "" { - libProperties["architectures"] = "*" - } - library.Architectures = []string{} - for _, arch := range strings.Split(libProperties["architectures"], ",") { - library.Architectures = append(library.Architectures, strings.TrimSpace(arch)) - } - - libProperties["category"] = strings.TrimSpace(libProperties["category"]) - if !libraries.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" - } - library.Category = libProperties["category"] - - if libProperties["license"] == "" { - libProperties["license"] = "Unspecified" - } - library.License = libProperties["license"] - - library.Name = filepath.Base(libraryFolder) - library.RealName = strings.TrimSpace(libProperties["name"]) - library.Version = strings.TrimSpace(libProperties["version"]) - library.Author = strings.TrimSpace(libProperties["author"]) - library.Maintainer = strings.TrimSpace(libProperties["maintainer"]) - library.Sentence = strings.TrimSpace(libProperties["sentence"]) - library.Paragraph = strings.TrimSpace(libProperties["paragraph"]) - library.Website = strings.TrimSpace(libProperties["url"]) - library.IsLegacy = false - library.DotALinkage = strings.TrimSpace(libProperties["dot_a_linkage"]) == "true" - library.Precompiled = strings.TrimSpace(libProperties["precompiled"]) == "true" - library.LDflags = strings.TrimSpace(libProperties["ldflags"]) - library.Properties = libProperties - - return library, nil -} - -func makeLegacyLibrary(libraryFolder string) (*libraries.Library, error) { - library := &libraries.Library{ - Folder: libraryFolder, - SrcFolder: libraryFolder, - Layout: libraries.FlatLayout, - Name: filepath.Base(libraryFolder), - Architectures: []string{"*"}, - IsLegacy: true, - } - addUtilityFolder(library) - return library, nil -} - func appendPathToLibrariesFolders(librariesFolders []string, newLibrariesFolder string) []string { if stat, err := os.Stat(newLibrariesFolder); os.IsNotExist(err) || !stat.IsDir() { return librariesFolders From f37025c1ff561f205eb672c6cbd31b8474b1c0ff Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 16 May 2018 22:16:45 +0200 Subject: [PATCH 18/57] Using paths.* utilities --- hardware_loader.go | 3 ++- libraries_loader.go | 3 ++- tools_loader.go | 4 +++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index 4283af50..04988411 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -33,13 +33,14 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" + "github.com/bcmi-labs/arduino-cli/paths" ) type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { pm := packagemanager.NewPackageManager() - if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { + if err := pm.LoadHardwareFromDirectories(paths.NewPathList(ctx.HardwareFolders...)); err != nil { return i18n.WrapError(err) } ctx.PackageManager = pm diff --git a/libraries_loader.go b/libraries_loader.go index d781844d..74067ae9 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -37,6 +37,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/bcmi-labs/arduino-cli/paths" ) type LibrariesLoader struct{} @@ -77,7 +78,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { return i18n.WrapError(err) } for _, subFolder := range subFolders { - library, err := libraries.Load(filepath.Join(libraryFolder, subFolder.Name())) + library, err := libraries.Load(paths.New(libraryFolder).Join(subFolder.Name())) if debugLevel > 0 { if warnings, err := library.Lint(); err != nil { return i18n.WrapError(err) diff --git a/tools_loader.go b/tools_loader.go index 42cf3426..01284cb9 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -34,6 +34,8 @@ import ( "path/filepath" "strings" + "github.com/bcmi-labs/arduino-cli/paths" + "github.com/arduino/arduino-builder/types" ) @@ -65,7 +67,7 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { } pm := ctx.PackageManager - pm.LoadToolsFromBundleDirectories(builtinFolders) + pm.LoadToolsFromBundleDirectories(paths.NewPathList(builtinFolders...)) ctx.AllTools = pm.GetAllInstalledToolsReleases() From 067f1d04e5b627d0f4d053d0cd138be41767f8d2 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 18 May 2018 11:59:36 +0200 Subject: [PATCH 19/57] moved LibraryToSourceFolder function in arduino-cli --- container_find_includes.go | 10 +++++----- fail_if_imported_library_is_wrong.go | 7 ++----- libraries_loader.go | 2 +- phases/libraries_builder.go | 16 ++++++++-------- test/includes_to_include_folders_test.go | 6 +++--- test/libraries_loader_test.go | 8 ++++---- types/types.go | 17 +---------------- 7 files changed, 24 insertions(+), 42 deletions(-) diff --git a/container_find_includes.go b/container_find_includes.go index fd76eef5..f599731c 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -315,8 +315,8 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t cache.ExpectFile(sourcePath) includes := ctx.IncludeFolders - if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityFolder != "" { - includes = append(includes, library.UtilityFolder) + if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityFolder != nil { + includes = append(includes, library.UtilityFolder.String()) } if unchanged && cache.valid { include = cache.Next().Include @@ -354,10 +354,10 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t // include path and queue its source files for further // include scanning ctx.ImportedLibraries = append(ctx.ImportedLibraries, library) - appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder) - sourceFolders := types.LibraryToSourceFolder(library) + appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder.String()) + sourceFolders := library.SourceDirs() for _, sourceFolder := range sourceFolders { - queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder, sourceFolder.Recurse) + queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder.String(), sourceFolder.Recurse) } first = false } diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 472fa565..a0dec009 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -30,9 +30,6 @@ package builder import ( - "os" - "path/filepath" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" @@ -50,7 +47,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { for _, library := range ctx.ImportedLibraries { if !library.IsLegacy { - if stat, err := os.Stat(filepath.Join(library.Folder, constants.LIBRARY_FOLDER_ARCH)); err == nil && stat.IsDir() { + if isDir, _ := library.Folder.Join(constants.LIBRARY_FOLDER_ARCH).IsDir(); isDir { return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) } for _, propName := range libraries.MandatoryProperties { @@ -59,7 +56,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { } } if library.Layout == libraries.RecursiveLayout { - if stat, err := os.Stat(filepath.Join(library.Folder, "utility")); err == nil && stat.IsDir() { + if library.UtilityFolder != nil { return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) } } diff --git a/libraries_loader.go b/libraries_loader.go index 74067ae9..dc641d72 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -99,7 +99,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { headerToLibraries := make(map[string][]*libraries.Library) for _, library := range libs { - headers, err := utils.ReadDirFiltered(library.SrcFolder, utils.FilterFilesWithExtensions(".h", ".hpp", ".hh")) + headers, err := utils.ReadDirFiltered(library.SrcFolder.String(), utils.FilterFilesWithExtensions(".h", ".hpp", ".hh")) if err != nil { return i18n.WrapError(err) } diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 3d12fcf1..5cbce89b 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -82,7 +82,7 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*libraries // add library src path to compiler.c.elf.extra_flags // use library.Name as lib name and srcPath/{mcpu} as location mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - path := filepath.Join(library.SrcFolder, mcu) + path := library.SrcFolder.Join(mcu).String() // find all library names in the folder and prepend -l filePaths := []string{} libs_cmd := library.LDflags + " " @@ -133,7 +133,7 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie filePaths := []string{} mcu := buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - err := utils.FindFilesInFolder(&filePaths, filepath.Join(library.SrcFolder, mcu), extensions, true) + err := utils.FindFilesInFolder(&filePaths, library.SrcFolder.Join(mcu).String(), extensions, true) if err != nil { return nil, i18n.WrapError(err) } @@ -145,7 +145,7 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie } if library.Layout == libraries.RecursiveLayout { - objectFiles, err = builder_utils.CompileFilesRecursive(objectFiles, library.SrcFolder, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + objectFiles, err = builder_utils.CompileFilesRecursive(objectFiles, library.SrcFolder.String(), libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } @@ -157,17 +157,17 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie objectFiles = []string{archiveFile} } } else { - if library.UtilityFolder != "" { - includes = append(includes, utils.WrapWithHyphenI(library.UtilityFolder)) + if library.UtilityFolder != nil { + includes = append(includes, utils.WrapWithHyphenI(library.UtilityFolder.String())) } - objectFiles, err = builder_utils.CompileFiles(objectFiles, library.SrcFolder, false, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + objectFiles, err = builder_utils.CompileFiles(objectFiles, library.SrcFolder.String(), false, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } - if library.UtilityFolder != "" { + if library.UtilityFolder != nil { utilityBuildPath := filepath.Join(libraryBuildPath, "utility") - objectFiles, err = builder_utils.CompileFiles(objectFiles, library.UtilityFolder, false, utilityBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + objectFiles, err = builder_utils.CompileFiles(objectFiles, library.UtilityFolder.String(), false, utilityBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index fafa3ff2..1216244b 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -222,7 +222,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")), importedLibraries[0].SrcFolder) + require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")), importedLibraries[0].SrcFolder.String()) } func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatform(t *testing.T) { @@ -260,7 +260,7 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "SPI")), importedLibraries[0].SrcFolder) + require.Equal(t, Abs(t, filepath.Join("libraries", "SPI")), importedLibraries[0].SrcFolder.String()) } func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { @@ -298,7 +298,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "USBHost", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "USBHost", "src")), importedLibraries[0].SrcFolder) + require.Equal(t, Abs(t, filepath.Join("libraries", "USBHost", "src")), importedLibraries[0].SrcFolder.String()) } func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index e153caa7..8af56278 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -79,8 +79,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ require.Equal(t, "Adafruit_PN532", libs[idx].Name) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].Folder) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].SrcFolder) + require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].Folder.String()) + require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].SrcFolder.String()) require.Equal(t, 1, len(libs[idx].Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, libs[idx].Architectures[0]) require.False(t, libs[idx].IsLegacy) @@ -95,8 +95,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ bridgeLib := libs[idx] require.Equal(t, "Bridge", bridgeLib.Name) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge"), bridgeLib.Folder) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge/src"), bridgeLib.SrcFolder) + require.Equal(t, Abs(t, "downloaded_libraries/Bridge"), bridgeLib.Folder.String()) + require.Equal(t, Abs(t, "downloaded_libraries/Bridge/src"), bridgeLib.SrcFolder.String()) require.Equal(t, 1, len(bridgeLib.Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Architectures[0]) require.Equal(t, "Arduino", bridgeLib.Author) diff --git a/types/types.go b/types/types.go index 83e38acc..ff74206c 100644 --- a/types/types.go +++ b/types/types.go @@ -80,7 +80,7 @@ func sourceRoot(ctx *Context, origin interface{}) string { case *Sketch: return ctx.SketchBuildPath case *libraries.Library: - return o.SrcFolder + return o.SrcFolder.String() default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) } @@ -149,11 +149,6 @@ func (proto *Prototype) String() string { return proto.Modifiers + " " + proto.Prototype + " @ " + strconv.Itoa(proto.Line) } -type SourceFolder struct { - Folder string - Recurse bool -} - type LibraryResolutionResult struct { Library *libraries.Library NotUsedLibraries []*libraries.Library @@ -176,16 +171,6 @@ type CTag struct { PrototypeModifiers string } -func LibraryToSourceFolder(library *libraries.Library) []SourceFolder { - sourceFolders := []SourceFolder{} - recurse := library.Layout == libraries.RecursiveLayout - sourceFolders = append(sourceFolders, SourceFolder{Folder: library.SrcFolder, Recurse: recurse}) - if library.UtilityFolder != "" { - sourceFolders = append(sourceFolders, SourceFolder{Folder: library.UtilityFolder, Recurse: false}) - } - return sourceFolders -} - type Command interface { Run(ctx *Context) error } From f1631fda6498b754dcf347d0f4c4c45651a09206 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 25 May 2018 23:16:32 +0200 Subject: [PATCH 20/57] Using paths.* methods and structure (almost) everywhere There are still some helper function to remove from utils packages, but the increase in readability is already impressive. There are some minor tweaks and small refactors here and there, but no substantial changes the code should perform exactly as before. --- add_additional_entries_to_context.go | 16 +- additional_sketch_files_copier.go | 28 +- arduino-builder/main.go | 40 +-- builder_utils/utils.go | 177 +++++------- container_add_prototypes.go | 6 +- container_find_includes.go | 60 ++-- ctags/ctags_parser.go | 6 +- ctags/ctags_parser_test.go | 2 +- ctags/ctags_to_prototypes.go | 2 +- ctags/ctags_to_prototypes_test.go | 3 +- ctags_runner.go | 2 +- ctags_target_file_saver.go | 11 +- ensure_buildpath_exists.go | 5 +- fail_if_buildpath_equals_sketchpath.go | 11 +- filter_sketch_source.go | 20 +- gcc_preproc_runner.go | 32 +-- generate_buildpath_if_missing.go | 18 +- hardware_loader.go | 3 +- libraries_loader.go | 37 ++- load_previous_build_options.go | 13 +- merge_sketch_with_bootloader.go | 38 +-- phases/core_builder.go | 55 ++-- phases/libraries_builder.go | 39 +-- phases/linker.go | 22 +- phases/sketch_builder.go | 18 +- platform_keys_rewrite_loader.go | 22 +- read_file_and_store_in_context.go | 3 +- setup_build_properties.go | 14 +- sketch_loader.go | 41 ++- sketch_saver.go | 7 +- sketch_source_merger.go | 7 +- store_build_options_map.go | 4 +- .../add_additional_entries_to_context_test.go | 12 +- ...dd_build_board_property_if_missing_test.go | 6 +- test/additional_sketch_files_copier_test.go | 32 ++- test/builder_test.go | 217 ++++++++------ test/builder_utils_test.go | 68 ++--- test/create_build_options_map_test.go | 14 +- test/ctags_runner_test.go | 118 ++++---- ...ail_if_buildpath_equals_sketchpath_test.go | 12 +- test/generate_buildpath_if_missing_test.go | 24 +- test/hardware_loader_test.go | 9 +- test/helper.go | 18 +- test/helper_tools_downloader.go | 245 ++++++++-------- test/includes_to_include_folders_test.go | 102 +++---- test/libraries_loader_test.go | 59 ++-- test/load_previous_build_options_map_test.go | 12 +- test/load_vid_pid_specific_properties_test.go | 18 +- test/merge_sketch_with_bootloader_test.go | 83 +++--- test/platform_keys_rewrite_loader_test.go | 3 +- test/prototypes_adder_test.go | 268 +++++++++--------- test/read_file_and_store_in_context_test.go | 18 +- test/setup_build_properties_test.go | 99 +++---- test/sketch_loader_test.go | 41 +-- test/sketch_source_merger_test.go | 4 +- test/store_build_options_map_test.go | 24 +- test/target_board_resolver_test.go | 13 +- test/tools_loader_test.go | 69 +++-- test/try_build_of_problematic_sketch_test.go | 22 +- .../unused_compiled_libraries_remover_test.go | 53 ++-- ...uild_path_if_build_options_changed_test.go | 29 +- tools_loader.go | 15 +- types/context.go | 63 ++-- types/types.go | 34 +-- types/utils.go | 2 +- unused_compiled_libraries_remover.go | 16 +- utils/utils.go | 50 +--- ...out_build_path_if_build_options_changed.go | 31 +- 68 files changed, 1303 insertions(+), 1362 deletions(-) diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index cc55138a..ab26bcc9 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -30,8 +30,6 @@ package builder import ( - "path/filepath" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" @@ -41,21 +39,21 @@ import ( type AddAdditionalEntriesToContext struct{} func (*AddAdditionalEntriesToContext) Run(ctx *types.Context) error { - if ctx.BuildPath != "" { + if ctx.BuildPath != nil { buildPath := ctx.BuildPath - preprocPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_PREPROC)) + preprocPath, err := buildPath.Join(constants.FOLDER_PREPROC).Abs() if err != nil { return i18n.WrapError(err) } - sketchBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_SKETCH)) + sketchBuildPath, err := buildPath.Join(constants.FOLDER_SKETCH).Abs() if err != nil { return i18n.WrapError(err) } - librariesBuildPath, err := filepath.Abs(filepath.Join(buildPath, "libraries")) + librariesBuildPath, err := buildPath.Join("libraries").Abs() if err != nil { return i18n.WrapError(err) } - coreBuildPath, err := filepath.Abs(filepath.Join(buildPath, constants.FOLDER_CORE)) + coreBuildPath, err := buildPath.Join(constants.FOLDER_CORE).Abs() if err != nil { return i18n.WrapError(err) } @@ -66,8 +64,8 @@ func (*AddAdditionalEntriesToContext) Run(ctx *types.Context) error { ctx.CoreBuildPath = coreBuildPath } - if ctx.BuildCachePath != "" { - coreBuildCachePath, err := filepath.Abs(filepath.Join(ctx.BuildCachePath, constants.FOLDER_CORE)) + if ctx.BuildCachePath != nil { + coreBuildCachePath, err := ctx.BuildCachePath.Join(constants.FOLDER_CORE).Abs() if err != nil { return i18n.WrapError(err) } diff --git a/additional_sketch_files_copier.go b/additional_sketch_files_copier.go index c992e820..0d9043e1 100644 --- a/additional_sketch_files_copier.go +++ b/additional_sketch_files_copier.go @@ -30,12 +30,11 @@ package builder import ( + "bytes" + "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "bytes" - "io/ioutil" - "path/filepath" + "github.com/arduino/go-paths-helper" ) type AdditionalSketchFilesCopier struct{} @@ -44,33 +43,30 @@ func (s *AdditionalSketchFilesCopier) Run(ctx *types.Context) error { sketch := ctx.Sketch sketchBuildPath := ctx.SketchBuildPath - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { + if err := sketchBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - sketchBasePath := filepath.Dir(sketch.MainFile.Name) + sketchBasePath := sketch.MainFile.Name.Parent() for _, file := range sketch.AdditionalFiles { - relativePath, err := filepath.Rel(sketchBasePath, file.Name) + relativePath, err := sketchBasePath.RelTo(file.Name) if err != nil { return i18n.WrapError(err) } - targetFilePath := filepath.Join(sketchBuildPath, relativePath) - err = utils.EnsureFolderExists(filepath.Dir(targetFilePath)) - if err != nil { + targetFilePath := sketchBuildPath.JoinPath(relativePath) + if err = targetFilePath.Parent().MkdirAll(); err != nil { return i18n.WrapError(err) } - bytes, err := ioutil.ReadFile(file.Name) + bytes, err := file.Name.ReadFile() if err != nil { return i18n.WrapError(err) } if targetFileChanged(bytes, targetFilePath) { - err := utils.WriteFileBytes(targetFilePath, bytes) - if err != nil { + if err := targetFilePath.WriteFile(bytes); err != nil { return i18n.WrapError(err) } } @@ -79,8 +75,8 @@ func (s *AdditionalSketchFilesCopier) Run(ctx *types.Context) error { return nil } -func targetFileChanged(currentBytes []byte, targetFilePath string) bool { - oldBytes, err := ioutil.ReadFile(targetFilePath) +func targetFileChanged(currentBytes []byte, targetFilePath *paths.Path) bool { + oldBytes, err := targetFilePath.ReadFile() if err != nil { return true } diff --git a/arduino-builder/main.go b/arduino-builder/main.go index 174c6666..6e1374ca 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -40,11 +40,12 @@ import ( "strings" "syscall" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" "github.com/go-errors/errors" ) @@ -194,7 +195,7 @@ func main() { if hardwareFolders, err := toSliceOfUnquoted(hardwareFoldersFlag); err != nil { printCompleteError(err) } else if len(hardwareFolders) > 0 { - ctx.HardwareFolders = hardwareFolders + ctx.HardwareFolders = paths.NewPathList(hardwareFolders...) } if len(ctx.HardwareFolders) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_HARDWARE + "' is mandatory")) @@ -204,7 +205,7 @@ func main() { if toolsFolders, err := toSliceOfUnquoted(toolsFoldersFlag); err != nil { printCompleteError(err) } else if len(toolsFolders) > 0 { - ctx.ToolsFolders = toolsFolders + ctx.ToolsFolders = paths.NewPathList(toolsFolders...) } if len(ctx.ToolsFolders) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_TOOLS + "' is mandatory")) @@ -214,14 +215,14 @@ func main() { if librariesFolders, err := toSliceOfUnquoted(librariesFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesFolders) > 0 { - ctx.OtherLibrariesFolders = librariesFolders + ctx.OtherLibrariesFolders = paths.NewPathList(librariesFolders...) } // FLAG_BUILT_IN_LIBRARIES if librariesBuiltInFolders, err := toSliceOfUnquoted(librariesBuiltInFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesBuiltInFolders) > 0 { - ctx.BuiltInLibrariesFolders = librariesBuiltInFolders + ctx.BuiltInLibrariesFolders = paths.NewPathList(librariesBuiltInFolders...) } // FLAG_PREFS @@ -242,38 +243,38 @@ func main() { } // FLAG_BUILD_PATH - buildPath, err := gohasissues.Unquote(*buildPathFlag) + buildPathUnquoted, err := gohasissues.Unquote(*buildPathFlag) if err != nil { printCompleteError(err) } - if buildPath != "" { - _, err := os.Stat(buildPath) - if err != nil { + buildPath := paths.New(buildPathUnquoted) + if buildPath != nil { + // TODO: mmmmhhh... this one looks like a bug, why check existence? + if _, err := buildPath.Stat(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } - err = utils.EnsureFolderExists(buildPath) - if err != nil { + if err := buildPath.MkdirAll(); err != nil { printCompleteError(err) } } ctx.BuildPath = buildPath // FLAG_BUILD_CACHE - buildCachePath, err := gohasissues.Unquote(*buildCachePathFlag) + buildCachePathUnquoted, err := gohasissues.Unquote(*buildCachePathFlag) if err != nil { printCompleteError(err) } - if buildCachePath != "" { - _, err := os.Stat(buildCachePath) - if err != nil { + buildCachePath := paths.New(buildCachePathUnquoted) + if buildCachePath != nil { + // TODO: mmmmhhh... this one looks like a bug, why check existence? + if _, err := buildCachePath.Stat(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } - err = utils.EnsureFolderExists(buildCachePath) - if err != nil { + if err := buildCachePath.MkdirAll(); err != nil { printCompleteError(err) } } @@ -285,12 +286,11 @@ func main() { } if flag.NArg() > 0 { - sketchLocation := flag.Arg(0) - sketchLocation, err := gohasissues.Unquote(sketchLocation) + sketchLocationUnquoted, err := gohasissues.Unquote(flag.Arg(0)) if err != nil { printCompleteError(err) } - ctx.SketchLocation = sketchLocation + ctx.SketchLocation = paths.New(sketchLocationUnquoted) } if *verboseFlag && *quietFlag { diff --git a/builder_utils/utils.go b/builder_utils/utils.go index 5be3b483..eb72399f 100644 --- a/builder_utils/utils.go +++ b/builder_utils/utils.go @@ -32,7 +32,6 @@ package builder_utils import ( "bytes" "fmt" - "io" "os" "os/exec" "path/filepath" @@ -41,72 +40,78 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" ) -func CompileFilesRecursive(objectFiles []string, sourcePath string, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { - objectFiles, err := CompileFiles(objectFiles, sourcePath, false, buildPath, buildProperties, includes, verbose, warningsLevel, logger) +func CompileFilesRecursive(sourcePath *paths.Path, buildPath *paths.Path, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { + objectFiles, err := CompileFiles(sourcePath, false, buildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) + folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs) if err != nil { return nil, i18n.WrapError(err) } for _, folder := range folders { - objectFiles, err = CompileFilesRecursive(objectFiles, filepath.Join(sourcePath, folder.Name()), filepath.Join(buildPath, folder.Name()), buildProperties, includes, verbose, warningsLevel, logger) + subFolderObjectFiles, err := CompileFilesRecursive(sourcePath.Join(folder.Name()), buildPath.Join(folder.Name()), buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } + objectFiles.AddAll(subFolderObjectFiles) } return objectFiles, nil } -func CompileFiles(objectFiles []string, sourcePath string, recurse bool, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { - objectFiles, err := compileFilesWithExtensionWithRecipe(objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".S", constants.RECIPE_S_PATTERN, verbose, warningsLevel, logger) +func CompileFiles(sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { + sObjectFiles, err := compileFilesWithExtensionWithRecipe(sourcePath, recurse, buildPath, buildProperties, includes, ".S", constants.RECIPE_S_PATTERN, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } - objectFiles, err = compileFilesWithExtensionWithRecipe(objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".c", constants.RECIPE_C_PATTERN, verbose, warningsLevel, logger) + cObjectFiles, err := compileFilesWithExtensionWithRecipe(sourcePath, recurse, buildPath, buildProperties, includes, ".c", constants.RECIPE_C_PATTERN, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } - objectFiles, err = compileFilesWithExtensionWithRecipe(objectFiles, sourcePath, recurse, buildPath, buildProperties, includes, ".cpp", constants.RECIPE_CPP_PATTERN, verbose, warningsLevel, logger) + cppObjectFiles, err := compileFilesWithExtensionWithRecipe(sourcePath, recurse, buildPath, buildProperties, includes, ".cpp", constants.RECIPE_CPP_PATTERN, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } + objectFiles := paths.NewPathList() + objectFiles.AddAll(sObjectFiles) + objectFiles.AddAll(cObjectFiles) + objectFiles.AddAll(cppObjectFiles) return objectFiles, nil } -func compileFilesWithExtensionWithRecipe(objectFiles []string, sourcePath string, recurse bool, buildPath string, buildProperties properties.Map, includes []string, extension string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { +func compileFilesWithExtensionWithRecipe(sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties properties.Map, includes []string, extension string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { sources, err := findFilesInFolder(sourcePath, extension, recurse) if err != nil { return nil, i18n.WrapError(err) } - return compileFilesWithRecipe(objectFiles, sourcePath, sources, buildPath, buildProperties, includes, recipe, verbose, warningsLevel, logger) + return compileFilesWithRecipe(sourcePath, sources, buildPath, buildProperties, includes, recipe, verbose, warningsLevel, logger) } -func findFilesInFolder(sourcePath string, extension string, recurse bool) ([]string, error) { - files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFilesWithExtensions(extension)) +func findFilesInFolder(sourcePath *paths.Path, extension string, recurse bool) (paths.PathList, error) { + files, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterFilesWithExtensions(extension)) if err != nil { return nil, i18n.WrapError(err) } - var sources []string + var sources paths.PathList for _, file := range files { - sources = append(sources, filepath.Join(sourcePath, file.Name())) + sources = append(sources, sourcePath.Join(file.Name())) } if recurse { - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) + folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs) if err != nil { return nil, i18n.WrapError(err) } for _, folder := range folders { - otherSources, err := findFilesInFolder(filepath.Join(sourcePath, folder.Name()), extension, recurse) + otherSources, err := findFilesInFolder(sourcePath.Join(folder.Name()), extension, recurse) if err != nil { return nil, i18n.WrapError(err) } @@ -145,62 +150,65 @@ func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) { return sources, nil } -func compileFilesWithRecipe(objectFiles []string, sourcePath string, sources []string, buildPath string, buildProperties properties.Map, includes []string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { +func compileFilesWithRecipe(sourcePath *paths.Path, sources paths.PathList, buildPath *paths.Path, buildProperties properties.Map, includes []string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { + objectFiles := paths.NewPathList() for _, source := range sources { - objectFile, err := compileFileWithRecipe(sourcePath, source, buildPath, buildProperties, includes, recipe, verbose, warningsLevel, logger) + objFile, err := compileFileWithRecipe(sourcePath, source, buildPath, buildProperties, includes, recipe, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } - objectFiles = append(objectFiles, objectFile) + objectFiles.Add(objFile) } return objectFiles, nil } -func compileFileWithRecipe(sourcePath string, source string, buildPath string, buildProperties properties.Map, includes []string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) (string, error) { +func compileFileWithRecipe(sourcePath *paths.Path, source *paths.Path, buildPath *paths.Path, buildProperties properties.Map, includes []string, recipe string, verbose bool, warningsLevel string, logger i18n.Logger) (*paths.Path, error) { properties := buildProperties.Clone() properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+warningsLevel] properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includes, constants.SPACE) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = source - relativeSource, err := filepath.Rel(sourcePath, source) + properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = source.String() + relativeSource, err := sourcePath.RelTo(source) if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = filepath.Join(buildPath, relativeSource+".o") + properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = buildPath.JoinPath(relativeSource).String() + ".o" - err = utils.EnsureFolderExists(filepath.Dir(properties[constants.BUILD_PROPERTIES_OBJECT_FILE])) + err = paths.New(properties[constants.BUILD_PROPERTIES_OBJECT_FILE]).Parent().MkdirAll() if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } - objIsUpToDate, err := ObjFileIsUpToDate(properties[constants.BUILD_PROPERTIES_SOURCE_FILE], properties[constants.BUILD_PROPERTIES_OBJECT_FILE], filepath.Join(buildPath, relativeSource+".d")) + objIsUpToDate, err := ObjFileIsUpToDate(properties.GetPath(constants.BUILD_PROPERTIES_SOURCE_FILE), properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE), buildPath.Join(relativeSource.String()+".d")) if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } if !objIsUpToDate { _, err = ExecRecipe(properties, recipe, false, verbose, verbose, logger) if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } } else if verbose { logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, properties[constants.BUILD_PROPERTIES_OBJECT_FILE]) } - return properties[constants.BUILD_PROPERTIES_OBJECT_FILE], nil + return paths.New(properties[constants.BUILD_PROPERTIES_OBJECT_FILE]), nil } -func ObjFileIsUpToDate(sourceFile, objectFile, dependencyFile string) (bool, error) { - sourceFile = filepath.Clean(sourceFile) - objectFile = filepath.Clean(objectFile) - dependencyFile = filepath.Clean(dependencyFile) +func ObjFileIsUpToDate(sourceFile, objectFile, dependencyFile *paths.Path) (bool, error) { + if objectFile == nil || dependencyFile == nil { + return false, nil + } - sourceFileStat, err := os.Stat(sourceFile) + sourceFile = sourceFile.Clean() + sourceFileStat, err := sourceFile.Stat() if err != nil { return false, i18n.WrapError(err) } - objectFileStat, err := os.Stat(objectFile) + objectFile = objectFile.Clean() + objectFileStat, err := objectFile.Stat() if err != nil { if os.IsNotExist(err) { return false, nil @@ -209,7 +217,8 @@ func ObjFileIsUpToDate(sourceFile, objectFile, dependencyFile string) (bool, err } } - dependencyFileStat, err := os.Stat(dependencyFile) + dependencyFile = dependencyFile.Clean() + dependencyFileStat, err := dependencyFile.Stat() if err != nil { if os.IsNotExist(err) { return false, nil @@ -225,7 +234,7 @@ func ObjFileIsUpToDate(sourceFile, objectFile, dependencyFile string) (bool, err return false, nil } - rows, err := utils.ReadFileToRows(dependencyFile) + rows, err := dependencyFile.ReadFileAsLines() if err != nil { return false, i18n.WrapError(err) } @@ -244,7 +253,7 @@ func ObjFileIsUpToDate(sourceFile, objectFile, dependencyFile string) (bool, err return false, nil } objFileInDepFile := firstRow[:len(firstRow)-1] - if objFileInDepFile != objectFile { + if objFileInDepFile != objectFile.String() { return false, nil } @@ -287,11 +296,11 @@ func nonEmptyString(s string) bool { return s != constants.EMPTY_STRING } -func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile string) bool { +func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile *paths.Path) bool { - targetFileStat, err := os.Stat(targetFile) + targetFileStat, err := targetFile.Stat() if err == nil { - files, err := findAllFilesInFolder(corePath, true) + files, err := findAllFilesInFolder(corePath.String(), true) if err != nil { return true } @@ -301,24 +310,24 @@ func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile string) return true } } - if targetCorePath != constants.EMPTY_STRING && !strings.EqualFold(corePath, targetCorePath) { - return CoreOrReferencedCoreHasChanged(targetCorePath, constants.EMPTY_STRING, targetFile) + if targetCorePath != nil && !strings.EqualFold(corePath.String(), targetCorePath.String()) { + return CoreOrReferencedCoreHasChanged(targetCorePath, nil, targetFile) } return false } return true } -func ArchiveCompiledFiles(buildPath string, archiveFile string, objectFiles []string, buildProperties properties.Map, verbose bool, logger i18n.Logger) (string, error) { - archiveFilePath := filepath.Join(buildPath, archiveFile) +func ArchiveCompiledFiles(buildPath *paths.Path, archiveFile *paths.Path, objectFilesToArchive paths.PathList, buildProperties properties.Map, verbose bool, logger i18n.Logger) (*paths.Path, error) { + archiveFilePath := buildPath.JoinPath(archiveFile) rebuildArchive := false - if archiveFileStat, err := os.Stat(archiveFilePath); err == nil { + if archiveFileStat, err := archiveFilePath.Stat(); err == nil { - for _, objectFile := range objectFiles { - objectFileStat, _ := os.Stat(objectFile) - if objectFileStat.ModTime().After(archiveFileStat.ModTime()) { + for _, objectFile := range objectFilesToArchive { + objectFileStat, err := objectFile.Stat() + if err != nil || objectFileStat.ModTime().After(archiveFileStat.ModTime()) { // need to rebuild the archive rebuildArchive = true break @@ -327,9 +336,9 @@ func ArchiveCompiledFiles(buildPath string, archiveFile string, objectFiles []st // something changed, rebuild the core archive if rebuildArchive { - err = os.Remove(archiveFilePath) + err = archiveFilePath.Remove() if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } } else { if verbose { @@ -339,15 +348,15 @@ func ArchiveCompiledFiles(buildPath string, archiveFile string, objectFiles []st } } - for _, objectFile := range objectFiles { + for _, objectFile := range objectFilesToArchive { properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = filepath.Base(archiveFilePath) - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = archiveFilePath - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = objectFile + properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = archiveFilePath.Base() + properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = archiveFilePath.String() + properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = objectFile.String() _, err := ExecRecipe(properties, constants.RECIPE_AR_PATTERN, false, verbose, verbose, logger) if err != nil { - return "", i18n.WrapError(err) + return nil, i18n.WrapError(err) } } @@ -377,7 +386,7 @@ func ExecRecipe(properties properties.Map, recipe string, removeUnsetProperties func PrepareCommandForRecipe(buildProperties properties.Map, recipe string, removeUnsetProperties bool, echoCommandLine bool, logger i18n.Logger) (*exec.Cmd, error) { pattern := buildProperties[recipe] - if pattern == constants.EMPTY_STRING { + if pattern == "" { return nil, i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, recipe) } @@ -415,58 +424,14 @@ func RemoveHyphenMDDFlagFromGCCCommandLine(buildProperties properties.Map) { buildProperties[constants.BUILD_PROPERTIES_COMPILER_CPP_FLAGS] = strings.Replace(buildProperties[constants.BUILD_PROPERTIES_COMPILER_CPP_FLAGS], "-MMD", "", -1) } -// CopyFile copies the contents of the file named src to the file named -// by dst. The file will be created if it does not already exist. If the -// destination file exists, all it's contents will be replaced by the contents -// of the source file. The file mode will be copied from the source and -// the copied data is synced/flushed to stable storage. -func CopyFile(src, dst string) (err error) { - in, err := os.Open(src) - if err != nil { - return - } - defer in.Close() - - out, err := os.Create(dst) - if err != nil { - return - } - defer func() { - if e := out.Close(); e != nil { - err = e - } - }() - - _, err = io.Copy(out, in) - if err != nil { - return - } - - err = out.Sync() - if err != nil { - return - } - - si, err := os.Stat(src) - if err != nil { - return - } - err = os.Chmod(dst, si.Mode()) - if err != nil { - return - } - - return -} - // GetCachedCoreArchiveFileName returns the filename to be used to store // the global cached core.a. -func GetCachedCoreArchiveFileName(fqbn, coreFolder string) string { +func GetCachedCoreArchiveFileName(fqbn string, coreFolder *paths.Path) string { fqbnToUnderscore := strings.Replace(fqbn, ":", "_", -1) fqbnToUnderscore = strings.Replace(fqbnToUnderscore, "=", "_", -1) - if absCoreFolder, err := filepath.Abs(coreFolder); err == nil { + if absCoreFolder, err := coreFolder.Abs(); err == nil { coreFolder = absCoreFolder } // silently continue if absolute path can't be detected - hash := utils.MD5Sum([]byte(coreFolder)) + hash := utils.MD5Sum([]byte(coreFolder.String())) return "core_" + fqbnToUnderscore + "_" + hash + ".a" } diff --git a/container_add_prototypes.go b/container_add_prototypes.go index cd0d56f7..bbfa2fd3 100644 --- a/container_add_prototypes.go +++ b/container_add_prototypes.go @@ -30,7 +30,7 @@ package builder import ( - "path/filepath" + "github.com/arduino/go-paths-helper" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" @@ -40,9 +40,9 @@ import ( type ContainerAddPrototypes struct{} func (s *ContainerAddPrototypes) Run(ctx *types.Context) error { - sourceFile := filepath.Join(ctx.SketchBuildPath, filepath.Base(ctx.Sketch.MainFile.Name)+".cpp") + sourceFile := ctx.SketchBuildPath.Join(ctx.Sketch.MainFile.Name.Base() + ".cpp") commands := []types.Command{ - &GCCPreprocRunner{SourceFilePath: sourceFile, TargetFileName: constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E, Includes: ctx.IncludeFolders}, + &GCCPreprocRunner{SourceFilePath: sourceFile, TargetFileName: paths.New(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E), Includes: ctx.IncludeFolders}, &ReadFileAndStoreInContext{Target: &ctx.SourceGccMinusE}, &FilterSketchSource{Source: &ctx.SourceGccMinusE}, &CTagsTargetFileSaver{Source: &ctx.SourceGccMinusE, TargetFileName: constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E}, diff --git a/container_find_includes.go b/container_find_includes.go index f599731c..66a6764e 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -108,9 +108,6 @@ package builder import ( "encoding/json" - "io/ioutil" - "os" - "path/filepath" "time" "github.com/arduino/arduino-builder/builder_utils" @@ -118,22 +115,23 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type ContainerFindIncludes struct{} func (s *ContainerFindIncludes) Run(ctx *types.Context) error { - cachePath := filepath.Join(ctx.BuildPath, constants.FILE_INCLUDES_CACHE) + cachePath := ctx.BuildPath.Join(constants.FILE_INCLUDES_CACHE) cache := readCache(cachePath) - appendIncludeFolder(ctx, cache, "", "", ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH]) - if ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] != constants.EMPTY_STRING { - appendIncludeFolder(ctx, cache, "", "", ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH]) + appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_CORE_PATH)) + if ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] != "" { + appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH)) } sketch := ctx.Sketch - mergedfile, err := types.MakeSourceFile(ctx, sketch, filepath.Base(sketch.MainFile.Name)+".cpp") + mergedfile, err := types.MakeSourceFile(ctx, sketch, paths.New(sketch.MainFile.Name.Base()+".cpp")) if err != nil { return i18n.WrapError(err) } @@ -141,15 +139,15 @@ func (s *ContainerFindIncludes) Run(ctx *types.Context) error { sourceFilePaths := ctx.CollectedSourceFiles queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, ctx.SketchBuildPath, false /* recurse */) - srcSubfolderPath := filepath.Join(ctx.SketchBuildPath, constants.SKETCH_FOLDER_SRC) - if info, err := os.Stat(srcSubfolderPath); err == nil && info.IsDir() { + srcSubfolderPath := ctx.SketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) + if isDir, _ := srcSubfolderPath.IsDir(); isDir { queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, srcSubfolderPath, true /* recurse */) } for !sourceFilePaths.Empty() { err := findIncludesUntilDone(ctx, cache, sourceFilePaths.Pop()) if err != nil { - os.Remove(cachePath) + cachePath.Remove() return i18n.WrapError(err) } } @@ -174,7 +172,7 @@ func (s *ContainerFindIncludes) Run(ctx *types.Context) error { // include (e.g. what #include line in what file it was resolved from) // and should be the empty string for the default include folders, like // the core or variant. -func appendIncludeFolder(ctx *types.Context, cache *includeCache, sourceFilePath string, include string, folder string) { +func appendIncludeFolder(ctx *types.Context, cache *includeCache, sourceFilePath *paths.Path, include string, folder *paths.Path) { ctx.IncludeFolders = append(ctx.IncludeFolders, folder) cache.ExpectEntry(sourceFilePath, include, folder) } @@ -189,9 +187,9 @@ func runCommand(ctx *types.Context, command types.Command) error { } type includeCacheEntry struct { - Sourcefile string + Sourcefile *paths.Path Include string - Includepath string + Includepath *paths.Path } type includeCache struct { @@ -213,8 +211,8 @@ func (cache *includeCache) Next() includeCacheEntry { // Check that the next cache entry is about the given file. If it is // not, or no entry is available, the cache is invalidated. Does not // advance the cache. -func (cache *includeCache) ExpectFile(sourcefile string) { - if cache.valid && cache.next < len(cache.entries) && cache.Next().Sourcefile != sourcefile { +func (cache *includeCache) ExpectFile(sourcefile *paths.Path) { + if cache.valid && cache.next < len(cache.entries) && cache.Next().Sourcefile.String() != sourcefile.String() { cache.valid = false cache.entries = cache.entries[:cache.next] } @@ -224,7 +222,7 @@ func (cache *includeCache) ExpectFile(sourcefile string) { // the cache. If not, the cache is invalidated. If the cache is // invalidated, or was already invalid, an entry with the given values // is appended. -func (cache *includeCache) ExpectEntry(sourcefile string, include string, librarypath string) { +func (cache *includeCache) ExpectEntry(sourcefile *paths.Path, include string, librarypath *paths.Path) { entry := includeCacheEntry{Sourcefile: sourcefile, Include: include, Includepath: librarypath} if cache.valid { if cache.next < len(cache.entries) && cache.Next() == entry { @@ -250,8 +248,8 @@ func (cache *includeCache) ExpectEnd() { } // Read the cache from the given file -func readCache(path string) *includeCache { - bytes, err := ioutil.ReadFile(path) +func readCache(path *paths.Path) *includeCache { + bytes, err := path.ReadFile() if err != nil { // Return an empty, invalid cache return &includeCache{} @@ -268,19 +266,19 @@ func readCache(path string) *includeCache { // Write the given cache to the given file if it is invalidated. If the // cache is still valid, just update the timestamps of the file. -func writeCache(cache *includeCache, path string) error { +func writeCache(cache *includeCache, path *paths.Path) error { // If the cache was still valid all the way, just touch its file // (in case any source file changed without influencing the // includes). If it was invalidated, overwrite the cache with // the new contents. if cache.valid { - os.Chtimes(path, time.Now(), time.Now()) + path.Chtimes(time.Now(), time.Now()) } else { bytes, err := json.MarshalIndent(cache.entries, "", " ") if err != nil { return i18n.WrapError(err) } - err = utils.WriteFileBytes(path, bytes) + err = path.WriteFile(bytes) if err != nil { return i18n.WrapError(err) } @@ -290,7 +288,7 @@ func writeCache(cache *includeCache, path string) error { func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile types.SourceFile) error { sourcePath := sourceFile.SourcePath(ctx) - targetFilePath := utils.NULLFile() + targetFilePath := paths.NullPath() // TODO: This should perhaps also compare against the // include.cache file timestamp. Now, it only checks if the file @@ -316,7 +314,7 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t includes := ctx.IncludeFolders if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityFolder != nil { - includes = append(includes, library.UtilityFolder.String()) + includes = append(includes, library.UtilityFolder) } if unchanged && cache.valid { include = cache.Next().Include @@ -339,14 +337,14 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t if include == "" { // No missing includes found, we're done - cache.ExpectEntry(sourcePath, "", "") + cache.ExpectEntry(sourcePath, "", nil) return nil } library := ResolveLibrary(ctx, include) if library == nil { // Library could not be resolved, show error - err := runCommand(ctx, &GCCPreprocRunner{SourceFilePath: sourcePath, TargetFileName: constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E, Includes: includes}) + err := runCommand(ctx, &GCCPreprocRunner{SourceFilePath: sourcePath, TargetFileName: paths.New(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E), Includes: includes}) return i18n.WrapError(err) } @@ -354,26 +352,26 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t // include path and queue its source files for further // include scanning ctx.ImportedLibraries = append(ctx.ImportedLibraries, library) - appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder.String()) + appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder) sourceFolders := library.SourceDirs() for _, sourceFolder := range sourceFolders { - queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder.String(), sourceFolder.Recurse) + queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder, sourceFolder.Recurse) } first = false } } -func queueSourceFilesFromFolder(ctx *types.Context, queue *types.UniqueSourceFileQueue, origin interface{}, folder string, recurse bool) error { +func queueSourceFilesFromFolder(ctx *types.Context, queue *types.UniqueSourceFileQueue, origin interface{}, folder *paths.Path, recurse bool) error { extensions := func(ext string) bool { return ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS[ext] } filePaths := []string{} - err := utils.FindFilesInFolder(&filePaths, folder, extensions, recurse) + err := utils.FindFilesInFolder(&filePaths, folder.String(), extensions, recurse) if err != nil { return i18n.WrapError(err) } for _, filePath := range filePaths { - sourceFile, err := types.MakeSourceFile(ctx, origin, filePath) + sourceFile, err := types.MakeSourceFile(ctx, origin, paths.New(filePath)) if err != nil { return i18n.WrapError(err) } diff --git a/ctags/ctags_parser.go b/ctags/ctags_parser.go index fc45b8ff..7bcc4c6c 100644 --- a/ctags/ctags_parser.go +++ b/ctags/ctags_parser.go @@ -33,6 +33,8 @@ import ( "strconv" "strings" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/types" ) @@ -52,10 +54,10 @@ var KNOWN_TAG_KINDS = map[string]bool{ type CTagsParser struct { tags []*types.CTag - mainFile string + mainFile *paths.Path } -func (p *CTagsParser) Parse(ctagsOutput string, mainFile string) []*types.CTag { +func (p *CTagsParser) Parse(ctagsOutput string, mainFile *paths.Path) []*types.CTag { rows := strings.Split(ctagsOutput, "\n") rows = removeEmpty(rows) diff --git a/ctags/ctags_parser_test.go b/ctags/ctags_parser_test.go index 8813e772..41f7ccd0 100644 --- a/ctags/ctags_parser_test.go +++ b/ctags/ctags_parser_test.go @@ -44,7 +44,7 @@ func produceTags(t *testing.T, filename string) []*types.CTag { require.NoError(t, err) parser := CTagsParser{} - return parser.Parse(string(bytes), "") + return parser.Parse(string(bytes), nil) } func TestCTagsParserShouldListPrototypes(t *testing.T) { diff --git a/ctags/ctags_to_prototypes.go b/ctags/ctags_to_prototypes.go index 7117c3f1..a1f654f9 100644 --- a/ctags/ctags_to_prototypes.go +++ b/ctags/ctags_to_prototypes.go @@ -92,7 +92,7 @@ func (p *CTagsParser) collectFunctions() []*types.CTag { func (p *CTagsParser) firstFunctionAtLine() int { for _, tag := range p.tags { - if !tagIsUnknown(tag) && isHandled(tag) && tag.Kind == KIND_FUNCTION && tag.Filename == p.mainFile { + if !tagIsUnknown(tag) && isHandled(tag) && tag.Kind == KIND_FUNCTION && tag.Filename == p.mainFile.String() { return tag.Line } } diff --git a/ctags/ctags_to_prototypes_test.go b/ctags/ctags_to_prototypes_test.go index 9388747d..429f72ed 100644 --- a/ctags/ctags_to_prototypes_test.go +++ b/ctags/ctags_to_prototypes_test.go @@ -35,6 +35,7 @@ import ( "testing" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -43,7 +44,7 @@ func producePrototypes(t *testing.T, filename string, mainFile string) ([]*types require.NoError(t, err) parser := &CTagsParser{} - parser.Parse(string(bytes), mainFile) + parser.Parse(string(bytes), paths.New(mainFile)) return parser.GeneratePrototypes() } diff --git a/ctags_runner.go b/ctags_runner.go index 82e4165c..b55d4992 100644 --- a/ctags_runner.go +++ b/ctags_runner.go @@ -48,7 +48,7 @@ func (s *CTagsRunner) Run(ctx *types.Context) error { properties := buildProperties.Clone() properties.Merge(buildProperties.SubTree(constants.BUILD_PROPERTIES_TOOLS_KEY).SubTree(constants.CTAGS)) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = ctagsTargetFilePath + properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, ctagsTargetFilePath) pattern := properties[constants.BUILD_PROPERTIES_PATTERN] if pattern == constants.EMPTY_STRING { diff --git a/ctags_target_file_saver.go b/ctags_target_file_saver.go index 3c79b31f..ef94ff95 100644 --- a/ctags_target_file_saver.go +++ b/ctags_target_file_saver.go @@ -32,8 +32,6 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" ) type CTagsTargetFileSaver struct { @@ -45,18 +43,15 @@ func (s *CTagsTargetFileSaver) Run(ctx *types.Context) error { source := *s.Source preprocPath := ctx.PreprocPath - err := utils.EnsureFolderExists(preprocPath) - if err != nil { + if err := preprocPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - ctagsTargetFilePath := filepath.Join(preprocPath, s.TargetFileName) - err = utils.WriteFile(ctagsTargetFilePath, source) - if err != nil { + ctagsTargetFilePath := preprocPath.Join(s.TargetFileName) + if err := ctagsTargetFilePath.WriteFile([]byte(source)); err != nil { return i18n.WrapError(err) } ctx.CTagsTargetFile = ctagsTargetFilePath - return nil } diff --git a/ensure_buildpath_exists.go b/ensure_buildpath_exists.go index 495b8d83..15b5c42d 100644 --- a/ensure_buildpath_exists.go +++ b/ensure_buildpath_exists.go @@ -32,16 +32,13 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" ) type EnsureBuildPathExists struct{} func (s *EnsureBuildPathExists) Run(ctx *types.Context) error { - err := utils.EnsureFolderExists(ctx.BuildPath) - if err != nil { + if err := ctx.BuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - return nil } diff --git a/fail_if_buildpath_equals_sketchpath.go b/fail_if_buildpath_equals_sketchpath.go index 4a3ac711..84359db3 100644 --- a/fail_if_buildpath_equals_sketchpath.go +++ b/fail_if_buildpath_equals_sketchpath.go @@ -33,28 +33,27 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "path/filepath" ) type FailIfBuildPathEqualsSketchPath struct{} func (s *FailIfBuildPathEqualsSketchPath) Run(ctx *types.Context) error { - if ctx.BuildPath == "" || ctx.SketchLocation == "" { + if ctx.BuildPath == nil || ctx.SketchLocation == nil { return nil } - buildPath, err := filepath.Abs(ctx.BuildPath) + buildPath, err := ctx.BuildPath.Abs() if err != nil { return i18n.WrapError(err) } - sketchPath, err := filepath.Abs(ctx.SketchLocation) + sketchPath, err := ctx.SketchLocation.Abs() if err != nil { return i18n.WrapError(err) } - sketchPath = filepath.Dir(sketchPath) + sketchPath = sketchPath.Parent() - if buildPath == sketchPath { + if buildPath.EqualsTo(sketchPath) { return i18n.ErrorfWithLogger(ctx.GetLogger(), constants.MSG_SKETCH_CANT_BE_IN_BUILDPATH) } diff --git a/filter_sketch_source.go b/filter_sketch_source.go index 6de658cd..8146697c 100644 --- a/filter_sketch_source.go +++ b/filter_sketch_source.go @@ -34,6 +34,8 @@ import ( "strconv" "strings" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" ) @@ -43,7 +45,8 @@ type FilterSketchSource struct { } func (s *FilterSketchSource) Run(ctx *types.Context) error { - fileNames := []string{ctx.Sketch.MainFile.Name} + fileNames := paths.NewPathList() + fileNames.Add(ctx.Sketch.MainFile.Name) for _, file := range ctx.Sketch.OtherSketchFiles { fileNames = append(fileNames, file.Name) } @@ -54,9 +57,8 @@ func (s *FilterSketchSource) Run(ctx *types.Context) error { scanner := bufio.NewScanner(strings.NewReader(*s.Source)) for scanner.Scan() { line := scanner.Text() - filename := parseLineMarker(line) - if filename != "" { - inSketch = utils.SliceContains(fileNames, filename) + if filename := parseLineMarker(line); filename != nil { + inSketch = fileNames.Contains(filename) } if inSketch { @@ -70,7 +72,7 @@ func (s *FilterSketchSource) Run(ctx *types.Context) error { // Parses the given line as a gcc line marker and returns the contained // filename. -func parseLineMarker(line string) string { +func parseLineMarker(line string) *paths.Path { // A line marker contains the line number and filename and looks like: // # 123 /path/to/file.cpp // It can be followed by zero or more flag number that indicate the @@ -80,12 +82,12 @@ func parseLineMarker(line string) string { split := strings.SplitN(line, " ", 3) if len(split) < 3 || split[0] != "#" { - return "" + return nil } _, err := strconv.Atoi(split[1]) if err != nil { - return "" + return nil } // If we get here, we found a # followed by a line number, so @@ -94,7 +96,7 @@ func parseLineMarker(line string) string { str, rest, ok := utils.ParseCppString(split[2]) if ok && (rest == "" || rest[0] == ' ') { - return str + return paths.New(str) } - return "" + return nil } diff --git a/gcc_preproc_runner.go b/gcc_preproc_runner.go index 40ff59e7..cc57a51c 100644 --- a/gcc_preproc_runner.go +++ b/gcc_preproc_runner.go @@ -30,7 +30,6 @@ package builder import ( - "path/filepath" "strings" "github.com/arduino/arduino-builder/builder_utils" @@ -38,13 +37,14 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" ) type GCCPreprocRunner struct { - SourceFilePath string - TargetFileName string - Includes []string + SourceFilePath *paths.Path + TargetFileName *paths.Path + Includes paths.PathList } func (s *GCCPreprocRunner) Run(ctx *types.Context) error { @@ -71,9 +71,9 @@ func (s *GCCPreprocRunner) Run(ctx *types.Context) error { } type GCCPreprocRunnerForDiscoveringIncludes struct { - SourceFilePath string - TargetFilePath string - Includes []string + SourceFilePath *paths.Path + TargetFilePath *paths.Path + Includes paths.PathList } func (s *GCCPreprocRunnerForDiscoveringIncludes) Run(ctx *types.Context) error { @@ -100,22 +100,20 @@ func (s *GCCPreprocRunnerForDiscoveringIncludes) Run(ctx *types.Context) error { return nil } -func prepareGCCPreprocRecipeProperties(ctx *types.Context, sourceFilePath string, targetFilePath string, includes []string) (properties.Map, string, error) { - if targetFilePath != utils.NULLFile() { +func prepareGCCPreprocRecipeProperties(ctx *types.Context, sourceFilePath *paths.Path, targetFilePath *paths.Path, includes paths.PathList) (properties.Map, *paths.Path, error) { + if !targetFilePath.EqualsTo(paths.NullPath()) { preprocPath := ctx.PreprocPath - err := utils.EnsureFolderExists(preprocPath) - if err != nil { - return nil, "", i18n.WrapError(err) + if err := preprocPath.MkdirAll(); err != nil { + return nil, nil, i18n.WrapError(err) } - targetFilePath = filepath.Join(preprocPath, targetFilePath) + targetFilePath = preprocPath.JoinPath(targetFilePath) } properties := ctx.BuildProperties.Clone() - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = sourceFilePath - properties[constants.BUILD_PROPERTIES_PREPROCESSED_FILE_PATH] = targetFilePath + properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, sourceFilePath) + properties.SetPath(constants.BUILD_PROPERTIES_PREPROCESSED_FILE_PATH, targetFilePath) - includes = utils.Map(includes, utils.WrapWithHyphenI) - properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includes, constants.SPACE) + properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(utils.Map(includes.AsStrings(), utils.WrapWithHyphenI), constants.SPACE) builder_utils.RemoveHyphenMDDFlagFromGCCCommandLine(properties) return properties, targetFilePath, nil diff --git a/generate_buildpath_if_missing.go b/generate_buildpath_if_missing.go index 7b11ae13..20afef86 100644 --- a/generate_buildpath_if_missing.go +++ b/generate_buildpath_if_missing.go @@ -30,29 +30,25 @@ package builder import ( + "os" + "strings" + "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" - "strings" + paths "github.com/arduino/go-paths-helper" ) type GenerateBuildPathIfMissing struct{} func (s *GenerateBuildPathIfMissing) Run(ctx *types.Context) error { - if ctx.BuildPath != "" { + if ctx.BuildPath != nil { return nil } - md5sum := utils.MD5Sum([]byte(ctx.SketchLocation)) + md5sum := utils.MD5Sum([]byte(ctx.SketchLocation.String())) - buildPath := filepath.Join(os.TempDir(), "arduino-sketch-"+strings.ToUpper(md5sum)) - _, err := os.Stat(buildPath) - if err != nil && !os.IsNotExist(err) { - return i18n.WrapError(err) - } + buildPath := paths.TempDir().Join("arduino-sketch-" + strings.ToUpper(md5sum)) if ctx.DebugLevel > 5 { logger := ctx.GetLogger() diff --git a/hardware_loader.go b/hardware_loader.go index 04988411..4283af50 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -33,14 +33,13 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" - "github.com/bcmi-labs/arduino-cli/paths" ) type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { pm := packagemanager.NewPackageManager() - if err := pm.LoadHardwareFromDirectories(paths.NewPathList(ctx.HardwareFolders...)); err != nil { + if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { return i18n.WrapError(err) } ctx.PackageManager = pm diff --git a/libraries_loader.go b/libraries_loader.go index dc641d72..9a272e9b 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -31,25 +31,23 @@ package builder import ( "os" - "path/filepath" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" - "github.com/bcmi-labs/arduino-cli/paths" ) type LibrariesLoader struct{} func (s *LibrariesLoader) Run(ctx *types.Context) error { builtInLibrariesFolders := ctx.BuiltInLibrariesFolders - builtInLibrariesFolders, err := utils.AbsolutizePaths(builtInLibrariesFolders) - if err != nil { + if err := builtInLibrariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - sortedLibrariesFolders := []string{} - sortedLibrariesFolders = utils.AppendIfNotPresent(sortedLibrariesFolders, builtInLibrariesFolders...) + sortedLibrariesFolders := paths.NewPathList() + sortedLibrariesFolders.AddAllMissing(builtInLibrariesFolders) platform := ctx.TargetPlatform debugLevel := ctx.DebugLevel @@ -57,28 +55,33 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { actualPlatform := ctx.ActualPlatform if actualPlatform != platform { - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(actualPlatform.Folder, "libraries")) + actualPlatformLibDir := paths.New(actualPlatform.Folder).Join("libraries") + if isDir, _ := actualPlatformLibDir.IsDir(); isDir { + sortedLibrariesFolders.Add(actualPlatformLibDir) + } } - sortedLibrariesFolders = appendPathToLibrariesFolders(sortedLibrariesFolders, filepath.Join(platform.Folder, "libraries")) + platformLibDir := paths.New(platform.Folder).Join("libraries") + if isDir, _ := platformLibDir.IsDir(); isDir { + sortedLibrariesFolders.Add(platformLibDir) + } librariesFolders := ctx.OtherLibrariesFolders - librariesFolders, err = utils.AbsolutizePaths(librariesFolders) - if err != nil { + if err := librariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - sortedLibrariesFolders = utils.AppendIfNotPresent(sortedLibrariesFolders, librariesFolders...) + sortedLibrariesFolders.AddAllMissing(librariesFolders) ctx.LibrariesFolders = sortedLibrariesFolders var libs []*libraries.Library for _, libraryFolder := range sortedLibrariesFolders { - subFolders, err := utils.ReadDirFiltered(libraryFolder, utils.FilterDirs) + subFolders, err := utils.ReadDirFiltered(libraryFolder.String(), utils.FilterDirs) if err != nil { return i18n.WrapError(err) } for _, subFolder := range subFolders { - library, err := libraries.Load(paths.New(libraryFolder).Join(subFolder.Name())) + library, err := libraries.Load(libraryFolder.Join(subFolder.Name())) if debugLevel > 0 { if warnings, err := library.Lint(); err != nil { return i18n.WrapError(err) @@ -113,11 +116,3 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { return nil } - -func appendPathToLibrariesFolders(librariesFolders []string, newLibrariesFolder string) []string { - if stat, err := os.Stat(newLibrariesFolder); os.IsNotExist(err) || !stat.IsDir() { - return librariesFolders - } - - return utils.AppendIfNotPresent(librariesFolders, newLibrariesFolder) -} diff --git a/load_previous_build_options.go b/load_previous_build_options.go index 3b9bd5d0..93997271 100644 --- a/load_previous_build_options.go +++ b/load_previous_build_options.go @@ -33,25 +33,22 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "io/ioutil" - "os" - "path/filepath" ) type LoadPreviousBuildOptionsMap struct{} func (s *LoadPreviousBuildOptionsMap) Run(ctx *types.Context) error { - buildOptionsFile := filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE) + buildOptionsFile := ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE) - _, err := os.Stat(buildOptionsFile) - if err != nil { - if os.IsNotExist(err) { + if exist, err := buildOptionsFile.Exist(); err == nil { + if !exist { return nil } + } else { return i18n.WrapError(err) } - bytes, err := ioutil.ReadFile(buildOptionsFile) + bytes, err := buildOptionsFile.ReadFile() if err != nil { return i18n.WrapError(err) } diff --git a/merge_sketch_with_bootloader.go b/merge_sketch_with_bootloader.go index ebefa77e..9df6c911 100644 --- a/merge_sketch_with_bootloader.go +++ b/merge_sketch_with_bootloader.go @@ -30,13 +30,15 @@ package builder import ( + "os" + "strings" + + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" - "strings" ) type MergeSketchWithBootloader struct{} @@ -49,16 +51,16 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { buildPath := ctx.BuildPath sketch := ctx.Sketch - sketchFileName := filepath.Base(sketch.MainFile.Name) + sketchFileName := sketch.MainFile.Name.Base() logger := ctx.GetLogger() - sketchInBuildPath := filepath.Join(buildPath, sketchFileName+".hex") - sketchInSubfolder := filepath.Join(buildPath, constants.FOLDER_SKETCH, sketchFileName+".hex") + sketchInBuildPath := buildPath.Join(sketchFileName + ".hex") + sketchInSubfolder := buildPath.Join(constants.FOLDER_SKETCH, sketchFileName+".hex") - builtSketchPath := constants.EMPTY_STRING - if _, err := os.Stat(sketchInBuildPath); err == nil { + var builtSketchPath *paths.Path + if exist, _ := sketchInBuildPath.Exist(); exist { builtSketchPath = sketchInBuildPath - } else if _, err := os.Stat(sketchInSubfolder); err == nil { + } else if exist, _ := sketchInSubfolder.Exist(); exist { builtSketchPath = sketchInSubfolder } else { return nil @@ -72,17 +74,15 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { } bootloader = buildProperties.ExpandPropsInString(bootloader) - bootloaderPath := filepath.Join(buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH], constants.FOLDER_BOOTLOADERS, bootloader) - if _, err := os.Stat(bootloaderPath); err != nil { + bootloaderPath := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH).Join(constants.FOLDER_BOOTLOADERS, bootloader) + if exist, _ := bootloaderPath.Exist(); !exist { logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_BOOTLOADER_FILE_MISSING, bootloaderPath) return nil } - mergedSketchPath := filepath.Join(filepath.Dir(builtSketchPath), sketchFileName+".with_bootloader.hex") - - err := merge(builtSketchPath, bootloaderPath, mergedSketchPath) + mergedSketchPath := builtSketchPath.Parent().Join(sketchFileName + ".with_bootloader.hex") - return err + return merge(builtSketchPath, bootloaderPath, mergedSketchPath) } func hexLineOnlyContainsFF(line string) bool { @@ -127,14 +127,14 @@ func extractActualBootloader(bootloader []string) []string { return realBootloader } -func merge(builtSketchPath, bootloaderPath, mergedSketchPath string) error { - sketch, err := utils.ReadFileToRows(builtSketchPath) +func merge(builtSketchPath, bootloaderPath, mergedSketchPath *paths.Path) error { + sketch, err := builtSketchPath.ReadFileAsLines() if err != nil { return i18n.WrapError(err) } sketch = sketch[:len(sketch)-2] - bootloader, err := utils.ReadFileToRows(bootloaderPath) + bootloader, err := bootloaderPath.ReadFileAsLines() if err != nil { return i18n.WrapError(err) } @@ -145,5 +145,5 @@ func merge(builtSketchPath, bootloaderPath, mergedSketchPath string) error { sketch = append(sketch, row) } - return utils.WriteFile(mergedSketchPath, strings.Join(sketch, "\n")) + return mergedSketchPath.WriteFile([]byte(strings.Join(sketch, "\n"))) } diff --git a/phases/core_builder.go b/phases/core_builder.go index 75b6535d..b3b22cb0 100644 --- a/phases/core_builder.go +++ b/phases/core_builder.go @@ -30,13 +30,12 @@ package phases import ( - "path/filepath" - "github.com/arduino/arduino-builder/builder_utils" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" ) @@ -50,14 +49,12 @@ func (s *CoreBuilder) Run(ctx *types.Context) error { warningsLevel := ctx.WarningsLevel logger := ctx.GetLogger() - err := utils.EnsureFolderExists(coreBuildPath) - if err != nil { + if err := coreBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - if coreBuildCachePath != "" { - err := utils.EnsureFolderExists(coreBuildCachePath) - if err != nil { + if coreBuildCachePath != nil { + if err := coreBuildCachePath.MkdirAll(); err != nil { return i18n.WrapError(err) } } @@ -73,36 +70,36 @@ func (s *CoreBuilder) Run(ctx *types.Context) error { return nil } -func compileCore(buildPath string, buildCachePath string, buildProperties properties.Map, verbose bool, warningsLevel string, logger i18n.Logger) (string, []string, error) { - coreFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] - variantFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] +func compileCore(buildPath *paths.Path, buildCachePath *paths.Path, buildProperties properties.Map, verbose bool, warningsLevel string, logger i18n.Logger) (*paths.Path, paths.PathList, error) { + coreFolder := paths.New(buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH]) + variantFolder := paths.New(buildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH]) - targetCoreFolder := buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] + targetCoreFolder := paths.New(buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH]) includes := []string{} - includes = append(includes, coreFolder) - if variantFolder != constants.EMPTY_STRING { - includes = append(includes, variantFolder) + includes = append(includes, coreFolder.String()) + if variantFolder != nil { + includes = append(includes, variantFolder.String()) } includes = utils.Map(includes, utils.WrapWithHyphenI) var err error - variantObjectFiles := []string{} - if variantFolder != constants.EMPTY_STRING { - variantObjectFiles, err = builder_utils.CompileFiles(variantObjectFiles, variantFolder, true, buildPath, buildProperties, includes, verbose, warningsLevel, logger) + variantObjectFiles := paths.NewPathList() + if variantFolder != nil { + variantObjectFiles, err = builder_utils.CompileFiles(variantFolder, true, buildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { - return "", nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } } // Recreate the archive if ANY of the core files (including platform.txt) has changed - realCoreFolder := utils.GetParentFolder(coreFolder, 2) + realCoreFolder := coreFolder.Parent().Parent() - var targetArchivedCore string - if buildCachePath != "" { + var targetArchivedCore *paths.Path + if buildCachePath != nil { archivedCoreName := builder_utils.GetCachedCoreArchiveFileName(buildProperties[constants.BUILD_PROPERTIES_FQBN], realCoreFolder) - targetArchivedCore = filepath.Join(buildCachePath, archivedCoreName) + targetArchivedCore = buildCachePath.Join(archivedCoreName) canUseArchivedCore := !builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, targetArchivedCore) if canUseArchivedCore { @@ -114,22 +111,24 @@ func compileCore(buildPath string, buildCachePath string, buildProperties proper } } - coreObjectFiles, err := builder_utils.CompileFiles([]string{}, coreFolder, true, buildPath, buildProperties, includes, verbose, warningsLevel, logger) + coreObjectFiles, err := builder_utils.CompileFiles(coreFolder, true, buildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { - return "", nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } - archiveFile, err := builder_utils.ArchiveCompiledFiles(buildPath, "core.a", coreObjectFiles, buildProperties, verbose, logger) + archiveFile, err := builder_utils.ArchiveCompiledFiles(buildPath, paths.New("core.a"), coreObjectFiles, buildProperties, verbose, logger) if err != nil { - return "", nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } // archive core.a - if targetArchivedCore != "" { + if targetArchivedCore != nil { if verbose { logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_ARCHIVING_CORE_CACHE, targetArchivedCore) } - builder_utils.CopyFile(archiveFile, targetArchivedCore) + if err := archiveFile.CopyTo(targetArchivedCore); err != nil { + return nil, nil, i18n.WrapError(err) + } } return archiveFile, variantObjectFiles, nil diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 5cbce89b..0c43d770 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -38,6 +38,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) @@ -50,15 +51,13 @@ type LibrariesBuilder struct{} func (s *LibrariesBuilder) Run(ctx *types.Context) error { librariesBuildPath := ctx.LibrariesBuildPath buildProperties := ctx.BuildProperties - includes := ctx.IncludeFolders - includes = utils.Map(includes, utils.WrapWithHyphenI) + includes := utils.Map(ctx.IncludeFolders.AsStrings(), utils.WrapWithHyphenI) libraries := ctx.ImportedLibraries verbose := ctx.Verbose warningsLevel := ctx.WarningsLevel logger := ctx.GetLogger() - err := utils.EnsureFolderExists(librariesBuildPath) - if err != nil { + if err := librariesBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } @@ -100,8 +99,8 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*libraries return nil } -func compileLibraries(libraries []*libraries.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { - objectFiles := []string{} +func compileLibraries(libraries []*libraries.Library, buildPath *paths.Path, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { + objectFiles := paths.NewPathList() for _, library := range libraries { libraryObjectFiles, err := compileLibrary(library, buildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { @@ -111,21 +110,19 @@ func compileLibraries(libraries []*libraries.Library, buildPath string, buildPro } return objectFiles, nil - } -func compileLibrary(library *libraries.Library, buildPath string, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) ([]string, error) { +func compileLibrary(library *libraries.Library, buildPath *paths.Path, buildProperties properties.Map, includes []string, verbose bool, warningsLevel string, logger i18n.Logger) (paths.PathList, error) { if verbose { logger.Println(constants.LOG_LEVEL_INFO, "Compiling library \"{0}\"", library.Name) } - libraryBuildPath := filepath.Join(buildPath, library.Name) + libraryBuildPath := buildPath.Join(library.Name) - err := utils.EnsureFolderExists(libraryBuildPath) - if err != nil { + if err := libraryBuildPath.MkdirAll(); err != nil { return nil, i18n.WrapError(err) } - objectFiles := []string{} + objectFiles := paths.NewPathList() if library.Precompiled { // search for files with PRECOMPILED_LIBRARIES_VALID_EXTENSIONS @@ -139,38 +136,42 @@ func compileLibrary(library *libraries.Library, buildPath string, buildPropertie } for _, path := range filePaths { if strings.Contains(filepath.Base(path), library.RealName) { - objectFiles = append(objectFiles, path) + objectFiles.Add(paths.New(path)) } } } if library.Layout == libraries.RecursiveLayout { - objectFiles, err = builder_utils.CompileFilesRecursive(objectFiles, library.SrcFolder.String(), libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + libObjectFiles, err := builder_utils.CompileFilesRecursive(library.SrcFolder, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } if library.DotALinkage { - archiveFile, err := builder_utils.ArchiveCompiledFiles(libraryBuildPath, library.Name+".a", objectFiles, buildProperties, verbose, logger) + archiveFile, err := builder_utils.ArchiveCompiledFiles(libraryBuildPath, paths.New(library.Name+".a"), libObjectFiles, buildProperties, verbose, logger) if err != nil { return nil, i18n.WrapError(err) } - objectFiles = []string{archiveFile} + objectFiles.Add(archiveFile) + } else { + objectFiles.AddAll(libObjectFiles) } } else { if library.UtilityFolder != nil { includes = append(includes, utils.WrapWithHyphenI(library.UtilityFolder.String())) } - objectFiles, err = builder_utils.CompileFiles(objectFiles, library.SrcFolder.String(), false, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + libObjectFiles, err := builder_utils.CompileFiles(library.SrcFolder, false, libraryBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } + objectFiles.AddAll(libObjectFiles) if library.UtilityFolder != nil { - utilityBuildPath := filepath.Join(libraryBuildPath, "utility") - objectFiles, err = builder_utils.CompileFiles(objectFiles, library.UtilityFolder.String(), false, utilityBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + utilityBuildPath := libraryBuildPath.Join("utility") + utilityObjectFiles, err := builder_utils.CompileFiles(library.UtilityFolder, false, utilityBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return nil, i18n.WrapError(err) } + objectFiles.AddAll(utilityObjectFiles) } } diff --git a/phases/linker.go b/phases/linker.go index d35f4993..cc1d2bb0 100644 --- a/phases/linker.go +++ b/phases/linker.go @@ -30,7 +30,6 @@ package phases import ( - "path/filepath" "strings" "github.com/arduino/arduino-builder/builder_utils" @@ -38,6 +37,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" ) @@ -48,14 +48,14 @@ func (s *Linker) Run(ctx *types.Context) error { objectFilesLibraries := ctx.LibrariesObjectFiles objectFilesCore := ctx.CoreObjectsFiles - var objectFiles []string - objectFiles = append(objectFiles, objectFilesSketch...) - objectFiles = append(objectFiles, objectFilesLibraries...) - objectFiles = append(objectFiles, objectFilesCore...) + objectFiles := paths.NewPathList() + objectFiles.AddAll(objectFilesSketch) + objectFiles.AddAll(objectFilesLibraries) + objectFiles.AddAll(objectFilesCore) coreArchiveFilePath := ctx.CoreArchiveFilePath buildPath := ctx.BuildPath - coreDotARelPath, err := filepath.Rel(buildPath, coreArchiveFilePath) + coreDotARelPath, err := buildPath.RelTo(coreArchiveFilePath) if err != nil { return i18n.WrapError(err) } @@ -73,17 +73,17 @@ func (s *Linker) Run(ctx *types.Context) error { return nil } -func link(objectFiles []string, coreDotARelPath string, coreArchiveFilePath string, buildProperties properties.Map, verbose bool, warningsLevel string, logger i18n.Logger) error { +func link(objectFiles paths.PathList, coreDotARelPath *paths.Path, coreArchiveFilePath *paths.Path, buildProperties properties.Map, verbose bool, warningsLevel string, logger i18n.Logger) error { optRelax := addRelaxTrickIfATMEGA2560(buildProperties) - objectFiles = utils.Map(objectFiles, wrapWithDoubleQuotes) - objectFileList := strings.Join(objectFiles, constants.SPACE) + quotedObjectFiles := utils.Map(objectFiles.AsStrings(), wrapWithDoubleQuotes) + objectFileList := strings.Join(quotedObjectFiles, constants.SPACE) properties := buildProperties.Clone() properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] + optRelax properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+warningsLevel] - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = coreDotARelPath - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = coreArchiveFilePath + properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = coreDotARelPath.String() + properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = coreArchiveFilePath.String() properties[constants.BUILD_PROPERTIES_OBJECT_FILES] = objectFileList _, err := builder_utils.ExecRecipe(properties, constants.RECIPE_C_COMBINE_PATTERN, false, verbose, verbose, logger) diff --git a/phases/sketch_builder.go b/phases/sketch_builder.go index 04c7ded7..82d6e8f9 100644 --- a/phases/sketch_builder.go +++ b/phases/sketch_builder.go @@ -35,8 +35,6 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "os" - "path/filepath" ) type SketchBuilder struct{} @@ -44,30 +42,28 @@ type SketchBuilder struct{} func (s *SketchBuilder) Run(ctx *types.Context) error { sketchBuildPath := ctx.SketchBuildPath buildProperties := ctx.BuildProperties - includes := ctx.IncludeFolders - includes = utils.Map(includes, utils.WrapWithHyphenI) + includes := utils.Map(ctx.IncludeFolders.AsStrings(), utils.WrapWithHyphenI) verbose := ctx.Verbose warningsLevel := ctx.WarningsLevel logger := ctx.GetLogger() - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { + if err := sketchBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - var objectFiles []string - objectFiles, err = builder_utils.CompileFiles(objectFiles, sketchBuildPath, false, sketchBuildPath, buildProperties, includes, verbose, warningsLevel, logger) + objectFiles, err := builder_utils.CompileFiles(sketchBuildPath, false, sketchBuildPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return i18n.WrapError(err) } // The "src/" subdirectory of a sketch is compiled recursively - sketchSrcPath := filepath.Join(sketchBuildPath, constants.SKETCH_FOLDER_SRC) - if info, err := os.Stat(sketchSrcPath); err == nil && info.IsDir() { - objectFiles, err = builder_utils.CompileFiles(objectFiles, sketchSrcPath, true, sketchSrcPath, buildProperties, includes, verbose, warningsLevel, logger) + sketchSrcPath := sketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) + if isDir, _ := sketchSrcPath.IsDir(); isDir { + srcObjectFiles, err := builder_utils.CompileFiles(sketchSrcPath, true, sketchSrcPath, buildProperties, includes, verbose, warningsLevel, logger) if err != nil { return i18n.WrapError(err) } + objectFiles.AddAll(srcObjectFiles) } ctx.SketchObjectFiles = objectFiles diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go index 8298c9bf..b3c1e29d 100644 --- a/platform_keys_rewrite_loader.go +++ b/platform_keys_rewrite_loader.go @@ -30,12 +30,12 @@ package builder import ( - "os" - "path/filepath" "sort" "strconv" "strings" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" @@ -52,14 +52,14 @@ func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { if err != nil { return i18n.WrapError(err) } - if platformKeysRewriteTxtPath == constants.EMPTY_STRING { + if platformKeysRewriteTxtPath == nil { return nil } platformKeysRewrite := types.PlatforKeysRewrite{} platformKeysRewrite.Rewrites = []types.PlatforKeyRewrite{} - txt, err := properties.Load(platformKeysRewriteTxtPath) + txt, err := properties.LoadFromPath(platformKeysRewriteTxtPath) if err != nil { return i18n.WrapError(err) } @@ -87,19 +87,17 @@ func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { return nil } -func findPlatformKeysRewriteTxt(folders []string) (string, error) { +func findPlatformKeysRewriteTxt(folders paths.PathList) (*paths.Path, error) { for _, folder := range folders { - txtPath := filepath.Join(folder, constants.FILE_PLATFORM_KEYS_REWRITE_TXT) - _, err := os.Stat(txtPath) - if err == nil { + txtPath := folder.Join(constants.FILE_PLATFORM_KEYS_REWRITE_TXT) + if exist, err := txtPath.Exist(); exist { return txtPath, nil - } - if !os.IsNotExist(err) { - return constants.EMPTY_STRING, i18n.WrapError(err) + } else if err != nil { + return nil, i18n.WrapError(err) } } - return constants.EMPTY_STRING, nil + return nil, nil } func growSliceOfRewrites(originalSlice []types.PlatforKeyRewrite, maxIndex int) []types.PlatforKeyRewrite { diff --git a/read_file_and_store_in_context.go b/read_file_and_store_in_context.go index a2533929..c2eaa07f 100644 --- a/read_file_and_store_in_context.go +++ b/read_file_and_store_in_context.go @@ -32,7 +32,6 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "io/ioutil" ) type ReadFileAndStoreInContext struct { @@ -40,7 +39,7 @@ type ReadFileAndStoreInContext struct { } func (s *ReadFileAndStoreInContext) Run(ctx *types.Context) error { - bytes, err := ioutil.ReadFile(ctx.FileToRead) + bytes, err := ctx.FileToRead.ReadFile() if err != nil { return i18n.WrapError(err) } diff --git a/setup_build_properties.go b/setup_build_properties.go index f965165f..b929e951 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -56,11 +56,11 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties.Merge(targetPlatform.Properties) buildProperties.Merge(targetBoard.Properties) - if ctx.BuildPath != "" { - buildProperties["build.path"] = ctx.BuildPath + if ctx.BuildPath != nil { + buildProperties.SetPath("build.path", ctx.BuildPath) } if ctx.Sketch != nil { - buildProperties["build.project_name"] = filepath.Base(ctx.Sketch.MainFile.Name) + buildProperties["build.project_name"] = ctx.Sketch.MainFile.Name.Base() } buildProperties["build.arch"] = strings.ToUpper(targetPlatform.Platform.Architecture) @@ -102,13 +102,13 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties["software"] = DEFAULT_SOFTWARE } - if ctx.SketchLocation != "" { - sourcePath, err := filepath.Abs(ctx.SketchLocation) + if ctx.SketchLocation != nil { + sourcePath, err := ctx.SketchLocation.Abs() if err != nil { return err } - sourcePath = filepath.Dir(sourcePath) - buildProperties["build.source.path"] = sourcePath + sourcePath = sourcePath.Parent() + buildProperties.SetPath("build.source.path", sourcePath) } now := time.Now() diff --git a/sketch_loader.go b/sketch_loader.go index f8ab8caa..d1c06249 100644 --- a/sketch_loader.go +++ b/sketch_loader.go @@ -30,12 +30,11 @@ package builder import ( - "io/ioutil" - "os" - "path/filepath" "sort" "strings" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" @@ -45,35 +44,35 @@ import ( type SketchLoader struct{} func (s *SketchLoader) Run(ctx *types.Context) error { - if ctx.SketchLocation == "" { + if ctx.SketchLocation == nil { return nil } sketchLocation := ctx.SketchLocation - sketchLocation, err := filepath.Abs(sketchLocation) + sketchLocation, err := sketchLocation.Abs() if err != nil { return i18n.WrapError(err) } - mainSketchStat, err := os.Stat(sketchLocation) + mainSketchStat, err := sketchLocation.Stat() if err != nil { return i18n.WrapError(err) } if mainSketchStat.IsDir() { - sketchLocation = filepath.Join(sketchLocation, mainSketchStat.Name()+".ino") + sketchLocation = sketchLocation.Join(mainSketchStat.Name() + ".ino") } ctx.SketchLocation = sketchLocation - allSketchFilePaths, err := collectAllSketchFiles(filepath.Dir(sketchLocation)) + allSketchFilePaths, err := collectAllSketchFiles(sketchLocation.Parent()) if err != nil { return i18n.WrapError(err) } logger := ctx.GetLogger() - if !utils.SliceContains(allSketchFilePaths, sketchLocation) { - return i18n.ErrorfWithLogger(logger, constants.MSG_CANT_FIND_SKETCH_IN_PATH, sketchLocation, filepath.Dir(sketchLocation)) + if !allSketchFilePaths.Contains(sketchLocation) { + return i18n.ErrorfWithLogger(logger, constants.MSG_CANT_FIND_SKETCH_IN_PATH, sketchLocation, sketchLocation.Parent()) } sketch, err := makeSketch(sketchLocation, allSketchFilePaths, logger) @@ -87,39 +86,39 @@ func (s *SketchLoader) Run(ctx *types.Context) error { return nil } -func collectAllSketchFiles(from string) ([]string, error) { +func collectAllSketchFiles(from *paths.Path) (paths.PathList, error) { filePaths := []string{} // Source files in the root are compiled, non-recursively. This // is the only place where .ino files can be present. rootExtensions := func(ext string) bool { return MAIN_FILE_VALID_EXTENSIONS[ext] || ADDITIONAL_FILE_VALID_EXTENSIONS[ext] } - err := utils.FindFilesInFolder(&filePaths, from, rootExtensions, true /* recurse */) + err := utils.FindFilesInFolder(&filePaths, from.String(), rootExtensions, true /* recurse */) if err != nil { return nil, i18n.WrapError(err) } - return filePaths, i18n.WrapError(err) + return paths.NewPathList(filePaths...), i18n.WrapError(err) } -func makeSketch(sketchLocation string, allSketchFilePaths []string, logger i18n.Logger) (*types.Sketch, error) { +func makeSketch(sketchLocation *paths.Path, allSketchFilePaths paths.PathList, logger i18n.Logger) (*types.Sketch, error) { sketchFilesMap := make(map[string]types.SketchFile) for _, sketchFilePath := range allSketchFilePaths { - source, err := ioutil.ReadFile(sketchFilePath) + source, err := sketchFilePath.ReadFile() if err != nil { return nil, i18n.WrapError(err) } - sketchFilesMap[sketchFilePath] = types.SketchFile{Name: sketchFilePath, Source: string(source)} + sketchFilesMap[sketchFilePath.String()] = types.SketchFile{Name: sketchFilePath, Source: string(source)} } - mainFile := sketchFilesMap[sketchLocation] - delete(sketchFilesMap, sketchLocation) + mainFile := sketchFilesMap[sketchLocation.String()] + delete(sketchFilesMap, sketchLocation.String()) additionalFiles := []types.SketchFile{} otherSketchFiles := []types.SketchFile{} - mainFileDir := filepath.Dir(mainFile.Name) + mainFileDir := mainFile.Name.Parent() for _, sketchFile := range sketchFilesMap { - ext := strings.ToLower(filepath.Ext(sketchFile.Name)) + ext := strings.ToLower(sketchFile.Name.Ext()) if MAIN_FILE_VALID_EXTENSIONS[ext] { - if filepath.Dir(sketchFile.Name) == mainFileDir { + if sketchFile.Name.Parent().EqualsTo(mainFileDir) { otherSketchFiles = append(otherSketchFiles, sketchFile) } } else if ADDITIONAL_FILE_VALID_EXTENSIONS[ext] { diff --git a/sketch_saver.go b/sketch_saver.go index b377e872..a4dd3785 100644 --- a/sketch_saver.go +++ b/sketch_saver.go @@ -32,8 +32,6 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" ) type SketchSaver struct{} @@ -42,11 +40,10 @@ func (s *SketchSaver) Run(ctx *types.Context) error { sketch := ctx.Sketch sketchBuildPath := ctx.SketchBuildPath - err := utils.EnsureFolderExists(sketchBuildPath) - if err != nil { + if err := sketchBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - err = utils.WriteFile(filepath.Join(sketchBuildPath, filepath.Base(sketch.MainFile.Name)+".cpp"), ctx.Source) + err := sketchBuildPath.Join(sketch.MainFile.Name.Base() + ".cpp").WriteFile([]byte(ctx.Source)) return i18n.WrapError(err) } diff --git a/sketch_source_merger.go b/sketch_source_merger.go index bbfaad0d..a4166fb9 100644 --- a/sketch_source_merger.go +++ b/sketch_source_merger.go @@ -31,9 +31,10 @@ package builder import ( + "regexp" + "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "regexp" ) type SketchSourceMerger struct{} @@ -47,7 +48,7 @@ func (s *SketchSourceMerger) Run(ctx *types.Context) error { includeSection += "#include \n" lineOffset++ } - includeSection += "#line 1 " + utils.QuoteCppString(sketch.MainFile.Name) + "\n" + includeSection += "#line 1 " + utils.QuoteCppString(sketch.MainFile.Name.String()) + "\n" lineOffset++ ctx.IncludeSection = includeSection @@ -73,7 +74,7 @@ func sketchIncludesArduinoH(sketch *types.SketchFile) bool { } func addSourceWrappedWithLineDirective(sketch *types.SketchFile) string { - source := "#line 1 " + utils.QuoteCppString(sketch.Name) + "\n" + source := "#line 1 " + utils.QuoteCppString(sketch.Name.String()) + "\n" source += sketch.Source source += "\n" diff --git a/store_build_options_map.go b/store_build_options_map.go index dc0c3220..6cb6d71c 100644 --- a/store_build_options_map.go +++ b/store_build_options_map.go @@ -32,13 +32,11 @@ package builder import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "path/filepath" ) type StoreBuildOptionsMap struct{} func (s *StoreBuildOptionsMap) Run(ctx *types.Context) error { - utils.WriteFile(filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE), ctx.BuildOptionsJson) + ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE).WriteFile([]byte(ctx.BuildOptionsJson)) return nil } diff --git a/test/add_additional_entries_to_context_test.go b/test/add_additional_entries_to_context_test.go index ca7bb0e1..ee904b78 100644 --- a/test/add_additional_entries_to_context_test.go +++ b/test/add_additional_entries_to_context_test.go @@ -30,12 +30,12 @@ package test import ( - "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -59,15 +59,15 @@ func TestAddAdditionalEntriesToContextNoBuildPath(t *testing.T) { func TestAddAdditionalEntriesToContextWithBuildPath(t *testing.T) { ctx := &types.Context{} - ctx.BuildPath = "folder" + ctx.BuildPath = paths.New("folder") command := builder.AddAdditionalEntriesToContext{} NoError(t, command.Run(ctx)) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_PREPROC)), ctx.PreprocPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_SKETCH)), ctx.SketchBuildPath) - require.Equal(t, Abs(t, filepath.Join("folder", "libraries")), ctx.LibrariesBuildPath) - require.Equal(t, Abs(t, filepath.Join("folder", constants.FOLDER_CORE)), ctx.CoreBuildPath) + require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_PREPROC)), ctx.PreprocPath) + require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_SKETCH)), ctx.SketchBuildPath) + require.Equal(t, Abs(t, paths.New("folder", "libraries")), ctx.LibrariesBuildPath) + require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_CORE)), ctx.CoreBuildPath) require.NotNil(t, ctx.WarningsLevel) diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index e6cfb680..9fa49e45 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -33,6 +33,8 @@ import ( "path/filepath" "testing" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" @@ -43,7 +45,7 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), FQBN: "my_avr_platform:avr:mymega", } @@ -74,7 +76,7 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", } diff --git a/test/additional_sketch_files_copier_test.go b/test/additional_sketch_files_copier_test.go index 1a138fd0..c6a901ab 100644 --- a/test/additional_sketch_files_copier_test.go +++ b/test/additional_sketch_files_copier_test.go @@ -30,16 +30,17 @@ package test import ( + "os" + "sort" + "testing" + "time" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "os" - "path/filepath" - "sort" - "testing" - "time" ) type ByFileInfoName []os.FileInfo @@ -56,11 +57,11 @@ func (s ByFileInfoName) Less(i, j int) bool { func TestCopyOtherFiles(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + SketchLocation: paths.New("sketch1", "sketch.ino"), } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, @@ -73,10 +74,11 @@ func TestCopyOtherFiles(t *testing.T) { NoError(t, err) } - _, err1 := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) + exist, err1 := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Exist() NoError(t, err1) + require.True(t, exist) - files, err1 := gohasissues.ReadDir(filepath.Join(buildPath, constants.FOLDER_SKETCH)) + files, err1 := gohasissues.ReadDir(buildPath.Join(constants.FOLDER_SKETCH).String()) NoError(t, err1) require.Equal(t, 3, len(files)) @@ -85,7 +87,7 @@ func TestCopyOtherFiles(t *testing.T) { require.Equal(t, "s_file.S", files[1].Name()) require.Equal(t, "src", files[2].Name()) - files, err1 = gohasissues.ReadDir(filepath.Join(buildPath, constants.FOLDER_SKETCH, "src")) + files, err1 = gohasissues.ReadDir(buildPath.Join(constants.FOLDER_SKETCH, "src").String()) NoError(t, err1) require.Equal(t, 1, len(files)) require.Equal(t, "helper.h", files[0].Name()) @@ -93,11 +95,11 @@ func TestCopyOtherFiles(t *testing.T) { func TestCopyOtherFilesOnlyIfChanged(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + SketchLocation: paths.New("sketch1", "sketch.ino"), } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, @@ -110,13 +112,13 @@ func TestCopyOtherFilesOnlyIfChanged(t *testing.T) { NoError(t, err) } - headerStatBefore, err := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) + headerStatBefore, err := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Stat() NoError(t, err) time.Sleep(2 * time.Second) ctx = &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + SketchLocation: paths.New("sketch1", "sketch.ino"), BuildPath: buildPath, } @@ -125,7 +127,7 @@ func TestCopyOtherFilesOnlyIfChanged(t *testing.T) { NoError(t, err) } - headerStatAfter, err := os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "header.h")) + headerStatAfter, err := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Stat() NoError(t, err) require.Equal(t, headerStatBefore.ModTime().Unix(), headerStatAfter.ModTime().Unix()) diff --git a/test/builder_test.go b/test/builder_test.go index 3b36c104..f40600ae 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -30,12 +30,13 @@ package test import ( - "os" "os/exec" "path/filepath" "testing" "time" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/builder_utils" "github.com/arduino/arduino-builder/constants" @@ -43,14 +44,14 @@ import ( "github.com/stretchr/testify/require" ) -func prepareBuilderTestContext(sketchPath, fqbn string) *types.Context { +func prepareBuilderTestContext(sketchPath *paths.Path, fqbn string) *types.Context { return &types.Context{ SketchLocation: sketchPath, FQBN: fqbn, - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), ArduinoAPIVersion: "10600", Verbose: false, } @@ -59,90 +60,107 @@ func prepareBuilderTestContext(sketchPath, fqbn string) *types.Context { func TestBuilderEmptySketch(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") ctx.DebugLevel = 10 buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "sketch.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("sketch.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.hex")) + require.True(t, exist) + exist, err = buildPath.Join("sketch.ino.hex").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderBridge(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.hex").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderSketchWithConfig(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(paths.New("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch_with_config.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("sketch_with_config.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch_with_config.ino.hex")) + require.True(t, exist) + exist, err = buildPath.Join("sketch_with_config.ino.hex").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderBridgeTwice(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} @@ -154,52 +172,66 @@ func TestBuilderBridgeTwice(t *testing.T) { err = command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.hex").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderBridgeSAM(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") + ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") ctx.WarningsLevel = "all" buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "syscalls_sam3.c.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "syscalls_sam3.c.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "avr", "dtostrf.c.d")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_CORE, "avr", "dtostrf.c.d").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.bin")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.bin").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() NoError(t, err) + require.True(t, exist) - cmd := exec.Command(filepath.Join("downloaded_tools", "arm-none-eabi-gcc", "4.8.3-2014q1", "bin", "arm-none-eabi-objdump"), "-f", filepath.Join(buildPath, constants.FOLDER_CORE, "core.a")) + cmd := exec.Command(filepath.Join("downloaded_tools", "arm-none-eabi-gcc", "4.8.3-2014q1", "bin", "arm-none-eabi-objdump"), "-f", buildPath.Join(constants.FOLDER_CORE, "core.a").String()) bytes, err := cmd.CombinedOutput() NoError(t, err) require.NotContains(t, string(bytes), "variant.cpp.o") @@ -208,41 +240,47 @@ func TestBuilderBridgeSAM(t *testing.T) { func TestBuilderBridgeRedBearLab(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") + ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") + ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_CORE, "HardwareSerial.cpp.o")) + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E)) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, constants.FOLDER_SKETCH, "Bridge.ino.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.elf")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.elf").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "Bridge.ino.hex")) + require.True(t, exist) + exist, err = buildPath.Join("Bridge.ino.hex").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge", "Mailbox.cpp.o")) + require.True(t, exist) + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderSketchNoFunctions(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") + ctx := prepareBuilderTestContext(paths.New("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") + ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} @@ -253,12 +291,12 @@ func TestBuilderSketchNoFunctions(t *testing.T) { func TestBuilderSketchWithBackup(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") - ctx.HardwareFolders = append(ctx.HardwareFolders, "downloaded_board_manager_stuff") - ctx.ToolsFolders = append(ctx.ToolsFolders, "downloaded_board_manager_stuff") + ctx := prepareBuilderTestContext(paths.New("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") + ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} @@ -269,10 +307,10 @@ func TestBuilderSketchWithBackup(t *testing.T) { func TestBuilderSketchWithOldLib(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(paths.New("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} @@ -283,10 +321,10 @@ func TestBuilderSketchWithOldLib(t *testing.T) { func TestBuilderSketchWithSubfolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() // Run builder command := builder.Builder{} @@ -297,34 +335,35 @@ func TestBuilderSketchWithSubfolders(t *testing.T) { func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - NoError(t, os.MkdirAll(filepath.Join(buildPath, "libraries", "SPI"), os.FileMode(0755))) + NoError(t, buildPath.Join("libraries", "SPI").MkdirAll()) // Run builder command := builder.Builder{} err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(buildPath, "libraries", "Bridge")) + exist, err := buildPath.Join("libraries", "SPI").Exist() + NoError(t, err) + require.False(t, exist) + exist, err = buildPath.Join("libraries", "Bridge").Exist() NoError(t, err) + require.True(t, exist) } func TestBuilderWithBuildPathInSketchDir(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") var err error - ctx.BuildPath, err = filepath.Abs(filepath.Join("sketch1", "build")) + ctx.BuildPath, err = paths.New("sketch1", "build").Abs() NoError(t, err) - defer os.RemoveAll(ctx.BuildPath) + defer ctx.BuildPath.RemoveAll() // Run build command := builder.Builder{} @@ -340,12 +379,12 @@ func TestBuilderWithBuildPathInSketchDir(t *testing.T) { func TestBuilderCacheCoreAFile(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(filepath.Join("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") SetupBuildPath(t, ctx) - defer os.RemoveAll(ctx.BuildPath) + defer ctx.BuildPath.RemoveAll() SetupBuildCachePath(t, ctx) - defer os.RemoveAll(ctx.BuildCachePath) + defer ctx.BuildCachePath.RemoveAll() // Run build bldr := builder.Builder{} @@ -353,31 +392,31 @@ func TestBuilderCacheCoreAFile(t *testing.T) { NoError(t, err) // Pick timestamp of cached core - coreFolder := filepath.Join("downloaded_hardware", "arduino", "avr") + coreFolder := paths.New("downloaded_hardware", "arduino", "avr") coreFileName := builder_utils.GetCachedCoreArchiveFileName(ctx.FQBN, coreFolder) - cachedCoreFile := filepath.Join(ctx.CoreBuildCachePath, coreFileName) - coreStatBefore, err := os.Stat(cachedCoreFile) + cachedCoreFile := ctx.CoreBuildCachePath.Join(coreFileName) + coreStatBefore, err := cachedCoreFile.Stat() require.NoError(t, err) // Run build again, to verify that the builder skips rebuilding core.a err = bldr.Run(ctx) NoError(t, err) - coreStatAfterRebuild, err := os.Stat(cachedCoreFile) + coreStatAfterRebuild, err := cachedCoreFile.Stat() require.NoError(t, err) require.Equal(t, coreStatBefore.ModTime(), coreStatAfterRebuild.ModTime()) // Touch a file of the core and check if the builder invalidate the cache time.Sleep(time.Second) now := time.Now().Local() - err = os.Chtimes(filepath.Join(coreFolder, "cores", "arduino", "Arduino.h"), now, now) + err = coreFolder.Join("cores", "arduino", "Arduino.h").Chtimes(now, now) require.NoError(t, err) // Run build again, to verify that the builder rebuilds core.a err = bldr.Run(ctx) NoError(t, err) - coreStatAfterTouch, err := os.Stat(cachedCoreFile) + coreStatAfterTouch, err := cachedCoreFile.Stat() require.NoError(t, err) require.NotEqual(t, coreStatBefore.ModTime(), coreStatAfterTouch.ModTime()) } diff --git a/test/builder_utils_test.go b/test/builder_utils_test.go index c6fc941c..e0f2c228 100644 --- a/test/builder_utils_test.go +++ b/test/builder_utils_test.go @@ -30,13 +30,13 @@ package test import ( - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" "io/ioutil" - "os" "testing" "time" + + "github.com/arduino/arduino-builder/builder_utils" + paths "github.com/arduino/go-paths-helper" + "github.com/stretchr/testify/require" ) func sleep(t *testing.T) { @@ -45,43 +45,44 @@ func sleep(t *testing.T) { time.Sleep(dur) } -func tempFile(t *testing.T, prefix string) string { +func tempFile(t *testing.T, prefix string) *paths.Path { file, err := ioutil.TempFile("", prefix) + file.Close() NoError(t, err) - return file.Name() + return paths.New(file.Name()) } func TestObjFileIsUpToDateObjMissing(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() - upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, "", "") + upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, nil, nil) NoError(t, err) require.False(t, upToDate) } func TestObjFileIsUpToDateDepMissing(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() - upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, "") + upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, nil) NoError(t, err) require.False(t, upToDate) } func TestObjFileIsUpToDateObjOlder(t *testing.T) { objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) + defer depFile.RemoveAll() sleep(t) sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, depFile) NoError(t, err) @@ -90,14 +91,14 @@ func TestObjFileIsUpToDateObjOlder(t *testing.T) { func TestObjFileIsUpToDateObjNewer(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() sleep(t) objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) + defer depFile.RemoveAll() upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, depFile) NoError(t, err) @@ -106,21 +107,22 @@ func TestObjFileIsUpToDateObjNewer(t *testing.T) { func TestObjFileIsUpToDateDepIsNewer(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() sleep(t) objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) + defer depFile.RemoveAll() sleep(t) headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) + defer headerFile.RemoveAll() - utils.WriteFile(depFile, objFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) + data := objFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() + depFile.WriteFile([]byte(data)) upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, depFile) NoError(t, err) @@ -129,19 +131,20 @@ func TestObjFileIsUpToDateDepIsNewer(t *testing.T) { func TestObjFileIsUpToDateDepIsOlder(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) + defer headerFile.RemoveAll() sleep(t) objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) + defer depFile.RemoveAll() - utils.WriteFile(depFile, objFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) + res := objFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() + depFile.WriteFile([]byte(res)) upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, depFile) NoError(t, err) @@ -150,21 +153,22 @@ func TestObjFileIsUpToDateDepIsOlder(t *testing.T) { func TestObjFileIsUpToDateDepIsWrong(t *testing.T) { sourceFile := tempFile(t, "source") - defer os.RemoveAll(sourceFile) + defer sourceFile.RemoveAll() sleep(t) objFile := tempFile(t, "obj") - defer os.RemoveAll(objFile) + defer objFile.RemoveAll() depFile := tempFile(t, "dep") - defer os.RemoveAll(depFile) + defer depFile.RemoveAll() sleep(t) headerFile := tempFile(t, "header") - defer os.RemoveAll(headerFile) + defer headerFile.RemoveAll() - utils.WriteFile(depFile, sourceFile+": \\\n\t"+sourceFile+" \\\n\t"+headerFile) + res := sourceFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() + depFile.WriteFile([]byte(res)) upToDate, err := builder_utils.ObjFileIsUpToDate(sourceFile, objFile, depFile) NoError(t, err) diff --git a/test/create_build_options_map_test.go b/test/create_build_options_map_test.go index dce062e8..81380d46 100644 --- a/test/create_build_options_map_test.go +++ b/test/create_build_options_map_test.go @@ -30,22 +30,24 @@ package test import ( + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "testing" ) func TestCreateBuildOptionsMap(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"hardware", "hardware2"}, - ToolsFolders: []string{"tools"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: "sketchLocation", + HardwareFolders: paths.NewPathList("hardware", "hardware2"), + ToolsFolders: paths.NewPathList("tools"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketchLocation"), FQBN: "fqbn", ArduinoAPIVersion: "ideVersion", Verbose: true, - BuildPath: "buildPath", + BuildPath: paths.New("buildPath"), DebugLevel: 5, } diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go index c5d6e6b5..8a6703ce 100644 --- a/test/ctags_runner_test.go +++ b/test/ctags_runner_test.go @@ -30,26 +30,26 @@ package test import ( - "os" "path/filepath" "strings" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestCTagsRunner(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := Abs(t, filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino")) + sketchLocation := Abs(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino")) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -57,7 +57,7 @@ func TestCTagsRunner(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -78,14 +78,14 @@ func TestCTagsRunner(t *testing.T) { NoError(t, err) } - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "server " + sketchLocation + " /^BridgeServer server;$/;\" kind:variable line:31\n" + - "setup " + sketchLocation + " /^void setup() {$/;\" kind:function line:33 signature:() returntype:void\n" + - "loop " + sketchLocation + " /^void loop() {$/;\" kind:function line:46 signature:() returntype:void\n" + - "process " + sketchLocation + " /^void process(BridgeClient client) {$/;\" kind:function line:62 signature:(BridgeClient client) returntype:void\n" + - "digitalCommand " + sketchLocation + " /^void digitalCommand(BridgeClient client) {$/;\" kind:function line:82 signature:(BridgeClient client) returntype:void\n" + - "analogCommand " + sketchLocation + " /^void analogCommand(BridgeClient client) {$/;\" kind:function line:109 signature:(BridgeClient client) returntype:void\n" + - "modeCommand " + sketchLocation + " /^void modeCommand(BridgeClient client) {$/;\" kind:function line:149 signature:(BridgeClient client) returntype:void\n" + quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) + expectedOutput := "server " + quotedSketchLocation + " /^BridgeServer server;$/;\" kind:variable line:31\n" + + "setup " + quotedSketchLocation + " /^void setup() {$/;\" kind:function line:33 signature:() returntype:void\n" + + "loop " + quotedSketchLocation + " /^void loop() {$/;\" kind:function line:46 signature:() returntype:void\n" + + "process " + quotedSketchLocation + " /^void process(BridgeClient client) {$/;\" kind:function line:62 signature:(BridgeClient client) returntype:void\n" + + "digitalCommand " + quotedSketchLocation + " /^void digitalCommand(BridgeClient client) {$/;\" kind:function line:82 signature:(BridgeClient client) returntype:void\n" + + "analogCommand " + quotedSketchLocation + " /^void analogCommand(BridgeClient client) {$/;\" kind:function line:109 signature:(BridgeClient client) returntype:void\n" + + "modeCommand " + quotedSketchLocation + " /^void modeCommand(BridgeClient client) {$/;\" kind:function line:149 signature:(BridgeClient client) returntype:void\n" require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) } @@ -93,13 +93,13 @@ func TestCTagsRunner(t *testing.T) { func TestCTagsRunnerSketchWithClass(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := Abs(t, filepath.Join("sketch_with_class", "sketch.ino")) + sketchLocation := Abs(t, paths.New("sketch_with_class", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -107,7 +107,7 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -128,12 +128,12 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { NoError(t, err) } - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "set_values\t" + sketchLocation + "\t/^ void set_values (int,int);$/;\"\tkind:prototype\tline:4\tclass:Rectangle\tsignature:(int,int)\treturntype:void\n" + - "area\t" + sketchLocation + "\t/^ int area() {return width*height;}$/;\"\tkind:function\tline:5\tclass:Rectangle\tsignature:()\treturntype:int\n" + - "set_values\t" + sketchLocation + "\t/^void Rectangle::set_values (int x, int y) {$/;\"\tkind:function\tline:8\tclass:Rectangle\tsignature:(int x, int y)\treturntype:void\n" + - "setup\t" + sketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:13\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {$/;\"\tkind:function\tline:17\tsignature:()\treturntype:void\n" + quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) + expectedOutput := "set_values\t" + quotedSketchLocation + "\t/^ void set_values (int,int);$/;\"\tkind:prototype\tline:4\tclass:Rectangle\tsignature:(int,int)\treturntype:void\n" + + "area\t" + quotedSketchLocation + "\t/^ int area() {return width*height;}$/;\"\tkind:function\tline:5\tclass:Rectangle\tsignature:()\treturntype:int\n" + + "set_values\t" + quotedSketchLocation + "\t/^void Rectangle::set_values (int x, int y) {$/;\"\tkind:function\tline:8\tclass:Rectangle\tsignature:(int x, int y)\treturntype:void\n" + + "setup\t" + quotedSketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:13\tsignature:()\treturntype:void\n" + + "loop\t" + quotedSketchLocation + "\t/^void loop() {$/;\"\tkind:function\tline:17\tsignature:()\treturntype:void\n" require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) } @@ -141,13 +141,13 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { func TestCTagsRunnerSketchWithTypename(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := Abs(t, filepath.Join("sketch_with_typename", "sketch.ino")) + sketchLocation := Abs(t, paths.New("sketch_with_typename", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -155,7 +155,7 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -176,11 +176,11 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { NoError(t, err) } - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "Foo\t" + sketchLocation + "\t/^ struct Foo{$/;\"\tkind:struct\tline:2\n" + - "setup\t" + sketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:6\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "func\t" + sketchLocation + "\t/^typename Foo::Bar func(){$/;\"\tkind:function\tline:12\tsignature:()\treturntype:Foo::Bar\n" + quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) + expectedOutput := "Foo\t" + quotedSketchLocation + "\t/^ struct Foo{$/;\"\tkind:struct\tline:2\n" + + "setup\t" + quotedSketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:6\tsignature:()\treturntype:void\n" + + "loop\t" + quotedSketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + + "func\t" + quotedSketchLocation + "\t/^typename Foo::Bar func(){$/;\"\tkind:function\tline:12\tsignature:()\treturntype:Foo::Bar\n" require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) } @@ -188,13 +188,13 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { func TestCTagsRunnerSketchWithNamespace(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := Abs(t, filepath.Join("sketch_with_namespace", "sketch.ino")) + sketchLocation := Abs(t, paths.New("sketch_with_namespace", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -202,7 +202,7 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -223,10 +223,10 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { NoError(t, err) } - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "value\t" + sketchLocation + "\t/^\tint value() {$/;\"\tkind:function\tline:2\tnamespace:Test\tsignature:()\treturntype:int\n" + - "setup\t" + sketchLocation + "\t/^void setup() {}$/;\"\tkind:function\tline:7\tsignature:()\treturntype:void\n" + - "loop\t" + sketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:8\tsignature:()\treturntype:void\n" + quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) + expectedOutput := "value\t" + quotedSketchLocation + "\t/^\tint value() {$/;\"\tkind:function\tline:2\tnamespace:Test\tsignature:()\treturntype:int\n" + + "setup\t" + quotedSketchLocation + "\t/^void setup() {}$/;\"\tkind:function\tline:7\tsignature:()\treturntype:void\n" + + "loop\t" + quotedSketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:8\tsignature:()\treturntype:void\n" require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) } @@ -234,13 +234,13 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { func TestCTagsRunnerSketchWithTemplates(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := Abs(t, filepath.Join("sketch_with_templates_and_shift", "template_and_shift.cpp")) + sketchLocation := Abs(t, paths.New("sketch_with_templates_and_shift", "template_and_shift.cpp")) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -248,7 +248,7 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -269,11 +269,11 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { NoError(t, err) } - sketchLocation = strings.Replace(sketchLocation, "\\", "\\\\", -1) - expectedOutput := "printGyro\t" + sketchLocation + "\t/^void printGyro()$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "bVar\t" + sketchLocation + "\t/^c< 8 > bVar;$/;\"\tkind:variable\tline:15\n" + - "aVar\t" + sketchLocation + "\t/^c< 1<<8 > aVar;$/;\"\tkind:variable\tline:16\n" + - "func\t" + sketchLocation + "\t/^template func( c< 1< & aParam) {$/;\"\tkind:function\tline:18\tsignature:( c< 1< & aParam)\treturntype:template\n" + quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) + expectedOutput := "printGyro\t" + quotedSketchLocation + "\t/^void printGyro()$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + + "bVar\t" + quotedSketchLocation + "\t/^c< 8 > bVar;$/;\"\tkind:variable\tline:15\n" + + "aVar\t" + quotedSketchLocation + "\t/^c< 1<<8 > aVar;$/;\"\tkind:variable\tline:16\n" + + "func\t" + quotedSketchLocation + "\t/^template func( c< 1< & aParam) {$/;\"\tkind:function\tline:18\tsignature:( c< 1< & aParam)\treturntype:template\n" require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) } diff --git a/test/fail_if_buildpath_equals_sketchpath_test.go b/test/fail_if_buildpath_equals_sketchpath_test.go index b29dc361..0e7ddc3f 100644 --- a/test/fail_if_buildpath_equals_sketchpath_test.go +++ b/test/fail_if_buildpath_equals_sketchpath_test.go @@ -30,16 +30,18 @@ package test import ( + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "testing" ) func TestFailIfBuildPathEqualsSketchPath(t *testing.T) { ctx := &types.Context{ - SketchLocation: "buildPath/sketch.ino", - BuildPath: "buildPath", + SketchLocation: paths.New("buildPath/sketch.ino"), + BuildPath: paths.New("buildPath"), } command := builder.FailIfBuildPathEqualsSketchPath{} @@ -48,8 +50,8 @@ func TestFailIfBuildPathEqualsSketchPath(t *testing.T) { func TestFailIfBuildPathEqualsSketchPathSketchPathDiffers(t *testing.T) { ctx := &types.Context{ - SketchLocation: "sketchPath/sketch.ino", - BuildPath: "buildPath", + SketchLocation: paths.New("sketchPath/sketch.ino"), + BuildPath: paths.New("buildPath"), } command := builder.FailIfBuildPathEqualsSketchPath{} diff --git a/test/generate_buildpath_if_missing_test.go b/test/generate_buildpath_if_missing_test.go index 05d17e22..03f5aff8 100644 --- a/test/generate_buildpath_if_missing_test.go +++ b/test/generate_buildpath_if_missing_test.go @@ -30,56 +30,58 @@ package test import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" "os" "path/filepath" "testing" + + "github.com/arduino/arduino-builder" + "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" + "github.com/stretchr/testify/require" ) func TestGenerateBuildPathIfMissing(t *testing.T) { ctx := &types.Context{ - SketchLocation: "test", + SketchLocation: paths.New("test"), } command := builder.GenerateBuildPathIfMissing{} err := command.Run(ctx) NoError(t, err) - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) + require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) require.True(t, os.IsNotExist(err)) } func TestGenerateBuildPathIfEmpty(t *testing.T) { ctx := &types.Context{ - SketchLocation: "test", + SketchLocation: paths.New("test"), } createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} err := createBuildPathIfMissing.Run(ctx) NoError(t, err) - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) + require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) require.True(t, os.IsNotExist(err)) } func TestDontGenerateBuildPathIfPresent(t *testing.T) { ctx := &types.Context{} - ctx.BuildPath = "test" + ctx.BuildPath = paths.New("test") createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} err := createBuildPathIfMissing.Run(ctx) NoError(t, err) - require.Equal(t, "test", ctx.BuildPath) + require.Equal(t, ctx.BuildPath.String(), "test") } func TestGenerateBuildPathAndEnsureItExists(t *testing.T) { ctx := &types.Context{ - SketchLocation: "test", + SketchLocation: paths.New("test"), } commands := []types.Command{ @@ -94,7 +96,7 @@ func TestGenerateBuildPathAndEnsureItExists(t *testing.T) { defer os.RemoveAll(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath) + require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) _, err := os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) NoError(t, err) } diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index a3e31ac7..31b550d3 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -37,12 +37,13 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestLoadHardware(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware"}, + HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), } commands := []types.Command{ @@ -86,7 +87,7 @@ func TestLoadHardware(t *testing.T) { func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), } commands := []types.Command{ @@ -156,7 +157,7 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff"}, + HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), } commands := []types.Command{ @@ -204,7 +205,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { func TestLoadLotsOfHardware(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), } commands := []types.Command{ diff --git a/test/helper.go b/test/helper.go index 72e21589..ba8b6014 100644 --- a/test/helper.go +++ b/test/helper.go @@ -33,7 +33,6 @@ package test import ( "bytes" "fmt" - "io/ioutil" "path/filepath" "testing" "text/template" @@ -41,6 +40,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/go-errors/errors" "github.com/stretchr/testify/assert" @@ -48,7 +48,7 @@ import ( func LoadAndInterpolate(t *testing.T, filename string, ctx *types.Context) string { funcsMap := template.FuncMap{ - "QuoteCppString": utils.QuoteCppString, + "QuoteCppString": utils.QuoteCppPath, } tpl, err := template.New(filepath.Base(filename)).Funcs(funcsMap).ParseFiles(filename) @@ -63,10 +63,10 @@ func LoadAndInterpolate(t *testing.T, filename string, ctx *types.Context) strin return buf.String() } -func Abs(t *testing.T, rel string) string { - toolPath, err := filepath.Abs(rel) +func Abs(t *testing.T, rel *paths.Path) *paths.Path { + absPath, err := rel.Abs() NoError(t, err) - return toolPath + return absPath } func NoError(t *testing.T, err error, msgAndArgs ...interface{}) { @@ -79,15 +79,15 @@ func NoError(t *testing.T, err error, msgAndArgs ...interface{}) { } } -func SetupBuildPath(t *testing.T, ctx *types.Context) string { - buildPath, err := ioutil.TempDir(constants.EMPTY_STRING, "test_build_path") +func SetupBuildPath(t *testing.T, ctx *types.Context) *paths.Path { + buildPath, err := paths.MkTempDir("", "test_build_path") NoError(t, err) ctx.BuildPath = buildPath return buildPath } -func SetupBuildCachePath(t *testing.T, ctx *types.Context) string { - buildCachePath, err := ioutil.TempDir(constants.EMPTY_STRING, "test_build_cache") +func SetupBuildCachePath(t *testing.T, ctx *types.Context) *paths.Path { + buildCachePath, err := paths.MkTempDir(constants.EMPTY_STRING, "test_build_cache") NoError(t, err) ctx.BuildCachePath = buildCachePath return buildCachePath diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index cfce881c..5bd1d13c 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -42,6 +42,8 @@ import ( "strings" "testing" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" @@ -50,11 +52,11 @@ import ( "github.com/go-errors/errors" ) -const HARDWARE_FOLDER = "downloaded_hardware" -const BOARD_MANAGER_FOLDER = "downloaded_board_manager_stuff" -const TOOLS_FOLDER = "downloaded_tools" -const LIBRARIES_FOLDER = "downloaded_libraries" -const PATCHES_FOLDER = "downloaded_stuff_patches" +var hardwareFolder = paths.New("downloaded_hardware") +var boardManagerFolder = paths.New("downloaded_board_manager_stuff") +var toolsFolder = paths.New("downloaded_tools") +var librariesFolder = paths.New("downloaded_libraries") +var patchesFolder = paths.New("downloaded_stuff_patches") type Tool struct { Name string @@ -140,13 +142,13 @@ func DownloadCoresAndToolsAndLibraries(t *testing.T) { } func patchFiles(t *testing.T) { - err := utils.EnsureFolderExists(PATCHES_FOLDER) + err := patchesFolder.MkdirAll() NoError(t, err) - files, err := ioutil.ReadDir(PATCHES_FOLDER) + files, err := patchesFolder.ReadDir() NoError(t, err) for _, file := range files { - if filepath.Ext(file.Name()) == ".patch" { + if file.Ext() == ".patch" { panic("Patching for downloaded tools is not available! (see https://github.com/arduino/arduino-builder/issues/147)") // XXX: find an alternative to x/codereview/patch // https://github.com/arduino/arduino-builder/issues/147 @@ -165,16 +167,16 @@ func patchFiles(t *testing.T) { } func download(t *testing.T, cores, boardsManagerCores, boardsManagerRedBearCores []Core, tools, toolsMultipleVersions, boardsManagerTools, boardsManagerRFduinoTools []Tool, libraries []Library) { - allCoresDownloaded, err := allCoresAlreadyDownloadedAndUnpacked(HARDWARE_FOLDER, cores) + allCoresDownloaded, err := allCoresAlreadyDownloadedAndUnpacked(hardwareFolder, cores) NoError(t, err) if allCoresDownloaded && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerCores) && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerRedBearCores) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerTools) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(BOARD_MANAGER_FOLDER, boardsManagerRFduinoTools) && - allToolsAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, tools) && - allToolsAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, toolsMultipleVersions) && - allLibrariesAlreadyDownloadedAndUnpacked(LIBRARIES_FOLDER, libraries) { + allBoardsManagerCoresAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerCores) && + allBoardsManagerCoresAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerRedBearCores) && + allBoardsManagerToolsAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerTools) && + allBoardsManagerToolsAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerRFduinoTools) && + allToolsAlreadyDownloadedAndUnpacked(toolsFolder, tools) && + allToolsAlreadyDownloadedAndUnpacked(toolsFolder, toolsMultipleVersions) && + allLibrariesAlreadyDownloadedAndUnpacked(librariesFolder, libraries) { return } @@ -239,7 +241,7 @@ func downloadCores(cores []Core, index map[string]interface{}) error { if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackCore(core, url, HARDWARE_FOLDER) + err = downloadAndUnpackCore(core, url, hardwareFolder) if err != nil { return i18n.WrapError(err) } @@ -253,7 +255,7 @@ func downloadBoardManagerCores(cores []Core, index map[string]interface{}) error if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackBoardManagerCore(core, url, BOARD_MANAGER_FOLDER) + err = downloadAndUnpackBoardManagerCore(core, url, boardManagerFolder) if err != nil { return i18n.WrapError(err) } @@ -290,7 +292,7 @@ func downloadTools(tools []Tool, index map[string]interface{}) error { if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackTool(tool, url, TOOLS_FOLDER, true) + err = downloadAndUnpackTool(tool, url, toolsFolder, true) if err != nil { return i18n.WrapError(err) } @@ -303,11 +305,9 @@ func downloadToolsMultipleVersions(tools []Tool, index map[string]interface{}) e host := translateGOOSGOARCHToPackageIndexValue() for _, tool := range tools { - if !toolAlreadyDownloadedAndUnpacked(TOOLS_FOLDER, tool) { - _, err := os.Stat(filepath.Join(TOOLS_FOLDER, tool.Name)) - if err == nil { - err = os.RemoveAll(filepath.Join(TOOLS_FOLDER, tool.Name)) - if err != nil { + if !toolAlreadyDownloadedAndUnpacked(toolsFolder, tool) { + if exist, _ := toolsFolder.Join(tool.Name).Exist(); exist { + if err := toolsFolder.Join(tool.Name).RemoveAll(); err != nil { return i18n.WrapError(err) } } @@ -319,7 +319,7 @@ func downloadToolsMultipleVersions(tools []Tool, index map[string]interface{}) e if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackTool(tool, url, TOOLS_FOLDER, false) + err = downloadAndUnpackTool(tool, url, toolsFolder, false) if err != nil { return i18n.WrapError(err) } @@ -336,7 +336,7 @@ func downloadBoardsManagerTools(tools []Tool, index map[string]interface{}) erro if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackBoardsManagerTool(tool, url, BOARD_MANAGER_FOLDER) + err = downloadAndUnpackBoardsManagerTool(tool, url, boardManagerFolder) if err != nil { return i18n.WrapError(err) } @@ -345,7 +345,7 @@ func downloadBoardsManagerTools(tools []Tool, index map[string]interface{}) erro return nil } -func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath string, cores []Core) bool { +func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) bool { for _, core := range cores { if !boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { return false @@ -354,12 +354,12 @@ func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath string, cores return true } -func boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath string, core Core) bool { - _, err := os.Stat(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) - return !os.IsNotExist(err) +func boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) bool { + exist, _ := targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).Exist() + return exist } -func allCoresAlreadyDownloadedAndUnpacked(targetPath string, cores []Core) (bool, error) { +func allCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) (bool, error) { for _, core := range cores { alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) if err != nil { @@ -372,27 +372,26 @@ func allCoresAlreadyDownloadedAndUnpacked(targetPath string, cores []Core) (bool return true, nil } -func coreAlreadyDownloadedAndUnpacked(targetPath string, core Core) (bool, error) { - corePath := filepath.Join(targetPath, core.Maintainer, core.Arch) +func coreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) (bool, error) { + corePath := targetPath.Join(core.Maintainer, core.Arch) - _, err := os.Stat(corePath) - if os.IsNotExist(err) { + if exist, _ := corePath.Exist(); !exist { return false, nil } - platform, err := properties.Load(filepath.Join(corePath, "platform.txt")) + platform, err := properties.LoadFromPath(corePath.Join("platform.txt")) if err != nil { return false, i18n.WrapError(err) } if core.Version != platform["version"] { - err := os.RemoveAll(corePath) + err := corePath.RemoveAll() return false, i18n.WrapError(err) } return true, nil } -func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath string, tools []Tool) bool { +func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) bool { for _, tool := range tools { if !boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { return false @@ -401,12 +400,12 @@ func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath string, tools return true } -func boardManagerToolAlreadyDownloadedAndUnpacked(targetPath string, tool Tool) bool { - _, err := os.Stat(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - return !os.IsNotExist(err) +func boardManagerToolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { + exist, _ := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).Exist() + return exist } -func allToolsAlreadyDownloadedAndUnpacked(targetPath string, tools []Tool) bool { +func allToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) bool { for _, tool := range tools { if !toolAlreadyDownloadedAndUnpacked(targetPath, tool) { return false @@ -415,12 +414,12 @@ func allToolsAlreadyDownloadedAndUnpacked(targetPath string, tools []Tool) bool return true } -func toolAlreadyDownloadedAndUnpacked(targetPath string, tool Tool) bool { - _, err := os.Stat(filepath.Join(targetPath, tool.Name, tool.Version)) - return !os.IsNotExist(err) +func toolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { + exist, _ := targetPath.Join(tool.Name, tool.Version).Exist() + return exist } -func allLibrariesAlreadyDownloadedAndUnpacked(targetPath string, libraries []Library) bool { +func allLibrariesAlreadyDownloadedAndUnpacked(targetPath *paths.Path, libraries []Library) bool { for _, library := range libraries { if !libraryAlreadyDownloadedAndUnpacked(targetPath, library) { return false @@ -429,20 +428,20 @@ func allLibrariesAlreadyDownloadedAndUnpacked(targetPath string, libraries []Lib return true } -func libraryAlreadyDownloadedAndUnpacked(targetPath string, library Library) bool { - _, err := os.Stat(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if os.IsNotExist(err) { +func libraryAlreadyDownloadedAndUnpacked(targetPath *paths.Path, library Library) bool { + exist, _ := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).Exist() + if !exist { return false } - libProps, err := properties.Load(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1), "library.properties")) + libProps, err := properties.LoadFromPath(targetPath.Join(strings.Replace(library.Name, " ", "_", -1), "library.properties")) if err != nil { return false } return libProps["version"] == library.Version || libProps["version"] == library.VersionInLibProperties } -func downloadAndUnpackCore(core Core, url string, targetPath string) error { +func downloadAndUnpackCore(core Core, url string, targetPath *paths.Path) error { alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) if err != nil { return i18n.WrapError(err) @@ -451,8 +450,7 @@ func downloadAndUnpackCore(core Core, url string, targetPath string) error { return nil } - targetPath, err = filepath.Abs(targetPath) - if err != nil { + if err := targetPath.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -460,32 +458,31 @@ func downloadAndUnpackCore(core Core, url string, targetPath string) error { if err != nil { return i18n.WrapError(err) } - defer os.RemoveAll(unpackFolder) + defer unpackFolder.RemoveAll() - _, err = os.Stat(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err != nil { + packagerPath := targetPath.Join(core.Maintainer) + corePath := targetPath.Join(core.Maintainer, core.Arch) + + if exist, _ := corePath.Exist(); exist { + if err := corePath.RemoveAll(); err != nil { return i18n.WrapError(err) } } if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer)) - if err != nil { + if err := packagerPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, core.Maintainer, core.Arch)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(core.Maintainer, core.Arch)) if err != nil { return i18n.WrapError(err) } } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, core.Arch)) - if err != nil { + if err := targetPath.Join(core.Maintainer, core.Arch).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, core.Maintainer, core.Arch, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(core.Maintainer, core.Arch, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -495,13 +492,12 @@ func downloadAndUnpackCore(core Core, url string, targetPath string) error { return nil } -func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath string) error { +func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath *paths.Path) error { if boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { return nil } - targetPath, err := filepath.Abs(targetPath) - if err != nil { + if err := targetPath.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -509,32 +505,28 @@ func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath string) if err != nil { return i18n.WrapError(err) } - defer os.RemoveAll(unpackFolder) + defer unpackFolder.RemoveAll() - _, err = os.Stat(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err != nil { + if exist, _ := targetPath.Join(core.Maintainer, "hardware", core.Arch).Exist(); exist { + if err := targetPath.Join(core.Maintainer, "hardware", core.Arch).RemoveAll(); err != nil { return i18n.WrapError(err) } } if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch)) - if err != nil { + if err := targetPath.Join(core.Maintainer, "hardware", core.Arch).MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version)) if err != nil { return i18n.WrapError(err) } } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version)) - if err != nil { + if err := targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, core.Maintainer, "hardware", core.Arch, core.Version, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -544,13 +536,12 @@ func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath string) return nil } -func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath string) error { +func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath *paths.Path) error { if boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { return nil } - targetPath, err := filepath.Abs(targetPath) - if err != nil { + if err := targetPath.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -558,24 +549,22 @@ func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath string if err != nil { return i18n.WrapError(err) } - defer os.RemoveAll(unpackFolder) + defer unpackFolder.RemoveAll() if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name)) - if err != nil { + if err := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name).MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) if err != nil { return i18n.WrapError(err) } } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - if err != nil { + if err := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -585,13 +574,12 @@ func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath string return nil } -func downloadAndUnpackTool(tool Tool, url string, targetPath string, deleteIfMissing bool) error { +func downloadAndUnpackTool(tool Tool, url string, targetPath *paths.Path, deleteIfMissing bool) error { if toolAlreadyDownloadedAndUnpacked(targetPath, tool) { return nil } - targetPath, err := filepath.Abs(targetPath) - if err != nil { + if err := targetPath.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -599,34 +587,30 @@ func downloadAndUnpackTool(tool Tool, url string, targetPath string, deleteIfMis if err != nil { return i18n.WrapError(err) } - defer os.RemoveAll(unpackFolder) + defer unpackFolder.RemoveAll() if deleteIfMissing { - _, err = os.Stat(filepath.Join(targetPath, tool.Name)) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, tool.Name)) - if err != nil { + if exist, _ := targetPath.Join(tool.Name).Exist(); exist { + if err := targetPath.Join(tool.Name).MkdirAll(); err != nil { return i18n.WrapError(err) } } } if len(files) == 1 && files[0].IsDir() { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Name)) - if err != nil { + if err := targetPath.Join(tool.Name).MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, tool.Name, tool.Version)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(tool.Name, tool.Version)) if err != nil { return i18n.WrapError(err) } } else { - err = utils.EnsureFolderExists(filepath.Join(targetPath, tool.Name, tool.Version)) - if err != nil { + if err := targetPath.Join(tool.Name, tool.Version).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(filepath.Join(unpackFolder, file.Name()), filepath.Join(targetPath, tool.Name, tool.Version, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(tool.Name, tool.Version, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -636,58 +620,58 @@ func downloadAndUnpackTool(tool Tool, url string, targetPath string, deleteIfMis return nil } -func downloadAndUnpack(url string) (string, []os.FileInfo, error) { +func downloadAndUnpack(url string) (*paths.Path, []os.FileInfo, error) { fmt.Fprintln(os.Stderr, "Downloading "+url) - unpackFolder, err := ioutil.TempDir(constants.EMPTY_STRING, "arduino-builder-tool") + unpackFolder, err := paths.MkTempDir("", "arduino-builder-tool") if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } urlParts := strings.Split(url, "/") archiveFileName := urlParts[len(urlParts)-1] - archiveFilePath := filepath.Join(unpackFolder, archiveFileName) + archiveFilePath := unpackFolder.Join(archiveFileName) res, err := http.Get(url) if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } bytes, err := ioutil.ReadAll(res.Body) if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } res.Body.Close() - utils.WriteFileBytes(archiveFilePath, bytes) + archiveFilePath.WriteFile(bytes) cmd := buildUnpackCmd(archiveFilePath) out, err := cmd.CombinedOutput() if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } if len(out) > 0 { fmt.Println(string(out)) } - os.Remove(archiveFilePath) + archiveFilePath.Remove() - files, err := gohasissues.ReadDir(unpackFolder) + files, err := gohasissues.ReadDir(unpackFolder.String()) if err != nil { - return constants.EMPTY_STRING, nil, i18n.WrapError(err) + return nil, nil, i18n.WrapError(err) } return unpackFolder, files, nil } -func buildUnpackCmd(file string) *exec.Cmd { +func buildUnpackCmd(file *paths.Path) *exec.Cmd { var cmd *exec.Cmd - if strings.HasSuffix(file, "zip") { - cmd = exec.Command("unzip", "-qq", filepath.Base(file)) + if file.Ext() == "zip" { + cmd = exec.Command("unzip", "-qq", file.Base()) } else { - cmd = exec.Command("tar", "xf", filepath.Base(file)) + cmd = exec.Command("tar", "xf", file.Base()) } - cmd.Dir = filepath.Dir(file) + cmd.Dir = file.Parent().String() return cmd } @@ -748,7 +732,7 @@ func downloadLibraries(libraries []Library, index map[string]interface{}) error if err != nil { return i18n.WrapError(err) } - err = downloadAndUnpackLibrary(library, url, LIBRARIES_FOLDER) + err = downloadAndUnpackLibrary(library, url, librariesFolder) if err != nil { return i18n.WrapError(err) } @@ -772,13 +756,12 @@ func findLibraryUrl(index map[string]interface{}, library Library) (string, erro return constants.EMPTY_STRING, errors.Errorf("Unable to find library " + library.Name + " " + library.Version) } -func downloadAndUnpackLibrary(library Library, url string, targetPath string) error { +func downloadAndUnpackLibrary(library Library, url string, targetPath *paths.Path) error { if libraryAlreadyDownloadedAndUnpacked(targetPath, library) { return nil } - targetPath, err := filepath.Abs(targetPath) - if err != nil { + if err := targetPath.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -786,17 +769,15 @@ func downloadAndUnpackLibrary(library Library, url string, targetPath string) er if err != nil { return i18n.WrapError(err) } - defer os.RemoveAll(unpackFolder) + defer unpackFolder.RemoveAll() - _, err = os.Stat(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if err == nil { - err = os.RemoveAll(filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) - if err != nil { + if exist, _ := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).Exist(); exist { + if err := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).RemoveAll(); err != nil { return i18n.WrapError(err) } } - err = copyRecursive(filepath.Join(unpackFolder, files[0].Name()), filepath.Join(targetPath, strings.Replace(library.Name, " ", "_", -1))) + err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(strings.Replace(library.Name, " ", "_", -1))) if err != nil { return i18n.WrapError(err) } @@ -804,17 +785,17 @@ func downloadAndUnpackLibrary(library Library, url string, targetPath string) er return nil } -func copyRecursive(from, to string) error { +func copyRecursive(from, to *paths.Path) error { copyFunc := func(currentPath string, info os.FileInfo, err error) error { if err != nil { return err } - rel, err := filepath.Rel(from, currentPath) + rel, err := filepath.Rel(from.String(), currentPath) if err != nil { return i18n.WrapError(err) } - targetPath := filepath.Join(to, rel) + targetPath := filepath.Join(to.String(), rel) if info.IsDir() { err := os.MkdirAll(targetPath, info.Mode()) if err != nil { @@ -855,6 +836,6 @@ func copyRecursive(from, to string) error { return nil } - err := gohasissues.Walk(from, copyFunc) + err := gohasissues.Walk(from.String(), copyFunc) return i18n.WrapError(err) } diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index 1216244b..a89b21b4 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -31,13 +31,13 @@ package test import ( "fmt" - "os" "path/filepath" "sort" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -45,18 +45,18 @@ func TestIncludesToIncludeFolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -81,18 +81,18 @@ func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -116,18 +116,18 @@ func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch9", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch9", "sketch.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -154,18 +154,18 @@ func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch10", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch10", "sketch.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -192,17 +192,17 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), FQBN: "my_avr_platform:avr:custom_yun", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -222,25 +222,25 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")), importedLibraries[0].SrcFolder.String()) + requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")) } func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatform(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), FQBN: "my_avr_platform:avr:custom_yun", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -260,25 +260,25 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "SPI")), importedLibraries[0].SrcFolder.String()) + requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("libraries", "SPI")) } func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_usbhost", "sketch_usbhost.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_usbhost", "sketch_usbhost.ino"), FQBN: "arduino:samd:arduino_zero_native", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -298,25 +298,25 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "USBHost", importedLibraries[0].Name) - require.Equal(t, Abs(t, filepath.Join("libraries", "USBHost", "src")), importedLibraries[0].SrcFolder.String()) + requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("libraries", "USBHost", "src")) } func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_with_subfolders", "sketch_with_subfolders.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 8af56278..c02bc537 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -37,6 +37,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -44,9 +45,9 @@ func TestLoadLibrariesAVR(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), FQBN: "arduino:avr:leonardo", } @@ -64,9 +65,9 @@ func TestLoadLibrariesAVR(t *testing.T) { librariesFolders := ctx.LibrariesFolders require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) libs := ctx.Libraries require.Equal(t, 24, len(libs)) @@ -79,8 +80,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ require.Equal(t, "Adafruit_PN532", libs[idx].Name) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].Folder.String()) - require.Equal(t, Abs(t, "downloaded_libraries/Adafruit_PN532"), libs[idx].SrcFolder.String()) + require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].Folder)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].SrcFolder)) require.Equal(t, 1, len(libs[idx].Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, libs[idx].Architectures[0]) require.False(t, libs[idx].IsLegacy) @@ -95,8 +96,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ bridgeLib := libs[idx] require.Equal(t, "Bridge", bridgeLib.Name) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge"), bridgeLib.Folder.String()) - require.Equal(t, Abs(t, "downloaded_libraries/Bridge/src"), bridgeLib.SrcFolder.String()) + require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge")).EquivalentTo(bridgeLib.Folder)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge/src")).EquivalentTo(bridgeLib.SrcFolder)) require.Equal(t, 1, len(bridgeLib.Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Architectures[0]) require.Equal(t, "Arduino", bridgeLib.Author) @@ -153,9 +154,9 @@ func TestLoadLibrariesSAM(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), FQBN: "arduino:sam:arduino_due_x_dbg", } @@ -173,9 +174,9 @@ func TestLoadLibrariesSAM(t *testing.T) { librariesFolders := ctx.LibrariesFolders require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "sam", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "sam", "libraries")).EquivalentTo(librariesFolders[1])) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) libraries := ctx.Libraries require.Equal(t, 22, len(libraries)) @@ -236,9 +237,9 @@ func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), FQBN: "arduino:avr:leonardo", } @@ -256,18 +257,18 @@ func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { librariesFolders := ctx.LibrariesFolders require.Equal(t, 3, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[2]) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) } func TestLoadLibrariesMyAVRPlatform(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), FQBN: "my_avr_platform:avr:custom_yun", } @@ -285,8 +286,8 @@ func TestLoadLibrariesMyAVRPlatform(t *testing.T) { librariesFolders := ctx.LibrariesFolders require.Equal(t, 4, len(librariesFolders)) - require.Equal(t, Abs(t, filepath.Join("downloaded_libraries")), librariesFolders[0]) - require.Equal(t, Abs(t, filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), librariesFolders[1]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries")), librariesFolders[2]) - require.Equal(t, Abs(t, filepath.Join("libraries")), librariesFolders[3]) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) + require.True(t, Abs(t, paths.New("user_hardware", "my_avr_platform", "avr", "libraries")).EquivalentTo(librariesFolders[2])) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[3])) } diff --git a/test/load_previous_build_options_map_test.go b/test/load_previous_build_options_map_test.go index 55984804..99a445ec 100644 --- a/test/load_previous_build_options_map_test.go +++ b/test/load_previous_build_options_map_test.go @@ -30,23 +30,21 @@ package test import ( + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/stretchr/testify/require" - "os" - "path/filepath" - "testing" ) func TestLoadPreviousBuildOptionsMap(t *testing.T) { ctx := &types.Context{} buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - err := utils.WriteFile(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE), "test") + err := buildPath.Join(constants.BUILD_OPTIONS_FILE).WriteFile([]byte("test")) NoError(t, err) command := builder.LoadPreviousBuildOptionsMap{} @@ -60,7 +58,7 @@ func TestLoadPreviousBuildOptionsMapMissingFile(t *testing.T) { ctx := &types.Context{} buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() command := builder.LoadPreviousBuildOptionsMap{} err := command.Run(ctx) diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go index ad3ea6f7..67348b5f 100644 --- a/test/load_vid_pid_specific_properties_test.go +++ b/test/load_vid_pid_specific_properties_test.go @@ -30,12 +30,12 @@ package test import ( - "os" "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -43,15 +43,15 @@ func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:micro", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, @@ -73,15 +73,15 @@ func TestLoadVIDPIDSpecificProperties(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:micro", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() ctx.USBVidPid = "0x2341_0x0237" diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go index 5d6776cf..59e6f0e0 100644 --- a/test/merge_sketch_with_bootloader_test.go +++ b/test/merge_sketch_with_bootloader_test.go @@ -30,40 +30,39 @@ package test import ( + "path/filepath" + "strings" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" ) func TestMergeSketchWithBootloader(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) + err := buildPath.Join("sketch").MkdirAll() NoError(t, err) fakeSketchHex := "row 1\n" + "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch", "sketch.ino.hex"), fakeSketchHex) + err = buildPath.Join("sketch", "sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) NoError(t, err) commands := []types.Command{ @@ -76,7 +75,7 @@ func TestMergeSketchWithBootloader(t *testing.T) { NoError(t, err) } - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch", "sketch.ino.with_bootloader.hex")) + bytes, err := buildPath.Join("sketch", "sketch.ino.with_bootloader.hex").ReadFile() NoError(t, err) mergedSketchHex := string(bytes) @@ -88,24 +87,24 @@ func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) + err := buildPath.Join("sketch").MkdirAll() NoError(t, err) fakeSketchHex := "row 1\n" + "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch.ino.hex"), fakeSketchHex) + err = buildPath.Join("sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) NoError(t, err) commands := []types.Command{ @@ -118,7 +117,7 @@ func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { NoError(t, err) } - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch.ino.with_bootloader.hex")) + bytes, err := buildPath.Join("sketch.ino.with_bootloader.hex").ReadFile() NoError(t, err) mergedSketchHex := string(bytes) @@ -130,17 +129,17 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, @@ -159,33 +158,33 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { err := command.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(buildPath, "sketch.ino.with_bootloader.hex")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) + exist, err := buildPath.Join("sketch.ino.with_bootloader.hex").Exist() + require.NoError(t, err) + require.False(t, exist) } func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - ToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + ToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - err := utils.EnsureFolderExists(filepath.Join(buildPath, "sketch")) + err := buildPath.Join("sketch").MkdirAll() NoError(t, err) fakeSketchHex := "row 1\n" + "row 2\n" - err = utils.WriteFile(filepath.Join(buildPath, "sketch", "sketch.ino.hex"), fakeSketchHex) + err = buildPath.Join("sketch", "sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) NoError(t, err) commands := []types.Command{ @@ -198,7 +197,7 @@ func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { NoError(t, err) } - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, "sketch", "sketch.ino.with_bootloader.hex")) + bytes, err := buildPath.Join("sketch", "sketch.ino.with_bootloader.hex").ReadFile() NoError(t, err) mergedSketchHex := string(bytes) diff --git a/test/platform_keys_rewrite_loader_test.go b/test/platform_keys_rewrite_loader_test.go index 3d69bf79..acb4fbbd 100644 --- a/test/platform_keys_rewrite_loader_test.go +++ b/test/platform_keys_rewrite_loader_test.go @@ -35,12 +35,13 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestLoadPlatformKeysRewrite(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"downloaded_hardware", filepath.Join("..", "hardware"), "hardware"}, + HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), } commands := []types.Command{ diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go index 18b8c2a6..0473e245 100644 --- a/test/prototypes_adder_test.go +++ b/test/prototypes_adder_test.go @@ -31,7 +31,6 @@ package test import ( - "os" "path/filepath" "strings" "testing" @@ -39,20 +38,21 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestPrototypesAdderBridgeExample(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -60,7 +60,7 @@ func TestPrototypesAdderBridgeExample(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() ctx.DebugLevel = 10 @@ -91,18 +91,18 @@ func TestPrototypesAdderSketchWithIfDef(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch2", "SketchWithIfDef.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -131,18 +131,18 @@ func TestPrototypesAdderBaladuino(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch3", "Baladuino.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch3", "Baladuino.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -171,18 +171,18 @@ func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch4", "CharWithEscapedDoubleQuote.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch4", "CharWithEscapedDoubleQuote.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -211,18 +211,18 @@ func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch5", "IncludeBetweenMultilineComment.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch5", "IncludeBetweenMultilineComment.ino"), FQBN: "arduino:sam:arduino_due_x_dbg", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -251,18 +251,18 @@ func TestPrototypesAdderLineContinuations(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch6", "/LineContinuations.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch6", "/LineContinuations.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -291,18 +291,18 @@ func TestPrototypesAdderStringWithComment(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch7", "StringWithComment.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch7", "StringWithComment.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -331,18 +331,18 @@ func TestPrototypesAdderSketchWithStruct(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch8", "SketchWithStruct.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch8", "SketchWithStruct.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -375,14 +375,14 @@ func TestPrototypesAdderSketchWithStruct(t *testing.T) { func TestPrototypesAdderSketchWithConfig(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_config", "sketch_with_config.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_config", "sketch_with_config.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -390,7 +390,7 @@ func TestPrototypesAdderSketchWithConfig(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -421,22 +421,22 @@ func TestPrototypesAdderSketchWithConfig(t *testing.T) { func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_no_functions_two_files", "main.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_no_functions_two_files", "main.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_no_functions_two_files", "main.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_no_functions_two_files", "main.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -465,21 +465,21 @@ func TestPrototypesAdderSketchNoFunctions(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("sketch_no_functions", "main.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_no_functions", "main.ino"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() - sketchLocation := filepath.Join("sketch_no_functions", "main.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_no_functions", "main.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) commands := []types.Command{ @@ -507,14 +507,14 @@ func TestPrototypesAdderSketchNoFunctions(t *testing.T) { func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_default_args", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_default_args", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -522,7 +522,7 @@ func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -550,14 +550,14 @@ func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_inline_function", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_inline_function", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -565,7 +565,7 @@ func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -604,14 +604,14 @@ func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_function_signature_inside_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_function_signature_inside_ifdef", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -619,7 +619,7 @@ func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -647,14 +647,14 @@ func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_usbcon", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_usbcon", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - OtherLibrariesFolders: []string{"libraries"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -662,7 +662,7 @@ func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -690,13 +690,13 @@ func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { func TestPrototypesAdderSketchWithTypename(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_typename", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_typename", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - LibrariesFolders: []string{"libraries", "downloaded_libraries"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + LibrariesFolders: paths.NewPathList("libraries", "downloaded_libraries"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), SketchLocation: sketchLocation, FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10600", @@ -704,7 +704,7 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -738,14 +738,14 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_ifdef", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:yun", ArduinoAPIVersion: "10600", @@ -753,7 +753,7 @@ func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -784,14 +784,14 @@ func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_ifdef", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:sam:arduino_due_x_dbg", ArduinoAPIVersion: "10600", @@ -799,7 +799,7 @@ func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -830,14 +830,14 @@ func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { func TestPrototypesAdderSketchWithConst(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - sketchLocation := filepath.Join("sketch_with_const", "sketch.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation)) + sketchLocation := paths.New("sketch_with_const", "sketch.ino") + quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", @@ -845,7 +845,7 @@ func TestPrototypesAdderSketchWithConst(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ @@ -874,18 +874,18 @@ func TestPrototypesAdderSketchWithDosEol(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: filepath.Join("eol_processing", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("eol_processing", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", Verbose: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ diff --git a/test/read_file_and_store_in_context_test.go b/test/read_file_and_store_in_context_test.go index a83cfa0c..b8336ed4 100644 --- a/test/read_file_and_store_in_context_test.go +++ b/test/read_file_and_store_in_context_test.go @@ -30,24 +30,26 @@ package test import ( + "io/ioutil" + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "testing" ) func TestReadFileAndStoreInContext(t *testing.T) { - file, err := ioutil.TempFile("", "test") + filePath, err := ioutil.TempFile("", "test") NoError(t, err) - defer os.RemoveAll(file.Name()) - utils.WriteFile(file.Name(), "test test\nciao") + file := paths.New(filePath.Name()) + defer file.RemoveAll() + + file.WriteFile([]byte("test test\nciao")) ctx := &types.Context{} - ctx.FileToRead = file.Name() + ctx.FileToRead = file command := &builder.ReadFileAndStoreInContext{Target: &ctx.SourceGccMinusE} err = command.Run(ctx) diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index 4f0b7c58..6e172f40 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -30,13 +30,13 @@ package test import ( - "os" "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -44,15 +44,15 @@ func TestSetupBuildProperties(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, @@ -78,23 +78,27 @@ func TestSetupBuildProperties(t *testing.T) { require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - require.Equal(t, Abs(t, "downloaded_hardware/arduino/avr"), buildProperties["runtime.platform.path"]) - require.Equal(t, Abs(t, "downloaded_hardware/arduino"), buildProperties["runtime.hardware.path"]) + requireEquivalentPaths(t, buildProperties["runtime.platform.path"], "downloaded_hardware/arduino/avr") + requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], "downloaded_hardware/arduino") require.Equal(t, "10600", buildProperties["runtime.ide.version"]) require.NotEmpty(t, buildProperties["runtime.os"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) + requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + + requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"], "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") + requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude.path"], "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") + bossacPath := buildProperties["runtime.tools.bossac.path"] - require.True(t, bossacPath == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || bossacPath == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - avrdudePath := buildProperties["runtime.tools.avrdude.path"] - require.True(t, avrdudePath == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath == Abs(t, "./tools_builtin/avr")) - avrgccPath := buildProperties["runtime.tools.avr-gcc.path"] - require.True(t, avrgccPath == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath == Abs(t, "./tools_builtin/avr")) + bossac161Path := buildProperties["runtime.tools.bossac-1.6.1-arduino.path"] + bossac15Path := buildProperties["runtime.tools.bossac-1.5-arduino.path"] + requireEquivalentPaths(t, bossac161Path, "downloaded_tools/bossac/1.6.1-arduino") + requireEquivalentPaths(t, bossac15Path, "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, bossacPath, bossac161Path, bossac15Path) - require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) + requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + + requireEquivalentPaths(t, buildProperties["build.source.path"], "sketch1") require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) @@ -106,9 +110,9 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "arduino:avr:uno", ArduinoAPIVersion: "10600", @@ -116,7 +120,7 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, @@ -147,15 +151,15 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "my_avr_platform:avr:custom_yun", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, @@ -177,23 +181,23 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { require.Equal(t, "custom_yun", buildProperties["_id"]) require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties["bootloader.file"]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform", "avr")), buildProperties["runtime.platform.path"]) - require.Equal(t, Abs(t, filepath.Join("user_hardware", "my_avr_platform")), buildProperties["runtime.hardware.path"]) + requireEquivalentPaths(t, buildProperties["runtime.platform.path"], filepath.Join("user_hardware", "my_avr_platform", "avr")) + requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], filepath.Join("user_hardware", "my_avr_platform")) } func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, - BuiltInToolsFolders: []string{"downloaded_tools", "./tools_builtin"}, - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: "my_avr_platform:avr:custom_yun", ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, @@ -214,26 +218,25 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) - require.Equal(t, Abs(t, "user_hardware/my_avr_platform/avr"), buildProperties["runtime.platform.path"]) - require.Equal(t, Abs(t, "user_hardware/my_avr_platform"), buildProperties["runtime.hardware.path"]) + requireEquivalentPaths(t, buildProperties["runtime.platform.path"], "user_hardware/my_avr_platform/avr") + requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], "user_hardware/my_avr_platform") require.Equal(t, "10600", buildProperties["runtime.ide.version"]) require.NotEmpty(t, buildProperties["runtime.os"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), buildProperties["runtime.tools.bossac-1.6.1-arduino.path"]) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), buildProperties["runtime.tools.bossac-1.5-arduino.path"]) - require.True(t, buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.6.1-arduino") || buildProperties["runtime.tools.bossac.path"] == Abs(t, "./downloaded_tools/bossac/1.5-arduino")) - avrdudePath := buildProperties["runtime.tools.avrdude.path"] - require.True(t, avrdudePath == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath == Abs(t, "./tools_builtin/avr")) - avrdudePath601 := buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"] - require.True(t, avrdudePath601 == Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5") || avrdudePath601 == Abs(t, "./tools_builtin/avr")) - avrgccPath := buildProperties["runtime.tools.avr-gcc.path"] - require.True(t, avrgccPath == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath == Abs(t, "./tools_builtin/avr")) - avrgccPath481 := buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"] - require.True(t, avrgccPath481 == Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5") || avrgccPath481 == Abs(t, "./tools_builtin/avr")) - - require.Equal(t, Abs(t, "sketch1"), buildProperties["build.source.path"]) + requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties["runtime.tools.bossac-1.6.1-arduino.path"], "downloaded_tools/bossac/1.6.1-arduino") + requireEquivalentPaths(t, buildProperties["runtime.tools.bossac-1.5-arduino.path"], "downloaded_tools/bossac/1.5-arduino") + + requireEquivalentPaths(t, buildProperties["runtime.tools.bossac.path"], "downloaded_tools/bossac/1.6.1-arduino", "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude.path"], "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") + + requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"], "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") + + requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + + requireEquivalentPaths(t, buildProperties["build.source.path"], "sketch1") require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) diff --git a/test/sketch_loader_test.go b/test/sketch_loader_test.go index b524457c..0e98d79f 100644 --- a/test/sketch_loader_test.go +++ b/test/sketch_loader_test.go @@ -35,12 +35,13 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestLoadSketchWithFolder(t *testing.T) { ctx := &types.Context{ - SketchLocation: "sketch1", + SketchLocation: paths.New("sketch1"), } loader := builder.SketchLoader{} @@ -52,7 +53,7 @@ func TestLoadSketchWithFolder(t *testing.T) { func TestLoadSketchNonExistentPath(t *testing.T) { ctx := &types.Context{ - SketchLocation: "asdasd78128123981723981273asdasd", + SketchLocation: paths.New("asdasd78128123981723981273asdasd"), } loader := builder.SketchLoader{} @@ -64,7 +65,7 @@ func TestLoadSketchNonExistentPath(t *testing.T) { func TestLoadSketch(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + SketchLocation: paths.New("sketch1", "sketch.ino"), } commands := []types.Command{ @@ -79,21 +80,21 @@ func TestLoadSketch(t *testing.T) { sketch := ctx.Sketch require.NotNil(t, sketch) - require.Contains(t, sketch.MainFile.Name, "sketch.ino") + require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") require.Equal(t, 2, len(sketch.OtherSketchFiles)) - require.Contains(t, sketch.OtherSketchFiles[0].Name, "old.pde") - require.Contains(t, sketch.OtherSketchFiles[1].Name, "other.ino") + require.Contains(t, sketch.OtherSketchFiles[0].Name.String(), "old.pde") + require.Contains(t, sketch.OtherSketchFiles[1].Name.String(), "other.ino") require.Equal(t, 3, len(sketch.AdditionalFiles)) - require.Contains(t, sketch.AdditionalFiles[0].Name, "header.h") - require.Contains(t, sketch.AdditionalFiles[1].Name, "s_file.S") - require.Contains(t, sketch.AdditionalFiles[2].Name, "helper.h") + require.Contains(t, sketch.AdditionalFiles[0].Name.String(), "header.h") + require.Contains(t, sketch.AdditionalFiles[1].Name.String(), "s_file.S") + require.Contains(t, sketch.AdditionalFiles[2].Name.String(), "helper.h") } func TestFailToLoadSketchFromFolder(t *testing.T) { ctx := &types.Context{ - SketchLocation: "./sketch1", + SketchLocation: paths.New("./sketch1"), } loader := builder.SketchLoader{} @@ -104,7 +105,7 @@ func TestFailToLoadSketchFromFolder(t *testing.T) { func TestLoadSketchFromFolder(t *testing.T) { ctx := &types.Context{ - SketchLocation: "sketch_with_subfolders", + SketchLocation: paths.New("sketch_with_subfolders"), } commands := []types.Command{ @@ -119,20 +120,20 @@ func TestLoadSketchFromFolder(t *testing.T) { sketch := ctx.Sketch require.NotNil(t, sketch) - require.Contains(t, sketch.MainFile.Name, "sketch_with_subfolders.ino") + require.Contains(t, sketch.MainFile.Name.String(), "sketch_with_subfolders.ino") require.Equal(t, 0, len(sketch.OtherSketchFiles)) require.Equal(t, 4, len(sketch.AdditionalFiles)) - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[0].Name), "sketch_with_subfolders/src/subfolder/other.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[1].Name), "sketch_with_subfolders/src/subfolder/other.h") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[2].Name), "sketch_with_subfolders/subfolder/dont_load_me.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[3].Name), "sketch_with_subfolders/subfolder/other.h") + require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[0].Name.String()), "sketch_with_subfolders/src/subfolder/other.cpp") + require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[1].Name.String()), "sketch_with_subfolders/src/subfolder/other.h") + require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[2].Name.String()), "sketch_with_subfolders/subfolder/dont_load_me.cpp") + require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[3].Name.String()), "sketch_with_subfolders/subfolder/other.h") } func TestLoadSketchWithBackup(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch_with_backup_files", "sketch.ino"), + SketchLocation: paths.New("sketch_with_backup_files", "sketch.ino"), } commands := []types.Command{ @@ -147,7 +148,7 @@ func TestLoadSketchWithBackup(t *testing.T) { sketch := ctx.Sketch require.NotNil(t, sketch) - require.Contains(t, sketch.MainFile.Name, "sketch.ino") + require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") require.Equal(t, 0, len(sketch.AdditionalFiles)) require.Equal(t, 0, len(sketch.OtherSketchFiles)) @@ -155,7 +156,7 @@ func TestLoadSketchWithBackup(t *testing.T) { func TestLoadSketchWithMacOSXGarbage(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch_with_macosx_garbage", "sketch.ino"), + SketchLocation: paths.New("sketch_with_macosx_garbage", "sketch.ino"), } commands := []types.Command{ @@ -170,7 +171,7 @@ func TestLoadSketchWithMacOSXGarbage(t *testing.T) { sketch := ctx.Sketch require.NotNil(t, sketch) - require.Contains(t, sketch.MainFile.Name, "sketch.ino") + require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") require.Equal(t, 0, len(sketch.AdditionalFiles)) require.Equal(t, 0, len(sketch.OtherSketchFiles)) diff --git a/test/sketch_source_merger_test.go b/test/sketch_source_merger_test.go index 5edfc35d..c88b82f5 100644 --- a/test/sketch_source_merger_test.go +++ b/test/sketch_source_merger_test.go @@ -35,6 +35,8 @@ import ( "strings" "testing" + "github.com/arduino/go-paths-helper" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" "github.com/stretchr/testify/require" @@ -42,7 +44,7 @@ import ( func TestMergeSketch(t *testing.T) { ctx := &types.Context{ - SketchLocation: filepath.Join("sketch1", "sketch.ino"), + SketchLocation: paths.New("sketch1", "sketch.ino"), } commands := []types.Command{ diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go index 31c20f1d..97ca993e 100644 --- a/test/store_build_options_map_test.go +++ b/test/store_build_options_map_test.go @@ -30,23 +30,22 @@ package test import ( + "testing" + "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" - "io/ioutil" - "os" - "path/filepath" - "testing" ) func TestStoreBuildOptionsMap(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{"hardware"}, - ToolsFolders: []string{"tools"}, - BuiltInLibrariesFolders: []string{"built-in libraries"}, - OtherLibrariesFolders: []string{"libraries"}, - SketchLocation: "sketchLocation", + HardwareFolders: paths.NewPathList("hardware"), + ToolsFolders: paths.NewPathList("tools"), + BuiltInLibrariesFolders: paths.NewPathList("built-in libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketchLocation"), FQBN: "fqbn", ArduinoAPIVersion: "ideVersion", CustomBuildProperties: []string{"custom=prop"}, @@ -55,7 +54,7 @@ func TestStoreBuildOptionsMap(t *testing.T) { } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() commands := []types.Command{ &builder.CreateBuildOptionsMap{}, @@ -67,10 +66,11 @@ func TestStoreBuildOptionsMap(t *testing.T) { NoError(t, err) } - _, err := os.Stat(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE)) + exist, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).Exist() NoError(t, err) + require.True(t, exist) - bytes, err := ioutil.ReadFile(filepath.Join(buildPath, constants.BUILD_OPTIONS_FILE)) + bytes, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).ReadFile() NoError(t, err) require.Equal(t, "{\n"+ diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index d896c5fb..06f1a245 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -35,12 +35,13 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) func TestTargetBoardResolverUno(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), FQBN: "arduino:avr:uno", } @@ -65,7 +66,7 @@ func TestTargetBoardResolverUno(t *testing.T) { func TestTargetBoardResolverDue(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), FQBN: "arduino:sam:arduino_due_x", } @@ -90,7 +91,7 @@ func TestTargetBoardResolverDue(t *testing.T) { func TestTargetBoardResolverMega1280(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), FQBN: "arduino:avr:mega:cpu=atmega1280", } @@ -116,7 +117,7 @@ func TestTargetBoardResolverMega1280(t *testing.T) { func TestTargetBoardResolverMega2560(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), FQBN: "arduino:avr:mega:cpu=atmega2560", } @@ -142,7 +143,7 @@ func TestTargetBoardResolverMega2560(t *testing.T) { func TestTargetBoardResolverCustomYun(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), FQBN: "my_avr_platform:avr:custom_yun", } @@ -168,7 +169,7 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { func TestTargetBoardResolverCustomCore(t *testing.T) { ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), FQBN: "watterott:avr:attiny841:core=spencekonde,info=info", } diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 14a6bcf7..873b7993 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -35,6 +35,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/stretchr/testify/require" ) @@ -57,11 +58,27 @@ func (s ByToolIDAndVersion) Less(i, j int) bool { return s[i].Folder < s[j].Folder } +func requireEquivalentPaths(t *testing.T, actual string, expected ...string) { + if len(expected) == 1 { + actualAbs, err := paths.New(actual).Abs() + require.NoError(t, err) + expectedAbs, err := paths.New(expected[0]).Abs() + require.NoError(t, err) + require.Equal(t, expectedAbs.String(), actualAbs.String()) + } else { + actualAbs, err := paths.New(actual).Abs() + require.NoError(t, err) + expectedAbs := paths.NewPathList(expected...) + require.NoError(t, expectedAbs.ToAbs()) + require.Contains(t, expectedAbs.AsStrings(), actualAbs.String()) + } +} + func TestLoadTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - BuiltInToolsFolders: []string{"downloaded_tools", "tools_builtin"}, + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) @@ -74,34 +91,34 @@ func TestLoadTools(t *testing.T) { idx := 0 require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avr-gcc/4.8.1-arduino5") idx++ require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") idx++ require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avrdude/6.0.1-arduino5") idx++ require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") idx++ require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.5-arduino") idx++ require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.6.1-arduino") idx++ require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/ctags/5.8-arduino11") } func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff"}, + HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) @@ -114,21 +131,21 @@ func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { idx := 0 require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") idx++ require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") } func TestLoadLotsOfTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{"downloaded_board_manager_stuff"}, - BuiltInToolsFolders: []string{"downloaded_tools", "tools_builtin"}, + HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) @@ -141,35 +158,35 @@ func TestLoadLotsOfTools(t *testing.T) { idx := 0 require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") idx++ require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/avr-gcc/4.8.1-arduino5"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avr-gcc/4.8.1-arduino5") idx++ require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") idx++ require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/avrdude/6.0.1-arduino5"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avrdude/6.0.1-arduino5") idx++ require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - require.Equal(t, Abs(t, "./tools_builtin/avr"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") idx++ require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.5-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.5-arduino") idx++ require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/bossac/1.6.1-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, tools[idx].Folder, "downloaded_tools/bossac/1.6.1-arduino") idx++ require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_tools/ctags/5.8-arduino11"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/ctags/5.8-arduino11") idx++ require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - require.Equal(t, Abs(t, "./downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino"), tools[idx].Folder) + requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") } diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go index fd5bcf9e..0b05a22c 100644 --- a/test/try_build_of_problematic_sketch_test.go +++ b/test/try_build_of_problematic_sketch_test.go @@ -31,12 +31,12 @@ package test import ( - "os" "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" ) func TestTryBuild001(t *testing.T) { @@ -119,7 +119,7 @@ func TestTryBuild019(t *testing.T) { func TestTryBuild020(t *testing.T) { ctx := makeDefaultContext(t) - ctx.OtherLibrariesFolders = []string{"dependent_libraries", "libraries"} + ctx.OtherLibrariesFolders = paths.NewPathList("dependent_libraries", "libraries") tryPreprocessWithContext(t, ctx, "sketch_with_dependend_libraries", "sketch.ino") } @@ -222,17 +222,17 @@ func makeDefaultContext(t *testing.T) *types.Context { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: []string{filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"}, - BuiltInToolsFolders: []string{"downloaded_tools"}, - BuiltInLibrariesFolders: []string{"downloaded_libraries"}, - OtherLibrariesFolders: []string{"libraries"}, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), + OtherLibrariesFolders: paths.NewPathList("libraries"), FQBN: "arduino:avr:leonardo", ArduinoAPIVersion: "10607", Verbose: true, DebugPreprocessor: true, } buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() return ctx } @@ -243,11 +243,11 @@ func tryBuild(t *testing.T, sketchPath ...string) { } func tryBuildWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := filepath.Join(sketchPath...) + sketchLocation := paths.New(sketchPath...) ctx.SketchLocation = sketchLocation err := builder.RunBuilder(ctx) - NoError(t, err, "Build error for "+sketchLocation) + NoError(t, err, "Build error for "+sketchLocation.String()) } func tryPreprocess(t *testing.T, sketchPath ...string) { @@ -256,9 +256,9 @@ func tryPreprocess(t *testing.T, sketchPath ...string) { } func tryPreprocessWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := filepath.Join(sketchPath...) + sketchLocation := paths.New(sketchPath...) ctx.SketchLocation = sketchLocation err := builder.RunPreprocess(ctx) - NoError(t, err, "Build error for "+sketchLocation) + NoError(t, err, "Build error for "+sketchLocation.String()) } diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go index 2a797e45..402d8942 100644 --- a/test/unused_compiled_libraries_remover_test.go +++ b/test/unused_compiled_libraries_remover_test.go @@ -30,25 +30,23 @@ package test import ( - "io/ioutil" - "os" - "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + paths "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/stretchr/testify/require" ) func TestUnusedCompiledLibrariesRemover(t *testing.T) { - temp, err := ioutil.TempDir("", "test") + temp, err := paths.MkTempDir("", "test") NoError(t, err) - defer os.RemoveAll(temp) + defer temp.RemoveAll() - NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755))) - NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755))) - NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644))) + NoError(t, temp.Join("SPI").MkdirAll()) + NoError(t, temp.Join("Bridge").MkdirAll()) + NoError(t, temp.Join("dummy_file").WriteFile([]byte{})) ctx := &types.Context{} ctx.LibrariesBuildPath = temp @@ -58,18 +56,20 @@ func TestUnusedCompiledLibrariesRemover(t *testing.T) { err = cmd.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(temp, "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "Bridge")) + exist, err := temp.Join("SPI").Exist() + require.NoError(t, err) + require.False(t, exist) + exist, err = temp.Join("Bridge").Exist() NoError(t, err) - _, err = os.Stat(filepath.Join(temp, "dummy_file")) + require.True(t, exist) + exist, err = temp.Join("dummy_file").Exist() NoError(t, err) + require.True(t, exist) } func TestUnusedCompiledLibrariesRemoverLibDoesNotExist(t *testing.T) { ctx := &types.Context{} - ctx.LibrariesBuildPath = filepath.Join(os.TempDir(), "test") + ctx.LibrariesBuildPath = paths.TempDir().Join("test") ctx.ImportedLibraries = []*libraries.Library{&libraries.Library{Name: "Bridge"}} cmd := builder.UnusedCompiledLibrariesRemover{} @@ -78,13 +78,13 @@ func TestUnusedCompiledLibrariesRemoverLibDoesNotExist(t *testing.T) { } func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { - temp, err := ioutil.TempDir("", "test") + temp, err := paths.MkTempDir("", "test") NoError(t, err) - defer os.RemoveAll(temp) + defer temp.RemoveAll() - NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755))) - NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755))) - NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644))) + NoError(t, temp.Join("SPI").MkdirAll()) + NoError(t, temp.Join("Bridge").MkdirAll()) + NoError(t, temp.Join("dummy_file").WriteFile([]byte{})) ctx := &types.Context{} ctx.LibrariesBuildPath = temp @@ -94,12 +94,13 @@ func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { err = cmd.Run(ctx) NoError(t, err) - _, err = os.Stat(filepath.Join(temp, "SPI")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "Bridge")) - require.Error(t, err) - require.True(t, os.IsNotExist(err)) - _, err = os.Stat(filepath.Join(temp, "dummy_file")) + exist, err := temp.Join("SPI").Exist() + require.NoError(t, err) + require.False(t, exist) + exist, err = temp.Join("Bridge").Exist() + require.NoError(t, err) + require.False(t, exist) + exist, err = temp.Join("dummy_file").Exist() NoError(t, err) + require.True(t, exist) } diff --git a/test/wipeout_build_path_if_build_options_changed_test.go b/test/wipeout_build_path_if_build_options_changed_test.go index 51bfe80d..b0498a59 100644 --- a/test/wipeout_build_path_if_build_options_changed_test.go +++ b/test/wipeout_build_path_if_build_options_changed_test.go @@ -30,14 +30,11 @@ package test import ( - "os" - "path/filepath" "testing" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/stretchr/testify/require" ) @@ -45,12 +42,12 @@ func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { ctx := &types.Context{} buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() ctx.BuildOptionsJsonPrevious = "{ \"old\":\"old\" }" ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - utils.TouchFile(filepath.Join(buildPath, "should_be_deleted.txt")) + buildPath.Join("should_be_deleted.txt").Truncate() commands := []types.Command{ &builder.WipeoutBuildPathIfBuildOptionsChanged{}, @@ -61,26 +58,28 @@ func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { NoError(t, err) } - _, err := os.Stat(buildPath) + exist, err := buildPath.Exist() NoError(t, err) + require.True(t, exist) - files, err := gohasissues.ReadDir(buildPath) + files, err := gohasissues.ReadDir(buildPath.String()) NoError(t, err) require.Equal(t, 0, len(files)) - _, err = os.Stat(filepath.Join(buildPath, "should_be_deleted.txt")) - require.Error(t, err) + exist, err = buildPath.Join("should_be_deleted.txt").Exist() + require.NoError(t, err) + require.False(t, exist) } func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing.T) { ctx := &types.Context{} buildPath := SetupBuildPath(t, ctx) - defer os.RemoveAll(buildPath) + defer buildPath.RemoveAll() ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - utils.TouchFile(filepath.Join(buildPath, "should_not_be_deleted.txt")) + require.NoError(t, buildPath.Join("should_not_be_deleted.txt").Truncate()) commands := []types.Command{ &builder.WipeoutBuildPathIfBuildOptionsChanged{}, @@ -91,13 +90,15 @@ func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing. NoError(t, err) } - _, err := os.Stat(buildPath) + exist, err := buildPath.Exist() NoError(t, err) + require.True(t, exist) - files, err := gohasissues.ReadDir(buildPath) + files, err := gohasissues.ReadDir(buildPath.String()) NoError(t, err) require.Equal(t, 1, len(files)) - _, err = os.Stat(filepath.Join(buildPath, "should_not_be_deleted.txt")) + exist, err = buildPath.Join("should_not_be_deleted.txt").Exist() NoError(t, err) + require.True(t, exist) } diff --git a/tools_loader.go b/tools_loader.go index 01284cb9..e171f8d7 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -31,19 +31,17 @@ package builder import ( "fmt" - "path/filepath" "strings" - "github.com/bcmi-labs/arduino-cli/paths" - "github.com/arduino/arduino-builder/types" + "github.com/arduino/go-paths-helper" ) type ToolsLoader struct{} func (s *ToolsLoader) Run(ctx *types.Context) error { - folders := []string{} - builtinFolders := []string{} + folders := paths.NewPathList() + builtinFolders := paths.NewPathList() if ctx.BuiltInToolsFolders != nil || len(ctx.BuiltInLibrariesFolders) == 0 { folders = ctx.ToolsFolders @@ -51,14 +49,13 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { } else { // Auto-detect built-in tools folders (for arduino-builder backward compatibility) // this is a deprecated feature and will be removed in the future - builtinHardwareFolder, err := filepath.Abs(filepath.Join(ctx.BuiltInLibrariesFolders[0], "..")) + builtinHardwareFolder, err := ctx.BuiltInLibrariesFolders[0].Join("..").Abs() if err != nil { fmt.Println("Error detecting ") } - builtinFolders = []string{} for _, folder := range ctx.ToolsFolders { - if !strings.Contains(folder, builtinHardwareFolder) { + if !strings.Contains(folder.String(), builtinHardwareFolder.String()) { // TODO: make a function to check for subfolders folders = append(folders, folder) } else { builtinFolders = append(builtinFolders, folder) @@ -67,7 +64,7 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { } pm := ctx.PackageManager - pm.LoadToolsFromBundleDirectories(paths.NewPathList(builtinFolders...)) + pm.LoadToolsFromBundleDirectories(builtinFolders) ctx.AllTools = pm.GetAllInstalledToolsReleases() diff --git a/types/context.go b/types/context.go index 6046c400..be4d1c1f 100644 --- a/types/context.go +++ b/types/context.go @@ -4,6 +4,7 @@ import ( "strings" "github.com/arduino/arduino-builder/i18n" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" @@ -13,13 +14,13 @@ import ( // Context structure type Context struct { // Build options - HardwareFolders []string - ToolsFolders []string - BuiltInToolsFolders []string - LibrariesFolders []string - BuiltInLibrariesFolders []string - OtherLibrariesFolders []string - SketchLocation string + HardwareFolders paths.PathList + ToolsFolders paths.PathList + BuiltInToolsFolders paths.PathList + LibrariesFolders paths.PathList + BuiltInLibrariesFolders paths.PathList + OtherLibrariesFolders paths.PathList + SketchLocation *paths.Path ArduinoAPIVersion string FQBN string @@ -42,17 +43,17 @@ type Context struct { BuildProperties properties.Map BuildCore string - BuildPath string - BuildCachePath string - SketchBuildPath string - CoreBuildPath string - CoreBuildCachePath string - CoreArchiveFilePath string - CoreObjectsFiles []string - LibrariesBuildPath string - LibrariesObjectFiles []string - PreprocPath string - SketchObjectFiles []string + BuildPath *paths.Path + BuildCachePath *paths.Path + SketchBuildPath *paths.Path + CoreBuildPath *paths.Path + CoreBuildCachePath *paths.Path + CoreArchiveFilePath *paths.Path + CoreObjectsFiles paths.PathList + LibrariesBuildPath *paths.Path + LibrariesObjectFiles paths.PathList + PreprocPath *paths.Path + SketchObjectFiles paths.PathList CollectedSourceFiles *UniqueSourceFileQueue @@ -68,11 +69,11 @@ type Context struct { ImportedLibraries []*libraries.Library LibrariesResolutionResults map[string]LibraryResolutionResult IncludeJustFound string - IncludeFolders []string + IncludeFolders paths.PathList // C++ Parsing CTagsOutput string - CTagsTargetFile string + CTagsTargetFile *paths.Path CTagsOfPreprocessedSource []*CTag IncludeSection string LineOffset int @@ -92,16 +93,16 @@ type Context struct { DebugLevel int // ReadFileAndStoreInContext command - FileToRead string + FileToRead *paths.Path } func (ctx *Context) ExtractBuildOptions() properties.Map { opts := make(properties.Map) - opts["hardwareFolders"] = strings.Join(ctx.HardwareFolders, ",") - opts["toolsFolders"] = strings.Join(ctx.ToolsFolders, ",") - opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesFolders, ",") - opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesFolders, ",") - opts["sketchLocation"] = ctx.SketchLocation + opts["hardwareFolders"] = strings.Join(ctx.HardwareFolders.AsStrings(), ",") + opts["toolsFolders"] = strings.Join(ctx.ToolsFolders.AsStrings(), ",") + opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesFolders.AsStrings(), ",") + opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesFolders.AsStrings(), ",") + opts["sketchLocation"] = ctx.SketchLocation.String() opts["fqbn"] = ctx.FQBN opts["runtime.ide.version"] = ctx.ArduinoAPIVersion opts["customBuildProperties"] = strings.Join(ctx.CustomBuildProperties, ",") @@ -109,11 +110,11 @@ func (ctx *Context) ExtractBuildOptions() properties.Map { } func (ctx *Context) InjectBuildOptions(opts properties.Map) { - ctx.HardwareFolders = strings.Split(opts["hardwareFolders"], ",") - ctx.ToolsFolders = strings.Split(opts["toolsFolders"], ",") - ctx.BuiltInLibrariesFolders = strings.Split(opts["builtInLibrariesFolders"], ",") - ctx.OtherLibrariesFolders = strings.Split(opts["otherLibrariesFolders"], ",") - ctx.SketchLocation = opts["sketchLocation"] + ctx.HardwareFolders = paths.NewPathList(strings.Split(opts["hardwareFolders"], ",")...) + ctx.ToolsFolders = paths.NewPathList(strings.Split(opts["toolsFolders"], ",")...) + ctx.BuiltInLibrariesFolders = paths.NewPathList(strings.Split(opts["builtInLibrariesFolders"], ",")...) + ctx.OtherLibrariesFolders = paths.NewPathList(strings.Split(opts["otherLibrariesFolders"], ",")...) + ctx.SketchLocation = paths.New(opts["sketchLocation"]) ctx.FQBN = opts["fqbn"] ctx.ArduinoAPIVersion = opts["runtime.ide.version"] ctx.CustomBuildProperties = strings.Split(opts["customBuildProperties"], ",") diff --git a/types/types.go b/types/types.go index ff74206c..55cebdd3 100644 --- a/types/types.go +++ b/types/types.go @@ -31,9 +31,9 @@ package types import ( "fmt" - "path/filepath" "strconv" + "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) @@ -41,16 +41,16 @@ type SourceFile struct { // Sketch or Library pointer that this source file lives in Origin interface{} // Path to the source file within the sketch/library root folder - RelativePath string + RelativePath *paths.Path } // Create a SourceFile containing the given source file path within the // given origin. The given path can be absolute, or relative within the // origin's root source folder -func MakeSourceFile(ctx *Context, origin interface{}, path string) (SourceFile, error) { - if filepath.IsAbs(path) { +func MakeSourceFile(ctx *Context, origin interface{}, path *paths.Path) (SourceFile, error) { + if path.IsAbs() { var err error - path, err = filepath.Rel(sourceRoot(ctx, origin), path) + path, err = sourceRoot(ctx, origin).RelTo(path) if err != nil { return SourceFile{}, err } @@ -61,12 +61,12 @@ func MakeSourceFile(ctx *Context, origin interface{}, path string) (SourceFile, // Return the build root for the given origin, where build products will // be placed. Any directories inside SourceFile.RelativePath will be // appended here. -func buildRoot(ctx *Context, origin interface{}) string { +func buildRoot(ctx *Context, origin interface{}) *paths.Path { switch o := origin.(type) { case *Sketch: return ctx.SketchBuildPath case *libraries.Library: - return filepath.Join(ctx.LibrariesBuildPath, o.Name) + return ctx.LibrariesBuildPath.Join(o.Name) default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) } @@ -75,31 +75,31 @@ func buildRoot(ctx *Context, origin interface{}) string { // Return the source root for the given origin, where its source files // can be found. Prepending this to SourceFile.RelativePath will give // the full path to that source file. -func sourceRoot(ctx *Context, origin interface{}) string { +func sourceRoot(ctx *Context, origin interface{}) *paths.Path { switch o := origin.(type) { case *Sketch: return ctx.SketchBuildPath case *libraries.Library: - return o.SrcFolder.String() + return o.SrcFolder default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) } } -func (f *SourceFile) SourcePath(ctx *Context) string { - return filepath.Join(sourceRoot(ctx, f.Origin), f.RelativePath) +func (f *SourceFile) SourcePath(ctx *Context) *paths.Path { + return sourceRoot(ctx, f.Origin).JoinPath(f.RelativePath) } -func (f *SourceFile) ObjectPath(ctx *Context) string { - return filepath.Join(buildRoot(ctx, f.Origin), f.RelativePath+".o") +func (f *SourceFile) ObjectPath(ctx *Context) *paths.Path { + return buildRoot(ctx, f.Origin).Join(f.RelativePath.String() + ".o") } -func (f *SourceFile) DepfilePath(ctx *Context) string { - return filepath.Join(buildRoot(ctx, f.Origin), f.RelativePath+".d") +func (f *SourceFile) DepfilePath(ctx *Context) *paths.Path { + return buildRoot(ctx, f.Origin).Join(f.RelativePath.String() + ".d") } type SketchFile struct { - Name string + Name *paths.Path Source string } @@ -114,7 +114,7 @@ func (s SketchFileSortByName) Swap(i, j int) { } func (s SketchFileSortByName) Less(i, j int) bool { - return s[i].Name < s[j].Name + return s[i].Name.String() < s[j].Name.String() } type Sketch struct { diff --git a/types/utils.go b/types/utils.go index a7200f0e..4016a69b 100644 --- a/types/utils.go +++ b/types/utils.go @@ -41,7 +41,7 @@ func sliceContains(slice []string, target string) bool { func sliceContainsSourceFile(slice []SourceFile, target SourceFile) bool { for _, elem := range slice { - if elem.Origin == target.Origin && elem.RelativePath == target.RelativePath { + if elem.Origin == target.Origin && elem.RelativePath.EqualsTo(target.RelativePath) { return true } } diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go index 299dc207..2599d242 100644 --- a/unused_compiled_libraries_remover.go +++ b/unused_compiled_libraries_remover.go @@ -30,10 +30,6 @@ package builder import ( - "io/ioutil" - "os" - "path/filepath" - "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" @@ -45,22 +41,20 @@ type UnusedCompiledLibrariesRemover struct{} func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { librariesBuildPath := ctx.LibrariesBuildPath - _, err := os.Stat(librariesBuildPath) - if err != nil && os.IsNotExist(err) { + if exist, _ := librariesBuildPath.Exist(); !exist { return nil } libraryNames := toLibraryNames(ctx.ImportedLibraries) - files, err := ioutil.ReadDir(librariesBuildPath) + files, err := librariesBuildPath.ReadDir() if err != nil { return i18n.WrapError(err) } for _, file := range files { - if file.IsDir() { - if !utils.SliceContains(libraryNames, file.Name()) { - err := os.RemoveAll(filepath.Join(librariesBuildPath, file.Name())) - if err != nil { + if isDir, _ := file.IsDir(); isDir { + if !utils.SliceContains(libraryNames, file.Base()) { + if err := file.RemoveAll(); err != nil { return i18n.WrapError(err) } } diff --git a/utils/utils.go b/utils/utils.go index 9b85850d..e6f69a76 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -32,7 +32,6 @@ package utils import ( "crypto/md5" "encoding/hex" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -44,6 +43,7 @@ import ( "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" + "github.com/arduino/go-paths-helper" ) func KeysOfMapOfString(input map[string]string) []string { @@ -263,17 +263,6 @@ func AbsolutizePaths(files []string) ([]string, error) { return files, nil } -func ReadFileToRows(file string) ([]string, error) { - bytes, err := ioutil.ReadFile(file) - if err != nil { - return nil, i18n.WrapError(err) - } - txt := string(bytes) - txt = strings.Replace(txt, "\r\n", "\n", -1) - - return strings.Split(txt, "\n"), nil -} - type CheckExtensionFunc func(ext string) bool func FindFilesInFolder(files *[]string, folder string, extensions CheckExtensionFunc, recurse bool) error { @@ -318,16 +307,6 @@ func FindFilesInFolder(files *[]string, folder string, extensions CheckExtension return gohasissues.Walk(folder, walkFunc) } -func GetParentFolder(basefolder string, n int) string { - tempFolder := basefolder - i := 0 - for i < n { - tempFolder = filepath.Dir(tempFolder) - i++ - } - return tempFolder -} - func AppendIfNotPresent(target []string, elements ...string) []string { for _, element := range elements { if !SliceContains(target, element) { @@ -337,29 +316,6 @@ func AppendIfNotPresent(target []string, elements ...string) []string { return target } -func EnsureFolderExists(folder string) error { - return os.MkdirAll(folder, os.FileMode(0755)) -} - -func WriteFileBytes(targetFilePath string, data []byte) error { - return ioutil.WriteFile(targetFilePath, data, os.FileMode(0644)) -} - -func WriteFile(targetFilePath string, data string) error { - return WriteFileBytes(targetFilePath, []byte(data)) -} - -func TouchFile(targetFilePath string) error { - return WriteFileBytes(targetFilePath, []byte{}) -} - -func NULLFile() string { - if runtime.GOOS == "windows" { - return "nul" - } - return "/dev/null" -} - func MD5Sum(data []byte) string { md5sumBytes := md5.Sum(data) return hex.EncodeToString(md5sumBytes[:]) @@ -392,6 +348,10 @@ func QuoteCppString(str string) string { return "\"" + str + "\"" } +func QuoteCppPath(path *paths.Path) string { + return QuoteCppString(path.String()) +} + // Parse a C-preprocessor string as emitted by the preprocessor. This // is a string contained in double quotes, with any backslashes or // quotes escaped with a backslash. If a valid string was present at the diff --git a/wipeout_build_path_if_build_options_changed.go b/wipeout_build_path_if_build_options_changed.go index 0764345d..09f73381 100644 --- a/wipeout_build_path_if_build_options_changed.go +++ b/wipeout_build_path_if_build_options_changed.go @@ -31,7 +31,6 @@ package builder import ( "encoding/json" - "os" "path/filepath" "github.com/arduino/arduino-builder/builder_utils" @@ -39,7 +38,6 @@ import ( "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-properties-map" ) @@ -64,29 +62,32 @@ func (s *WipeoutBuildPathIfBuildOptionsChanged) Run(ctx *types.Context) error { delete(prevOpts, "sketchLocation") } - // check if any of the files contained in the core folders has changed - // since the json was generated - like platform.txt or similar - // if so, trigger a "safety" wipe - buildProperties := ctx.BuildProperties - targetCoreFolder := buildProperties[constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH] - coreFolder := buildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH] - realCoreFolder := utils.GetParentFolder(coreFolder, 2) - jsonPath := filepath.Join(ctx.BuildPath, constants.BUILD_OPTIONS_FILE) - coreHasChanged := builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, jsonPath) + // If options are not changed check if core has + if opts.Equals(prevOpts) { + // check if any of the files contained in the core folders has changed + // since the json was generated - like platform.txt or similar + // if so, trigger a "safety" wipe + buildProperties := ctx.BuildProperties + targetCoreFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH) + coreFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_CORE_PATH) + realCoreFolder := coreFolder.Parent().Parent() + jsonPath := ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE) + coreHasChanged := builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, jsonPath) - if opts.Equals(prevOpts) && !coreHasChanged { - return nil + if !coreHasChanged { + return nil + } } logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_BUILD_OPTIONS_CHANGED) buildPath := ctx.BuildPath - files, err := gohasissues.ReadDir(buildPath) + files, err := gohasissues.ReadDir(buildPath.String()) if err != nil { return i18n.WrapError(err) } for _, file := range files { - os.RemoveAll(filepath.Join(buildPath, file.Name())) + buildPath.Join(file.Name()).RemoveAll() } return nil From f06377e8caf91954eaa3531219664c87c1534f21 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 7 Jun 2018 14:57:06 +0200 Subject: [PATCH 21/57] Moved function LoadLibrariesFromDir to arduino-cli --- libraries_loader.go | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index 9a272e9b..4cb59f56 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -46,8 +46,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { if err := builtInLibrariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - sortedLibrariesFolders := paths.NewPathList() - sortedLibrariesFolders.AddAllMissing(builtInLibrariesFolders) + sortedLibrariesFolders := builtInLibrariesFolders.Clone() platform := ctx.TargetPlatform debugLevel := ctx.DebugLevel @@ -76,25 +75,21 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { var libs []*libraries.Library for _, libraryFolder := range sortedLibrariesFolders { - subFolders, err := utils.ReadDirFiltered(libraryFolder.String(), utils.FilterDirs) + libsInFolder, err := libraries.LoadLibrariesFromDir(libraryFolder) if err != nil { return i18n.WrapError(err) } - for _, subFolder := range subFolders { - library, err := libraries.Load(libraryFolder.Join(subFolder.Name())) - if debugLevel > 0 { - if warnings, err := library.Lint(); err != nil { - return i18n.WrapError(err) - } else { - for _, warning := range warnings { - logger.Fprintln(os.Stdout, "warn", warning) - } - } - } + libs = append(libs, libsInFolder...) + } + if debugLevel > 0 { + for _, lib := range libs { + warnings, err := lib.Lint() if err != nil { return i18n.WrapError(err) } - libs = append(libs, library) + for _, warning := range warnings { + logger.Fprintln(os.Stdout, "warn", warning) + } } } From c40beca10eb126356bf5a044653956568519a489 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 7 Jun 2018 16:50:18 +0200 Subject: [PATCH 22/57] Sligthly improved WarnAboutArchIncompatibleLibraries --- warn_about_arch_incompatible_libraries.go | 27 +++++++---------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go index 482d8468..d07769f8 100644 --- a/warn_about_arch_incompatible_libraries.go +++ b/warn_about_arch_incompatible_libraries.go @@ -48,30 +48,19 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { buildProperties := ctx.BuildProperties logger := ctx.GetLogger() - archs := []string{} - archs = append(archs, targetPlatform.Platform.Architecture) - - if buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK] != constants.EMPTY_STRING { - overrides := strings.Split(buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK], ",") - for _, override := range overrides { - archs = append(archs, override) - } + archs := []string{targetPlatform.Platform.Architecture} + if overrides, ok := buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK]; ok { + archs = append(archs, strings.Split(overrides, ",")...) } for _, importedLibrary := range ctx.ImportedLibraries { - if !importedLibrary.SupportsArchitectures(archs) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, importedLibrary.Name, sliceToCommaSeparatedString(importedLibrary.Architectures), sliceToCommaSeparatedString(archs)) + if !importedLibrary.SupportsAnyArchitectureIn(archs) { + logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, + importedLibrary.Name, + strings.Join(importedLibrary.Architectures, ", "), + strings.Join(archs, ", ")) } } return nil } - -func sliceToCommaSeparatedString(slice []string) string { - str := "(" - str = str + slice[0] - for i := 1; i < len(slice); i++ { - str = str + ", " + slice[i] - } - return str + ")" -} From b796399dfc3f411118deccb8001dc7a57363ac55 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 8 Jun 2018 16:44:00 +0200 Subject: [PATCH 23/57] Slightly improved library loader --- libraries_loader.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index 4cb59f56..4c9c4fb2 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -34,8 +34,6 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) @@ -48,21 +46,19 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } sortedLibrariesFolders := builtInLibrariesFolders.Clone() + actualPlatform := ctx.ActualPlatform platform := ctx.TargetPlatform debugLevel := ctx.DebugLevel logger := ctx.GetLogger() - actualPlatform := ctx.ActualPlatform if actualPlatform != platform { - actualPlatformLibDir := paths.New(actualPlatform.Folder).Join("libraries") - if isDir, _ := actualPlatformLibDir.IsDir(); isDir { - sortedLibrariesFolders.Add(actualPlatformLibDir) + if dir := actualPlatform.GetLibrariesDir(); dir != nil { + sortedLibrariesFolders.Add(dir) } } - platformLibDir := paths.New(platform.Folder).Join("libraries") - if isDir, _ := platformLibDir.IsDir(); isDir { - sortedLibrariesFolders.Add(platformLibDir) + if dir := platform.GetLibrariesDir(); dir != nil { + sortedLibrariesFolders.Add(dir) } librariesFolders := ctx.OtherLibrariesFolders @@ -97,12 +93,13 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { headerToLibraries := make(map[string][]*libraries.Library) for _, library := range libs { - headers, err := utils.ReadDirFiltered(library.SrcFolder.String(), utils.FilterFilesWithExtensions(".h", ".hpp", ".hh")) + headers, err := library.SrcFolder.ReadDir() if err != nil { return i18n.WrapError(err) } + headers.FilterSuffix(".h", ".hpp", ".hh") for _, header := range headers { - headerFileName := header.Name() + headerFileName := header.Base() headerToLibraries[headerFileName] = append(headerToLibraries[headerFileName], library) } } From 81d2e00e1af9b45433b616c8b08f2c8a08882a03 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 11 Jun 2018 17:40:18 +0200 Subject: [PATCH 24/57] Using FQBN facilities from arduino-cli --- arduino-builder/main.go | 13 ++-- create_build_options_map.go | 2 +- grpc/rpc.go | 13 +++- prototypes_adder.go | 2 +- setup_build_properties.go | 2 +- target_board_resolver.go | 69 +++---------------- ...dd_build_board_property_if_missing_test.go | 11 ++- test/builder_test.go | 32 ++++----- test/create_build_options_map_test.go | 4 +- test/ctags_runner_test.go | 10 +-- test/i18n_test.go | 2 +- test/includes_to_include_folders_test.go | 16 ++--- test/libraries_loader_test.go | 8 +-- test/load_vid_pid_specific_properties_test.go | 4 +- test/merge_sketch_with_bootloader_test.go | 8 +-- test/prototypes_adder_test.go | 40 +++++------ test/setup_build_properties_test.go | 8 +-- test/store_build_options_map_test.go | 4 +- test/target_board_resolver_test.go | 12 ++-- test/try_build_of_problematic_sketch_test.go | 8 +-- types/context.go | 10 ++- 21 files changed, 126 insertions(+), 152 deletions(-) diff --git a/arduino-builder/main.go b/arduino-builder/main.go index 15869c9c..f40225c2 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -51,6 +51,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" + "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/go-errors/errors" ) @@ -296,12 +297,16 @@ func main() { } // FLAG_FQBN - if fqbn, err := gohasissues.Unquote(*fqbnFlag); err != nil { + if fqbnIn, err := gohasissues.Unquote(*fqbnFlag); err != nil { printCompleteError(err) - } else if fqbn != "" { - ctx.FQBN = fqbn + } else if fqbnIn != "" { + if fqbn, err := cores.ParseFQBN(fqbnIn); err != nil { + printCompleteError(err) + } else { + ctx.FQBN = fqbn + } } - if ctx.FQBN == "" { + if ctx.FQBN == nil { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_FQBN + "' is mandatory")) } diff --git a/create_build_options_map.go b/create_build_options_map.go index 490a2188..0a11cc29 100644 --- a/create_build_options_map.go +++ b/create_build_options_map.go @@ -30,9 +30,9 @@ package builder import ( + "encoding/json" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "encoding/json" ) type CreateBuildOptionsMap struct{} diff --git a/grpc/rpc.go b/grpc/rpc.go index 33a03ddc..9538dbf8 100644 --- a/grpc/rpc.go +++ b/grpc/rpc.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/arduino/go-paths-helper" + "github.com/bcmi-labs/arduino-cli/arduino/cores" builder "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/i18n" @@ -89,7 +90,11 @@ func (s *builderServer) Autocomplete(ctx context.Context, args *pb.BuildParams) s.ctx.SketchLocation = paths.New(args.SketchLocation) s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - s.ctx.FQBN = args.FQBN + if fqbn, err := cores.ParseFQBN(args.FQBN); err != nil { + return nil, fmt.Errorf("parsing fqbn: %s", err) + } else { + s.ctx.FQBN = fqbn + } s.ctx.Verbose = false //p.Verbose s.ctx.BuildCachePath = paths.New(args.BuildCachePath) s.ctx.BuildPath = paths.New(args.BuildPath) @@ -129,7 +134,11 @@ func (s *builderServer) Build(args *pb.BuildParams, stream pb.Builder_BuildServe s.ctx.SketchLocation = paths.New(args.SketchLocation) s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - s.ctx.FQBN = args.FQBN + if fqbn, err := cores.ParseFQBN(args.FQBN); err != nil { + return fmt.Errorf("parsing fqbn: %s", err) + } else { + s.ctx.FQBN = fqbn + } s.ctx.Verbose = args.Verbose s.ctx.BuildCachePath = paths.New(args.BuildCachePath) s.ctx.BuildPath = paths.New(args.BuildPath) diff --git a/prototypes_adder.go b/prototypes_adder.go index db283519..91a7eb63 100644 --- a/prototypes_adder.go +++ b/prototypes_adder.go @@ -30,10 +30,10 @@ package builder import ( + "fmt" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "fmt" "strconv" "strings" ) diff --git a/setup_build_properties.go b/setup_build_properties.go index 99535ff3..c1059776 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -79,7 +79,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties["runtime.hardware.path"] = filepath.Join(targetPlatform.Folder, "..") buildProperties["runtime.ide.version"] = ctx.ArduinoAPIVersion buildProperties["runtime.ide.path"] = exPath - buildProperties["build.fqbn"] = ctx.FQBN + buildProperties["build.fqbn"] = ctx.FQBN.String() buildProperties["ide_version"] = ctx.ArduinoAPIVersion buildProperties["runtime.os"] = utils.PrettyOSName() diff --git a/target_board_resolver.go b/target_board_resolver.go index 0010c59f..13eaaa1d 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -35,7 +35,6 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type TargetBoardResolver struct{} @@ -43,71 +42,19 @@ type TargetBoardResolver struct{} func (s *TargetBoardResolver) Run(ctx *types.Context) error { logger := ctx.GetLogger() - fqbn := ctx.FQBN - - fqbnParts := strings.Split(fqbn, ":") - if len(fqbnParts) < 3 { - return i18n.ErrorfWithLogger(logger, constants.MSG_FQBN_INVALID, fqbn) - } - targetPackageName := fqbnParts[0] - targetPlatformName := fqbnParts[1] - targetBoardName := fqbnParts[2] - - packages := ctx.Hardware - - targetPackage := packages.Packages[targetPackageName] - if targetPackage == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_PACKAGE_UNKNOWN, targetPackageName) - } - - targetPlatforms := targetPackage.Platforms[targetPlatformName] - if targetPlatforms == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) - } - targetPlatform := targetPlatforms.GetInstalled() - if targetPlatform == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_PLATFORM_UNKNOWN, targetPlatformName, targetPackageName) - } - - targetBoard := targetPlatform.Boards[targetBoardName] - if targetBoard == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_BOARD_UNKNOWN, targetBoardName, targetPlatformName, targetPackageName) + targetPackage, targetPlatform, targetBoard, buildProperties, actualPlatform, err := ctx.PackageManager.ResolveFQBN(ctx.FQBN) + if err != nil { + return i18n.ErrorfWithLogger(logger, "Error resolving FQBN: {0}", err) } - ctx.TargetPlatform = targetPlatform - ctx.TargetPackage = targetPackage - ctx.TargetBoard = targetBoard - - if len(fqbnParts) > 3 { - if props, err := targetBoard.GeneratePropertiesForConfiguration(fqbnParts[3]); err != nil { - i18n.ErrorfWithLogger(logger, "Error in FQBN: %s", err) - } else { - targetBoard.Properties = props - } - } + targetBoard.Properties = buildProperties // FIXME.... core := targetBoard.Properties["build.core"] if core == "" { core = "arduino" } - - var corePlatform *cores.PlatformRelease - coreParts := strings.Split(core, ":") - if len(coreParts) > 1 { - core = coreParts[1] - if packages.Packages[coreParts[0]] == nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_MISSING_CORE_FOR_BOARD, coreParts[0]) - - } - corePlatform = packages.Packages[coreParts[0]].Platforms[targetPlatforms.Architecture].GetInstalled() - } - - var actualPlatform *cores.PlatformRelease - if corePlatform != nil { - actualPlatform = corePlatform - } else { - actualPlatform = targetPlatform - } + // select the core name in case of "package:core" format + core = core[strings.Index(core, ":")+1:] if ctx.Verbose { logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Folder) @@ -115,7 +62,9 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { } ctx.BuildCore = core + ctx.TargetBoard = targetBoard + ctx.TargetPlatform = targetPlatform + ctx.TargetPackage = targetPackage ctx.ActualPlatform = actualPlatform - return nil } diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index 9fa49e45..52011d8b 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -34,6 +34,7 @@ import ( "testing" "github.com/arduino/go-paths-helper" + "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" @@ -41,12 +42,18 @@ import ( "github.com/stretchr/testify/require" ) +func parseFQBN(t *testing.T, fqbnIn string) *cores.FQBN { + fqbn, err := cores.ParseFQBN(fqbnIn) + require.NoError(t, err) + return fqbn +} + func TestAddBuildBoardPropertyIfMissing(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: "my_avr_platform:avr:mymega", + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega"), } commands := []types.Command{ @@ -77,7 +84,7 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), } commands := []types.Command{ diff --git a/test/builder_test.go b/test/builder_test.go index f40600ae..061f1624 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -44,10 +44,10 @@ import ( "github.com/stretchr/testify/require" ) -func prepareBuilderTestContext(sketchPath *paths.Path, fqbn string) *types.Context { +func prepareBuilderTestContext(t *testing.T, sketchPath *paths.Path, fqbn string) *types.Context { return &types.Context{ SketchLocation: sketchPath, - FQBN: fqbn, + FQBN: parseFQBN(t, fqbn), HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), @@ -60,7 +60,7 @@ func prepareBuilderTestContext(sketchPath *paths.Path, fqbn string) *types.Conte func TestBuilderEmptySketch(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") ctx.DebugLevel = 10 buildPath := SetupBuildPath(t, ctx) @@ -91,7 +91,7 @@ func TestBuilderEmptySketch(t *testing.T) { func TestBuilderBridge(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -124,7 +124,7 @@ func TestBuilderBridge(t *testing.T) { func TestBuilderSketchWithConfig(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(t, paths.New("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -157,7 +157,7 @@ func TestBuilderSketchWithConfig(t *testing.T) { func TestBuilderBridgeTwice(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -195,7 +195,7 @@ func TestBuilderBridgeTwice(t *testing.T) { func TestBuilderBridgeSAM(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") + ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") ctx.WarningsLevel = "all" buildPath := SetupBuildPath(t, ctx) @@ -240,7 +240,7 @@ func TestBuilderBridgeSAM(t *testing.T) { func TestBuilderBridgeRedBearLab(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") + ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) @@ -275,7 +275,7 @@ func TestBuilderBridgeRedBearLab(t *testing.T) { func TestBuilderSketchNoFunctions(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") + ctx := prepareBuilderTestContext(t, paths.New("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) @@ -291,7 +291,7 @@ func TestBuilderSketchNoFunctions(t *testing.T) { func TestBuilderSketchWithBackup(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) @@ -307,7 +307,7 @@ func TestBuilderSketchWithBackup(t *testing.T) { func TestBuilderSketchWithOldLib(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -321,7 +321,7 @@ func TestBuilderSketchWithOldLib(t *testing.T) { func TestBuilderSketchWithSubfolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -335,7 +335,7 @@ func TestBuilderSketchWithSubfolders(t *testing.T) { func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") + ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -358,7 +358,7 @@ func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testin func TestBuilderWithBuildPathInSketchDir(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") var err error ctx.BuildPath, err = paths.New("sketch1", "build").Abs() @@ -379,7 +379,7 @@ func TestBuilderWithBuildPathInSketchDir(t *testing.T) { func TestBuilderCacheCoreAFile(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) - ctx := prepareBuilderTestContext(paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") + ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") SetupBuildPath(t, ctx) defer ctx.BuildPath.RemoveAll() @@ -393,7 +393,7 @@ func TestBuilderCacheCoreAFile(t *testing.T) { // Pick timestamp of cached core coreFolder := paths.New("downloaded_hardware", "arduino", "avr") - coreFileName := builder_utils.GetCachedCoreArchiveFileName(ctx.FQBN, coreFolder) + coreFileName := builder_utils.GetCachedCoreArchiveFileName(ctx.FQBN.String(), coreFolder) cachedCoreFile := ctx.CoreBuildCachePath.Join(coreFileName) coreStatBefore, err := cachedCoreFile.Stat() require.NoError(t, err) diff --git a/test/create_build_options_map_test.go b/test/create_build_options_map_test.go index 78c8001e..beebd1df 100644 --- a/test/create_build_options_map_test.go +++ b/test/create_build_options_map_test.go @@ -44,7 +44,7 @@ func TestCreateBuildOptionsMap(t *testing.T) { ToolsFolders: paths.NewPathList("tools"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketchLocation"), - FQBN: "fqbn", + FQBN: parseFQBN(t, "my:nice:fqbn"), ArduinoAPIVersion: "ideVersion", Verbose: true, BuildPath: paths.New("buildPath"), @@ -59,7 +59,7 @@ func TestCreateBuildOptionsMap(t *testing.T) { " \"additionalFiles\": \"\",\n"+ " \"builtInLibrariesFolders\": \"\",\n"+ " \"customBuildProperties\": \"\",\n"+ - " \"fqbn\": \"fqbn\",\n"+ + " \"fqbn\": \"my:nice:fqbn\",\n"+ " \"hardwareFolders\": \"hardware,hardware2\",\n"+ " \"otherLibrariesFolders\": \"libraries\",\n"+ " \"runtime.ide.version\": \"ideVersion\",\n"+ diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go index 8a6703ce..c1516b8e 100644 --- a/test/ctags_runner_test.go +++ b/test/ctags_runner_test.go @@ -51,7 +51,7 @@ func TestCTagsRunner(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -101,7 +101,7 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -149,7 +149,7 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -196,7 +196,7 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -242,7 +242,7 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } diff --git a/test/i18n_test.go b/test/i18n_test.go index 7dfb8d4b..dbfae0d3 100644 --- a/test/i18n_test.go +++ b/test/i18n_test.go @@ -30,9 +30,9 @@ package test import ( + "fmt" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" - "fmt" "github.com/stretchr/testify/require" "testing" ) diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index a89b21b4..24c71deb 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -50,7 +50,7 @@ func TestIncludesToIncludeFolders(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -86,7 +86,7 @@ func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -121,7 +121,7 @@ func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch9", "sketch.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -159,7 +159,7 @@ func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch10", "sketch.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -196,7 +196,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -234,7 +234,7 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -272,7 +272,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch_usbhost", "sketch_usbhost.ino"), - FQBN: "arduino:samd:arduino_zero_native", + FQBN: parseFQBN(t, "arduino:samd:arduino_zero_native"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -310,7 +310,7 @@ func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index c02bc537..e71e0a0d 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -48,7 +48,7 @@ func TestLoadLibrariesAVR(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), } commands := []types.Command{ @@ -157,7 +157,7 @@ func TestLoadLibrariesSAM(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: "arduino:sam:arduino_due_x_dbg", + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), } commands := []types.Command{ @@ -240,7 +240,7 @@ func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), } commands := []types.Command{ @@ -269,7 +269,7 @@ func TestLoadLibrariesMyAVRPlatform(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), } commands := []types.Command{ diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go index 67348b5f..efbc6812 100644 --- a/test/load_vid_pid_specific_properties_test.go +++ b/test/load_vid_pid_specific_properties_test.go @@ -46,7 +46,7 @@ func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:micro", + FQBN: parseFQBN(t, "arduino:avr:micro"), ArduinoAPIVersion: "10600", } @@ -76,7 +76,7 @@ func TestLoadVIDPIDSpecificProperties(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:micro", + FQBN: parseFQBN(t, "arduino:avr:micro"), ArduinoAPIVersion: "10600", } diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go index 59e6f0e0..976510b6 100644 --- a/test/merge_sketch_with_bootloader_test.go +++ b/test/merge_sketch_with_bootloader_test.go @@ -50,7 +50,7 @@ func TestMergeSketchWithBootloader(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", } @@ -92,7 +92,7 @@ func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", } @@ -134,7 +134,7 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", } @@ -172,7 +172,7 @@ func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:mymega:cpu=atmega2560", + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), ArduinoAPIVersion: "10600", } diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go index 0473e245..8e3e125e 100644 --- a/test/prototypes_adder_test.go +++ b/test/prototypes_adder_test.go @@ -54,7 +54,7 @@ func TestPrototypesAdderBridgeExample(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -96,7 +96,7 @@ func TestPrototypesAdderSketchWithIfDef(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -136,7 +136,7 @@ func TestPrototypesAdderBaladuino(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch3", "Baladuino.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -176,7 +176,7 @@ func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch4", "CharWithEscapedDoubleQuote.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -216,7 +216,7 @@ func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch5", "IncludeBetweenMultilineComment.ino"), - FQBN: "arduino:sam:arduino_due_x_dbg", + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -256,7 +256,7 @@ func TestPrototypesAdderLineContinuations(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch6", "/LineContinuations.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -296,7 +296,7 @@ func TestPrototypesAdderStringWithComment(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch7", "StringWithComment.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -336,7 +336,7 @@ func TestPrototypesAdderSketchWithStruct(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch8", "SketchWithStruct.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -384,7 +384,7 @@ func TestPrototypesAdderSketchWithConfig(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -430,7 +430,7 @@ func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch_no_functions_two_files", "main.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -470,7 +470,7 @@ func TestPrototypesAdderSketchNoFunctions(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketch_no_functions", "main.ino"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -516,7 +516,7 @@ func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -559,7 +559,7 @@ func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -613,7 +613,7 @@ func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -656,7 +656,7 @@ func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { OtherLibrariesFolders: paths.NewPathList("libraries"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -698,7 +698,7 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { LibrariesFolders: paths.NewPathList("libraries", "downloaded_libraries"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -747,7 +747,7 @@ func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:yun", + FQBN: parseFQBN(t, "arduino:avr:yun"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -793,7 +793,7 @@ func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:sam:arduino_due_x_dbg", + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -839,7 +839,7 @@ func TestPrototypesAdderSketchWithConst(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: sketchLocation, - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", Verbose: true, } @@ -879,7 +879,7 @@ func TestPrototypesAdderSketchWithDosEol(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("eol_processing", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", Verbose: true, } diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index 6e172f40..a1334638 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -47,7 +47,7 @@ func TestSetupBuildProperties(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", } @@ -113,7 +113,7 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), ArduinoAPIVersion: "10600", CustomBuildProperties: []string{"name=fake name", "tools.avrdude.config.path=non existent path with space and a ="}, @@ -154,7 +154,7 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), ArduinoAPIVersion: "10600", } @@ -192,7 +192,7 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), ArduinoAPIVersion: "10600", } diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go index 2298e123..c04cbc76 100644 --- a/test/store_build_options_map_test.go +++ b/test/store_build_options_map_test.go @@ -46,7 +46,7 @@ func TestStoreBuildOptionsMap(t *testing.T) { BuiltInLibrariesFolders: paths.NewPathList("built-in libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), SketchLocation: paths.New("sketchLocation"), - FQBN: "fqbn", + FQBN: parseFQBN(t, "my:nice:fqbn"), ArduinoAPIVersion: "ideVersion", CustomBuildProperties: []string{"custom=prop"}, Verbose: true, @@ -77,7 +77,7 @@ func TestStoreBuildOptionsMap(t *testing.T) { " \"additionalFiles\": \"\",\n"+ " \"builtInLibrariesFolders\": \"built-in libraries\",\n"+ " \"customBuildProperties\": \"custom=prop\",\n"+ - " \"fqbn\": \"fqbn\",\n"+ + " \"fqbn\": \"my:nice:fqbn\",\n"+ " \"hardwareFolders\": \"hardware\",\n"+ " \"otherLibrariesFolders\": \"libraries\",\n"+ " \"runtime.ide.version\": \"ideVersion\",\n"+ diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index 06f1a245..acf3a462 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -42,7 +42,7 @@ import ( func TestTargetBoardResolverUno(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: "arduino:avr:uno", + FQBN: parseFQBN(t, "arduino:avr:uno"), } commands := []types.Command{ @@ -67,7 +67,7 @@ func TestTargetBoardResolverUno(t *testing.T) { func TestTargetBoardResolverDue(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: "arduino:sam:arduino_due_x", + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x"), } commands := []types.Command{ @@ -92,7 +92,7 @@ func TestTargetBoardResolverDue(t *testing.T) { func TestTargetBoardResolverMega1280(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: "arduino:avr:mega:cpu=atmega1280", + FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega1280"), } commands := []types.Command{ @@ -118,7 +118,7 @@ func TestTargetBoardResolverMega1280(t *testing.T) { func TestTargetBoardResolverMega2560(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: "arduino:avr:mega:cpu=atmega2560", + FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega2560"), } commands := []types.Command{ @@ -144,7 +144,7 @@ func TestTargetBoardResolverMega2560(t *testing.T) { func TestTargetBoardResolverCustomYun(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: "my_avr_platform:avr:custom_yun", + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), } commands := []types.Command{ @@ -170,7 +170,7 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { func TestTargetBoardResolverCustomCore(t *testing.T) { ctx := &types.Context{ HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: "watterott:avr:attiny841:core=spencekonde,info=info", + FQBN: parseFQBN(t, "watterott:avr:attiny841:core=spencekonde,info=info"), } commands := []types.Command{ diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go index 0b05a22c..a1a9f574 100644 --- a/test/try_build_of_problematic_sketch_test.go +++ b/test/try_build_of_problematic_sketch_test.go @@ -129,7 +129,7 @@ func TestTryBuild021(t *testing.T) { func TestTryBuild022(t *testing.T) { ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" + ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") tryBuildWithContext(t, ctx, "sketch_usbhost", "sketch_usbhost.ino") } @@ -188,7 +188,7 @@ func TestTryBuild035(t *testing.T) { func TestTryBuild036(t *testing.T) { ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" + ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") tryBuildWithContext(t, ctx, "sketch11", "sketch_fastleds.ino") } @@ -202,7 +202,7 @@ func TestTryBuild038(t *testing.T) { func TestTryBuild039(t *testing.T) { ctx := makeDefaultContext(t) - ctx.FQBN = "arduino:samd:arduino_zero_native" + ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") tryBuildWithContext(t, ctx, "sketch12", "sketch12.ino") } @@ -226,7 +226,7 @@ func makeDefaultContext(t *testing.T) *types.Context { BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: "arduino:avr:leonardo", + FQBN: parseFQBN(t, "arduino:avr:leonardo"), ArduinoAPIVersion: "10607", Verbose: true, DebugPreprocessor: true, diff --git a/types/context.go b/types/context.go index 34bfde22..1a164be1 100644 --- a/types/context.go +++ b/types/context.go @@ -29,7 +29,7 @@ type Context struct { SketchLocation *paths.Path WatchedLocations paths.PathList ArduinoAPIVersion string - FQBN string + FQBN *cores.FQBN CodeCompleteAt string // Build options are serialized here @@ -129,7 +129,7 @@ func (ctx *Context) ExtractBuildOptions() properties.Map { additionalFilesRelative = append(additionalFilesRelative, relPath.String()) } } - opts["fqbn"] = ctx.FQBN + opts["fqbn"] = ctx.FQBN.String() opts["runtime.ide.version"] = ctx.ArduinoAPIVersion opts["customBuildProperties"] = strings.Join(ctx.CustomBuildProperties, ",") opts["additionalFiles"] = strings.Join(additionalFilesRelative, ",") @@ -142,7 +142,11 @@ func (ctx *Context) InjectBuildOptions(opts properties.Map) { ctx.BuiltInLibrariesFolders = paths.NewPathList(strings.Split(opts["builtInLibrariesFolders"], ",")...) ctx.OtherLibrariesFolders = paths.NewPathList(strings.Split(opts["otherLibrariesFolders"], ",")...) ctx.SketchLocation = paths.New(opts["sketchLocation"]) - ctx.FQBN = opts["fqbn"] + fqbn, err := cores.ParseFQBN(opts["fqbn"]) + if err != nil { + i18n.ErrorfWithLogger(ctx.GetLogger(), "Error in FQBN: %s", err) + } + ctx.FQBN = fqbn ctx.ArduinoAPIVersion = opts["runtime.ide.version"] ctx.CustomBuildProperties = strings.Split(opts["customBuildProperties"], ",") } From e82d0725fbee6f1528426949202902d0c7aa74e5 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 2 Jul 2018 16:52:02 +0200 Subject: [PATCH 25/57] Use librarymanager to handle libraries loading --- libraries_loader.go | 46 ++++++++++++++++--------------- test/libraries_loader_test.go | 51 ++++++++++++++++++++++++----------- types/context.go | 4 ++- 3 files changed, 63 insertions(+), 38 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index 4c9c4fb2..96ca7c8e 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -32,6 +32,8 @@ package builder import ( "os" + "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" + "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/bcmi-labs/arduino-cli/arduino/libraries" @@ -69,38 +71,40 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { ctx.LibrariesFolders = sortedLibrariesFolders - var libs []*libraries.Library + lm := librariesmanager.NewLibraryManager() for _, libraryFolder := range sortedLibrariesFolders { - libsInFolder, err := libraries.LoadLibrariesFromDir(libraryFolder) - if err != nil { + if err := lm.LoadLibrariesFromDir(libraryFolder); err != nil { return i18n.WrapError(err) } - libs = append(libs, libsInFolder...) } if debugLevel > 0 { - for _, lib := range libs { - warnings, err := lib.Lint() - if err != nil { - return i18n.WrapError(err) - } - for _, warning := range warnings { - logger.Fprintln(os.Stdout, "warn", warning) + for _, lib := range lm.Libraries { + for _, libAlt := range lib.Alternatives { + warnings, err := libAlt.Lint() + if err != nil { + return i18n.WrapError(err) + } + for _, warning := range warnings { + logger.Fprintln(os.Stdout, "warn", warning) + } } } } - ctx.Libraries = libs + ctx.LibrariesManager = lm headerToLibraries := make(map[string][]*libraries.Library) - for _, library := range libs { - headers, err := library.SrcFolder.ReadDir() - if err != nil { - return i18n.WrapError(err) - } - headers.FilterSuffix(".h", ".hpp", ".hh") - for _, header := range headers { - headerFileName := header.Base() - headerToLibraries[headerFileName] = append(headerToLibraries[headerFileName], library) + for _, lib := range lm.Libraries { + for _, library := range lib.Alternatives { + headers, err := library.SrcFolder.ReadDir() + if err != nil { + return i18n.WrapError(err) + } + headers.FilterSuffix(".h", ".hpp", ".hh") + for _, header := range headers { + headerFileName := header.Base() + headerToLibraries[headerFileName] = append(headerToLibraries[headerFileName], library) + } } } diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index e71e0a0d..841e88ec 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -38,9 +38,19 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" paths "github.com/arduino/go-paths-helper" + "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/stretchr/testify/require" ) +func extractLibraries(ctx *types.Context) []*libraries.Library { + res := []*libraries.Library{} + for _, lib := range ctx.LibrariesManager.Libraries { + for _, libAlternative := range lib.Alternatives { + res = append(res, libAlternative) + } + } + return res +} func TestLoadLibrariesAVR(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) @@ -69,7 +79,7 @@ func TestLoadLibrariesAVR(t *testing.T) { require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) - libs := ctx.Libraries + libs := extractLibraries(ctx) require.Equal(t, 24, len(libs)) sort.Sort(ByLibraryName(libs)) @@ -134,18 +144,24 @@ func TestLoadLibrariesAVR(t *testing.T) { headerToLibraries := ctx.HeaderToLibraries require.Equal(t, 2, len(headerToLibraries["Audio.h"])) - require.Equal(t, "Audio", headerToLibraries["Audio.h"][0].Name) - require.Equal(t, "FakeAudio", headerToLibraries["Audio.h"][1].Name) - require.Equal(t, 1, len(headerToLibraries["FakeAudio.h"])) + + libs = headerToLibraries["Audio.h"] + require.Len(t, libs, 2) + sort.Sort(ByLibraryName(libs)) + require.Equal(t, "Audio", libs[0].Name) + require.Equal(t, "FakeAudio", libs[1].Name) + + require.Len(t, headerToLibraries["FakeAudio.h"], 1) require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) - require.Equal(t, 1, len(headerToLibraries["Adafruit_PN532.h"])) + + require.Len(t, headerToLibraries["Adafruit_PN532.h"], 1) require.Equal(t, "Adafruit_PN532", headerToLibraries["Adafruit_PN532.h"][0].Name) - require.Equal(t, 2, len(headerToLibraries["IRremote.h"])) + require.Len(t, headerToLibraries["IRremote.h"], 2) libs = headerToLibraries["IRremote.h"] + require.Len(t, libs, 2) sort.Sort(ByLibraryName(libs)) - require.Equal(t, "IRremote", libs[0].Name) require.Equal(t, "Robot_IR_Remote", libs[1].Name) } @@ -178,7 +194,7 @@ func TestLoadLibrariesSAM(t *testing.T) { require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "sam", "libraries")).EquivalentTo(librariesFolders[1])) require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) - libraries := ctx.Libraries + libraries := extractLibraries(ctx) require.Equal(t, 22, len(libraries)) sort.Sort(ByLibraryName(libraries)) @@ -220,17 +236,20 @@ func TestLoadLibrariesSAM(t *testing.T) { headerToLibraries := ctx.HeaderToLibraries - require.Equal(t, 2, len(headerToLibraries["Audio.h"])) - libraries = headerToLibraries["Audio.h"] - sort.Sort(ByLibraryName(libraries)) - require.Equal(t, "Audio", libraries[0].Name) - require.Equal(t, "FakeAudio", libraries[1].Name) + libs := headerToLibraries["Audio.h"] + require.Len(t, libs, 2) + sort.Sort(ByLibraryName(libs)) + require.Equal(t, "Audio", libs[0].Name) + require.Equal(t, "FakeAudio", libs[1].Name) require.Equal(t, 1, len(headerToLibraries["FakeAudio.h"])) require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) - require.Equal(t, 2, len(headerToLibraries["IRremote.h"])) - require.Equal(t, "Robot_IR_Remote", headerToLibraries["IRremote.h"][0].Name) - require.Equal(t, "IRremote", headerToLibraries["IRremote.h"][1].Name) + + libs = headerToLibraries["IRremote.h"] + require.Len(t, libs, 2) + sort.Sort(ByLibraryName(libs)) + require.Equal(t, "IRremote", libs[0].Name) + require.Equal(t, "Robot_IR_Remote", libs[1].Name) } func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { diff --git a/types/context.go b/types/context.go index 1a164be1..1a65d6ba 100644 --- a/types/context.go +++ b/types/context.go @@ -3,6 +3,8 @@ package types import ( "strings" + "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" + "github.com/arduino/arduino-builder/i18n" "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" @@ -73,7 +75,7 @@ type Context struct { WarningsLevel string // Libraries handling - Libraries []*libraries.Library + LibrariesManager *librariesmanager.StatusContext HeaderToLibraries map[string][]*libraries.Library ImportedLibraries []*libraries.Library LibrariesResolutionResults map[string]LibraryResolutionResult From fd8b7dcea92845ba26eb0252aae29ccaef635a4e Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 16 Jul 2018 18:03:51 +0200 Subject: [PATCH 26/57] Renamed librariesmanager.StatusContext -> librariesmanager.LibrariesManager --- types/context.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/context.go b/types/context.go index 1a65d6ba..e5fc221c 100644 --- a/types/context.go +++ b/types/context.go @@ -75,7 +75,7 @@ type Context struct { WarningsLevel string // Libraries handling - LibrariesManager *librariesmanager.StatusContext + LibrariesManager *librariesmanager.LibrariesManager HeaderToLibraries map[string][]*libraries.Library ImportedLibraries []*libraries.Library LibrariesResolutionResults map[string]LibraryResolutionResult From 4722d661a3ceb9adff5f9a26ea558d6c110ace6e Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 16 Jul 2018 19:05:07 +0200 Subject: [PATCH 27/57] Using LibraryLocations and librarymanager functions to load libraries --- libraries_loader.go | 28 ++++++++++++---------------- phases/libraries_builder.go | 10 +++++----- types/context.go | 1 - 3 files changed, 17 insertions(+), 22 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index 96ca7c8e..2bd7cad9 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -42,41 +42,39 @@ import ( type LibrariesLoader struct{} func (s *LibrariesLoader) Run(ctx *types.Context) error { + lm := librariesmanager.NewLibraryManager() + ctx.LibrariesManager = lm + builtInLibrariesFolders := ctx.BuiltInLibrariesFolders if err := builtInLibrariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - sortedLibrariesFolders := builtInLibrariesFolders.Clone() + lm.AddLibrariesDir(libraries.IDEBuiltIn, builtInLibrariesFolders...) - actualPlatform := ctx.ActualPlatform - platform := ctx.TargetPlatform debugLevel := ctx.DebugLevel logger := ctx.GetLogger() + actualPlatform := ctx.ActualPlatform + platform := ctx.TargetPlatform if actualPlatform != platform { if dir := actualPlatform.GetLibrariesDir(); dir != nil { - sortedLibrariesFolders.Add(dir) + lm.AddLibrariesDir(libraries.ReferencedPlatformBuiltIn, dir) } } - if dir := platform.GetLibrariesDir(); dir != nil { - sortedLibrariesFolders.Add(dir) + lm.AddLibrariesDir(libraries.PlatformBuiltIn, dir) } librariesFolders := ctx.OtherLibrariesFolders if err := librariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - sortedLibrariesFolders.AddAllMissing(librariesFolders) + lm.AddLibrariesDir(libraries.Sketchbook, librariesFolders...) - ctx.LibrariesFolders = sortedLibrariesFolders - - lm := librariesmanager.NewLibraryManager() - for _, libraryFolder := range sortedLibrariesFolders { - if err := lm.LoadLibrariesFromDir(libraryFolder); err != nil { - return i18n.WrapError(err) - } + if err := lm.RescanLibraries(); err != nil { + return i18n.WrapError(err) } + if debugLevel > 0 { for _, lib := range lm.Libraries { for _, libAlt := range lib.Alternatives { @@ -91,8 +89,6 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } } - ctx.LibrariesManager = lm - headerToLibraries := make(map[string][]*libraries.Library) for _, lib := range lm.Libraries { for _, library := range lib.Alternatives { diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 33e8c96a..ae7a2c61 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -52,13 +52,13 @@ func (s *LibrariesBuilder) Run(ctx *types.Context) error { librariesBuildPath := ctx.LibrariesBuildPath buildProperties := ctx.BuildProperties includes := utils.Map(ctx.IncludeFolders.AsStrings(), utils.WrapWithHyphenI) - libraries := ctx.ImportedLibraries + libs := ctx.ImportedLibraries if err := librariesBuildPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - objectFiles, err := compileLibraries(ctx, libraries, librariesBuildPath, buildProperties, includes) + objectFiles, err := compileLibraries(ctx, libs, librariesBuildPath, buildProperties, includes) if err != nil { return i18n.WrapError(err) } @@ -66,14 +66,14 @@ func (s *LibrariesBuilder) Run(ctx *types.Context) error { ctx.LibrariesObjectFiles = objectFiles // Search for precompiled libraries - fixLDFLAGforPrecompiledLibraries(ctx, libraries) + fixLDFLAGforPrecompiledLibraries(ctx, libs) return nil } -func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libraries []*libraries.Library) error { +func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs []*libraries.Library) error { - for _, library := range libraries { + for _, library := range libs { if library.Precompiled { // add library src path to compiler.c.elf.extra_flags // use library.Name as lib name and srcPath/{mcpu} as location diff --git a/types/context.go b/types/context.go index e5fc221c..fbb917c5 100644 --- a/types/context.go +++ b/types/context.go @@ -25,7 +25,6 @@ type Context struct { HardwareFolders paths.PathList ToolsFolders paths.PathList BuiltInToolsFolders paths.PathList - LibrariesFolders paths.PathList BuiltInLibrariesFolders paths.PathList OtherLibrariesFolders paths.PathList SketchLocation *paths.Path From 22a1e71c1f968a6e6c184b3ae26699197678ed15 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 18 Jul 2018 11:09:52 +0200 Subject: [PATCH 28/57] Use libraryresolver to resolve libraries --- libraries_loader.go | 20 +-- phases/libraries_builder.go | 4 +- resolve_library.go | 192 ++-------------------- resolve_library_test.go | 71 -------- test/helper_tools_downloader.go | 2 +- test/includes_to_include_folders_test.go | 3 - test/libraries_loader_test.go | 72 ++++---- test/prototypes_adder_test.go | 14 +- types/context.go | 5 +- warn_about_arch_incompatible_libraries.go | 2 +- 10 files changed, 68 insertions(+), 317 deletions(-) delete mode 100644 resolve_library_test.go diff --git a/libraries_loader.go b/libraries_loader.go index 2bd7cad9..08644c80 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -33,6 +33,7 @@ import ( "os" "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" + "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesresolver" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" @@ -89,22 +90,11 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } } - headerToLibraries := make(map[string][]*libraries.Library) - for _, lib := range lm.Libraries { - for _, library := range lib.Alternatives { - headers, err := library.SrcFolder.ReadDir() - if err != nil { - return i18n.WrapError(err) - } - headers.FilterSuffix(".h", ".hpp", ".hh") - for _, header := range headers { - headerFileName := header.Base() - headerToLibraries[headerFileName] = append(headerToLibraries[headerFileName], library) - } - } + resolver := librariesresolver.NewCppResolver() + if err := resolver.ScanFromLibrariesManager(lm); err != nil { + return i18n.WrapError(err) } - - ctx.HeaderToLibraries = headerToLibraries + ctx.LibrariesResolver = resolver return nil } diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index ae7a2c61..2b473675 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -71,7 +71,7 @@ func (s *LibrariesBuilder) Run(ctx *types.Context) error { return nil } -func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs []*libraries.Library) error { +func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs libraries.List) error { for _, library := range libs { if library.Precompiled { @@ -96,7 +96,7 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs []*libraries.Libr return nil } -func compileLibraries(ctx *types.Context, libraries []*libraries.Library, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { +func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { objectFiles := paths.NewPathList() for _, library := range libraries { libraryObjectFiles, err := compileLibrary(ctx, library, buildPath, buildProperties, includes) diff --git a/resolve_library.go b/resolve_library.go index 82e867d3..4b9b4412 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -30,98 +30,44 @@ package builder import ( - "path/filepath" - "strings" + "fmt" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { - headerToLibraries := ctx.HeaderToLibraries - platforms := []*cores.PlatformRelease{ctx.ActualPlatform, ctx.TargetPlatform} - libraryResolutionResults := ctx.LibrariesResolutionResults + resolver := ctx.LibrariesResolver importedLibraries := ctx.ImportedLibraries - libs := append([]*libraries.Library{}, headerToLibraries[header]...) + candidates := resolver.AlternativesFor(header) + fmt.Printf("ResolveLibrary(%s)\n", header) + fmt.Printf(" -> candidates: %s\n", candidates) - if libs == nil || len(libs) == 0 { + if candidates == nil || len(candidates) == 0 { return nil } - if importedLibraryContainsOneOfCandidates(importedLibraries, libs) { - return nil - } - - if len(libs) == 1 { - return libs[0] - } - - reverse(libs) - - var library *libraries.Library - - for _, platform := range platforms { - if platform != nil { - library = findBestLibraryWithHeader(header, librariesCompatibleWithPlatform(libs, platform, true)) + for _, candidate := range candidates { + if importedLibraries.Contains(candidate) { + return nil } } - if library == nil { - library = findBestLibraryWithHeader(header, libs) - } - - if library == nil { - // reorder libraries to promote fully compatible ones - for _, platform := range platforms { - if platform != nil { - libs = append(librariesCompatibleWithPlatform(libs, platform, false), libs...) - } - } - library = libs[0] + selected := resolver.ResolveFor(header, ctx.TargetPlatform.Platform.Architecture) + if alreadyImported := importedLibraries.FindByName(selected.Name); alreadyImported != nil { + selected = alreadyImported } - library = useAlreadyImportedLibraryWithSameNameIfExists(library, importedLibraries) - - libraryResolutionResults[header] = types.LibraryResolutionResult{ - Library: library, - NotUsedLibraries: filterOutLibraryFrom(libs, library), + ctx.LibrariesResolutionResults[header] = types.LibraryResolutionResult{ + Library: selected, + NotUsedLibraries: filterOutLibraryFrom(candidates, selected), } - return library -} - -//facepalm. sort.Reverse needs an Interface that implements Len/Less/Swap. It's a slice! What else for reversing it?!? -func reverse(data []*libraries.Library) { - for i, j := 0, len(data)-1; i < j; i, j = i+1, j-1 { - data[i], data[j] = data[j], data[i] - } + return selected } -func importedLibraryContainsOneOfCandidates(imported []*libraries.Library, candidates []*libraries.Library) bool { - for _, i := range imported { - for _, j := range candidates { - if i == j { - return true - } - } - } - return false -} - -func useAlreadyImportedLibraryWithSameNameIfExists(library *libraries.Library, imported []*libraries.Library) *libraries.Library { - for _, lib := range imported { - if lib.Name == library.Name { - return lib - } - } - return library -} - -func filterOutLibraryFrom(libs []*libraries.Library, libraryToRemove *libraries.Library) []*libraries.Library { +func filterOutLibraryFrom(libs libraries.List, libraryToRemove *libraries.Library) libraries.List { filteredOutLibraries := []*libraries.Library{} for _, lib := range libs { if lib != libraryToRemove { @@ -130,107 +76,3 @@ func filterOutLibraryFrom(libs []*libraries.Library, libraryToRemove *libraries. } return filteredOutLibraries } - -func libraryCompatibleWithPlatform(library *libraries.Library, platform *cores.PlatformRelease) (bool, bool) { - if len(library.Architectures) == 0 { - return true, true - } - if utils.SliceContains(library.Architectures, constants.LIBRARY_ALL_ARCHS) { - return true, true - } - return utils.SliceContains(library.Architectures, platform.Platform.Architecture), false -} - -func libraryCompatibleWithAllPlatforms(library *libraries.Library) bool { - if utils.SliceContains(library.Architectures, constants.LIBRARY_ALL_ARCHS) { - return true - } - return false -} - -func librariesCompatibleWithPlatform(libs []*libraries.Library, platform *cores.PlatformRelease, reorder bool) []*libraries.Library { - var compatibleLibraries []*libraries.Library - for _, library := range libs { - compatible, generic := libraryCompatibleWithPlatform(library, platform) - if compatible { - if !generic && len(compatibleLibraries) != 0 && libraryCompatibleWithAllPlatforms(compatibleLibraries[0]) && reorder == true { - //priority inversion - compatibleLibraries = append([]*libraries.Library{library}, compatibleLibraries...) - } else { - compatibleLibraries = append(compatibleLibraries, library) - } - } - } - - return compatibleLibraries -} - -func findBestLibraryWithHeader(header string, libs []*libraries.Library) *libraries.Library { - headerName := strings.Replace(header, filepath.Ext(header), constants.EMPTY_STRING, -1) - - var library *libraries.Library - for _, headerName := range []string{headerName, strings.ToLower(headerName)} { - library = findLibWithName(headerName, libs) - if library != nil { - return library - } - library = findLibWithName(headerName+"-master", libs) - if library != nil { - return library - } - library = findLibWithNameStartingWith(headerName, libs) - if library != nil { - return library - } - library = findLibWithNameEndingWith(headerName, libs) - if library != nil { - return library - } - library = findLibWithNameContaining(headerName, libs) - if library != nil { - return library - } - } - - return nil -} - -func findLibWithName(name string, libraries []*libraries.Library) *libraries.Library { - for _, library := range libraries { - if simplifyName(library.Name) == simplifyName(name) { - return library - } - } - return nil -} - -func findLibWithNameStartingWith(name string, libraries []*libraries.Library) *libraries.Library { - for _, library := range libraries { - if strings.HasPrefix(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func findLibWithNameEndingWith(name string, libraries []*libraries.Library) *libraries.Library { - for _, library := range libraries { - if strings.HasSuffix(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func findLibWithNameContaining(name string, libraries []*libraries.Library) *libraries.Library { - for _, library := range libraries { - if strings.Contains(simplifyName(library.Name), simplifyName(name)) { - return library - } - } - return nil -} - -func simplifyName(name string) string { - return strings.ToLower(strings.Replace(name, "_", " ", -1)) -} diff --git a/resolve_library_test.go b/resolve_library_test.go deleted file mode 100644 index 0566073d..00000000 --- a/resolve_library_test.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2017 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "testing" - - "github.com/bcmi-labs/arduino-cli/arduino/libraries" - - "github.com/stretchr/testify/require" -) - -func TestFindBestLibraryWithHeader(t *testing.T) { - l1 := &libraries.Library{Name: "Calculus Lib"} - l2 := &libraries.Library{Name: "Calculus Lib-master"} - l3 := &libraries.Library{Name: "Calculus Lib Improved"} - l4 := &libraries.Library{Name: "Another Calculus Lib"} - l5 := &libraries.Library{Name: "Yet Another Calculus Lib Improved"} - l6 := &libraries.Library{Name: "AnotherLib"} - - // Test exact name matching - res := findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3, l2, l1}) - require.Equal(t, l1.Name, res.Name) - - // Test exact name with "-master" postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3, l2}) - require.Equal(t, l2.Name, res.Name) - - // Test prefix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4, l3}) - require.Equal(t, l3.Name, res.Name) - - // Test postfix matching - res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5, l4}) - require.Equal(t, l4.Name, res.Name) - - // Test "contains"" matching - res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6, l5}) - require.Equal(t, l5.Name, res.Name) - - // Test none matching - res = findBestLibraryWithHeader("calculus_lib.h", []*libraries.Library{l6}) - require.Nil(t, res) -} diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index 9a8cc95a..cc0a98dc 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -142,7 +142,7 @@ func DownloadCoresAndToolsAndLibraries(t *testing.T) { Library{Name: "Bridge", Version: "1.6.1"}, Library{Name: "CapacitiveSensor", Version: "0.5.0", VersionInLibProperties: "0.5"}, Library{Name: "Ethernet", Version: "1.1.1"}, - Library{Name: "Robot IR Remote", Version: "1.0.2"}, + Library{Name: "Robot IR Remote", Version: "2.0.0"}, Library{Name: "FastLED", Version: "3.1.0"}, } diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index 24c71deb..3b71c754 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -168,11 +168,8 @@ func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { defer buildPath.RemoveAll() commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.ContainerMergeCopySketchFiles{}, - &builder.ContainerFindIncludes{}, } diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 841e88ec..50814e9f 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -73,11 +73,11 @@ func TestLoadLibrariesAVR(t *testing.T) { NoError(t, err) } - librariesFolders := ctx.LibrariesFolders + librariesFolders := ctx.LibrariesManager.LibrariesDir require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) libs := extractLibraries(ctx) require.Equal(t, 24, len(libs)) @@ -142,28 +142,23 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ require.Equal(t, "Wire", libs[idx].Name) - headerToLibraries := ctx.HeaderToLibraries - require.Equal(t, 2, len(headerToLibraries["Audio.h"])) - - libs = headerToLibraries["Audio.h"] + libs = ctx.LibrariesResolver.AlternativesFor("Audio.h") require.Len(t, libs, 2) sort.Sort(ByLibraryName(libs)) require.Equal(t, "Audio", libs[0].Name) require.Equal(t, "FakeAudio", libs[1].Name) - require.Len(t, headerToLibraries["FakeAudio.h"], 1) - require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) - - require.Len(t, headerToLibraries["Adafruit_PN532.h"], 1) - require.Equal(t, "Adafruit_PN532", headerToLibraries["Adafruit_PN532.h"][0].Name) + libs = ctx.LibrariesResolver.AlternativesFor("FakeAudio.h") + require.Len(t, libs, 1) + require.Equal(t, "FakeAudio", libs[0].Name) - require.Len(t, headerToLibraries["IRremote.h"], 2) + libs = ctx.LibrariesResolver.AlternativesFor("Adafruit_PN532.h") + require.Len(t, libs, 1) + require.Equal(t, "Adafruit_PN532", libs[0].Name) - libs = headerToLibraries["IRremote.h"] - require.Len(t, libs, 2) - sort.Sort(ByLibraryName(libs)) + libs = ctx.LibrariesResolver.AlternativesFor("IRremote.h") + require.Len(t, libs, 1) require.Equal(t, "IRremote", libs[0].Name) - require.Equal(t, "Robot_IR_Remote", libs[1].Name) } func TestLoadLibrariesSAM(t *testing.T) { @@ -188,11 +183,11 @@ func TestLoadLibrariesSAM(t *testing.T) { NoError(t, err) } - librariesFolders := ctx.LibrariesFolders + librariesFolders := ctx.LibrariesManager.LibrariesDir require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "sam", "libraries")).EquivalentTo(librariesFolders[1])) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "sam", "libraries")).EquivalentTo(librariesFolders[1].Path)) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) libraries := extractLibraries(ctx) require.Equal(t, 22, len(libraries)) @@ -234,22 +229,19 @@ func TestLoadLibrariesSAM(t *testing.T) { idx++ require.Equal(t, "Wire", libraries[idx].Name) - headerToLibraries := ctx.HeaderToLibraries - - libs := headerToLibraries["Audio.h"] + libs := ctx.LibrariesResolver.AlternativesFor("Audio.h") require.Len(t, libs, 2) sort.Sort(ByLibraryName(libs)) require.Equal(t, "Audio", libs[0].Name) require.Equal(t, "FakeAudio", libs[1].Name) - require.Equal(t, 1, len(headerToLibraries["FakeAudio.h"])) - require.Equal(t, "FakeAudio", headerToLibraries["FakeAudio.h"][0].Name) + libs = ctx.LibrariesResolver.AlternativesFor("FakeAudio.h") + require.Len(t, libs, 1) + require.Equal(t, "FakeAudio", libs[0].Name) - libs = headerToLibraries["IRremote.h"] - require.Len(t, libs, 2) - sort.Sort(ByLibraryName(libs)) + libs = ctx.LibrariesResolver.AlternativesFor("IRremote.h") + require.Len(t, libs, 1) require.Equal(t, "IRremote", libs[0].Name) - require.Equal(t, "Robot_IR_Remote", libs[1].Name) } func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { @@ -274,11 +266,11 @@ func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { NoError(t, err) } - librariesFolders := ctx.LibrariesFolders + librariesFolders := ctx.LibrariesManager.LibrariesDir require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2])) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) } func TestLoadLibrariesMyAVRPlatform(t *testing.T) { @@ -303,10 +295,10 @@ func TestLoadLibrariesMyAVRPlatform(t *testing.T) { NoError(t, err) } - librariesFolders := ctx.LibrariesFolders + librariesFolders := ctx.LibrariesManager.LibrariesDir require.Equal(t, 4, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0])) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1])) - require.True(t, Abs(t, paths.New("user_hardware", "my_avr_platform", "avr", "libraries")).EquivalentTo(librariesFolders[2])) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[3])) + require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) + require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) + require.True(t, Abs(t, paths.New("user_hardware", "my_avr_platform", "avr", "libraries")).EquivalentTo(librariesFolders[2].Path)) + require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[3].Path)) } diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go index 8e3e125e..eb4837eb 100644 --- a/test/prototypes_adder_test.go +++ b/test/prototypes_adder_test.go @@ -694,13 +694,13 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - LibrariesFolders: paths.NewPathList("libraries", "downloaded_libraries"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesFolders: paths.NewPathList("libraries", "downloaded_libraries"), + BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) diff --git a/types/context.go b/types/context.go index fbb917c5..223a6bb2 100644 --- a/types/context.go +++ b/types/context.go @@ -4,6 +4,7 @@ import ( "strings" "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" + "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesresolver" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/go-paths-helper" @@ -75,8 +76,8 @@ type Context struct { // Libraries handling LibrariesManager *librariesmanager.LibrariesManager - HeaderToLibraries map[string][]*libraries.Library - ImportedLibraries []*libraries.Library + LibrariesResolver *librariesresolver.Cpp + ImportedLibraries libraries.List LibrariesResolutionResults map[string]LibraryResolutionResult IncludeFolders paths.PathList //OutputGccMinusM string diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go index d07769f8..c72e46f7 100644 --- a/warn_about_arch_incompatible_libraries.go +++ b/warn_about_arch_incompatible_libraries.go @@ -54,7 +54,7 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { } for _, importedLibrary := range ctx.ImportedLibraries { - if !importedLibrary.SupportsAnyArchitectureIn(archs) { + if !importedLibrary.SupportsAnyArchitectureIn(archs...) { logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, importedLibrary.Name, strings.Join(importedLibrary.Architectures, ", "), From 006c22d8df73e74f3c310f85d11f5b6e5f0ec914 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 19 Jul 2018 15:49:39 +0200 Subject: [PATCH 29/57] Fixed test libraries downloader --- test/helper_tools_downloader.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index cc0a98dc..faded5e4 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -676,7 +676,7 @@ func downloadAndUnpack(url string) (*paths.Path, []os.FileInfo, error) { func buildUnpackCmd(file *paths.Path) *exec.Cmd { var cmd *exec.Cmd - if file.Ext() == "zip" { + if file.Ext() == ".zip" { cmd = exec.Command("unzip", "-qq", file.Base()) } else { cmd = exec.Command("tar", "xf", file.Base()) From 23a0bb485459519f137fa2cf9ed4b6fc0c8d9b1f Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 19 Jul 2018 15:49:56 +0200 Subject: [PATCH 30/57] Using new librarymanager functions to load libraries --- libraries_loader.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/libraries_loader.go b/libraries_loader.go index 08644c80..6564bd0c 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -50,7 +50,9 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { if err := builtInLibrariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - lm.AddLibrariesDir(libraries.IDEBuiltIn, builtInLibrariesFolders...) + for _, folder := range builtInLibrariesFolders { + lm.AddLibrariesDir(folder, libraries.IDEBuiltIn) + } debugLevel := ctx.DebugLevel logger := ctx.GetLogger() @@ -58,19 +60,17 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { actualPlatform := ctx.ActualPlatform platform := ctx.TargetPlatform if actualPlatform != platform { - if dir := actualPlatform.GetLibrariesDir(); dir != nil { - lm.AddLibrariesDir(libraries.ReferencedPlatformBuiltIn, dir) - } - } - if dir := platform.GetLibrariesDir(); dir != nil { - lm.AddLibrariesDir(libraries.PlatformBuiltIn, dir) + lm.AddPlatformReleaseLibrariesDir(actualPlatform, libraries.ReferencedPlatformBuiltIn) } + lm.AddPlatformReleaseLibrariesDir(platform, libraries.PlatformBuiltIn) librariesFolders := ctx.OtherLibrariesFolders if err := librariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } - lm.AddLibrariesDir(libraries.Sketchbook, librariesFolders...) + for _, folder := range librariesFolders { + lm.AddLibrariesDir(folder, libraries.Sketchbook) + } if err := lm.RescanLibraries(); err != nil { return i18n.WrapError(err) From 1901f83ecfb87d3c3ba741f9cd71dd856406403c Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Thu, 19 Jul 2018 15:50:28 +0200 Subject: [PATCH 31/57] tests: print error output if something goes wrong with untar --- test/helper_tools_downloader.go | 1 + 1 file changed, 1 insertion(+) diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index faded5e4..30a1826a 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -658,6 +658,7 @@ func downloadAndUnpack(url string) (*paths.Path, []os.FileInfo, error) { cmd := buildUnpackCmd(archiveFilePath) out, err := cmd.CombinedOutput() if err != nil { + fmt.Println(string(out)) return nil, nil, i18n.WrapError(err) } if len(out) > 0 { From 54213270c68494da5af64ba86969ef8ab75b788e Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 25 Jul 2018 19:48:26 +0200 Subject: [PATCH 32/57] Using new *manager constructors --- hardware_loader.go | 2 +- libraries_loader.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index 4283af50..efc9f8f7 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -38,7 +38,7 @@ import ( type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { - pm := packagemanager.NewPackageManager() + pm := packagemanager.NewPackageManager(nil, nil, nil, nil) if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { return i18n.WrapError(err) } diff --git a/libraries_loader.go b/libraries_loader.go index 6564bd0c..c6f52d1f 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -43,7 +43,7 @@ import ( type LibrariesLoader struct{} func (s *LibrariesLoader) Run(ctx *types.Context) error { - lm := librariesmanager.NewLibraryManager() + lm := librariesmanager.NewLibraryManager(nil, nil) ctx.LibrariesManager = lm builtInLibrariesFolders := ctx.BuiltInLibrariesFolders From fdfea8e05c0d8bc218f241fcaf8fd634be4e2a3e Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 1 Aug 2018 11:47:46 +0200 Subject: [PATCH 33/57] Changed field name Folder->InstallDir --- setup_build_properties.go | 10 +++++----- target_board_resolver.go | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/setup_build_properties.go b/setup_build_properties.go index c1059776..25c77d3f 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -73,10 +73,10 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } buildProperties["build.core"] = ctx.BuildCore - buildProperties["build.core.path"] = filepath.Join(actualPlatform.Folder, "cores", buildProperties["build.core"]) - buildProperties["build.system.path"] = filepath.Join(actualPlatform.Folder, "system") - buildProperties["runtime.platform.path"] = targetPlatform.Folder - buildProperties["runtime.hardware.path"] = filepath.Join(targetPlatform.Folder, "..") + buildProperties["build.core.path"] = actualPlatform.InstallDir.Join("cores", buildProperties["build.core"]).String() + buildProperties["build.system.path"] = actualPlatform.InstallDir.Join("system").String() + buildProperties["runtime.platform.path"] = targetPlatform.InstallDir.String() + buildProperties["runtime.hardware.path"] = targetPlatform.InstallDir.Join("..").String() buildProperties["runtime.ide.version"] = ctx.ArduinoAPIVersion buildProperties["runtime.ide.path"] = exPath buildProperties["build.fqbn"] = ctx.FQBN.String() @@ -95,7 +95,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } else { variantPlatform = targetPlatform } - buildProperties["build.variant.path"] = filepath.Join(variantPlatform.Folder, "variants", variant) + buildProperties["build.variant.path"] = variantPlatform.InstallDir.Join("variants", variant).String() } for _, tool := range ctx.AllTools { diff --git a/target_board_resolver.go b/target_board_resolver.go index 13eaaa1d..9c09fc4a 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -57,8 +57,8 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { core = core[strings.Index(core, ":")+1:] if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.Folder) - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.Folder) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.InstallDir) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.InstallDir) } ctx.BuildCore = core From 543863f310ab44793b4706bfe195e8c4047e54a0 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 1 Aug 2018 12:09:48 +0200 Subject: [PATCH 34/57] Changed field name Folder->InstallDir --- setup_build_properties.go | 8 +++---- test/tools_loader_test.go | 50 +++++++++++++++++++-------------------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/setup_build_properties.go b/setup_build_properties.go index 25c77d3f..9d78b08f 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -99,12 +99,12 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } for _, tool := range ctx.AllTools { - buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.InstallDir.String() } for _, tool := range ctx.RequiredTools { - buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.Folder - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.Folder + buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.InstallDir.String() } if !utils.MapStringStringHas(buildProperties, "software") { diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 6076305f..10b053c3 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -55,7 +55,7 @@ func (s ByToolIDAndVersion) Less(i, j int) bool { if s[i].Version != s[j].Version { return s[i].Version < s[j].Version } - return s[i].Folder < s[j].Folder + return s[i].InstallDir.String() < s[j].InstallDir.String() } func requireEquivalentPaths(t *testing.T, actual string, expected ...string) { @@ -91,31 +91,31 @@ func TestLoadTools(t *testing.T) { idx := 0 require.Equal(t, ":arduino-preprocessor@0.1.5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arduino-preprocessor/0.1.5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arduino-preprocessor/0.1.5") idx++ require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avr-gcc/4.8.1-arduino5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avr-gcc/4.8.1-arduino5") idx++ require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") idx++ require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avrdude/6.0.1-arduino5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avrdude/6.0.1-arduino5") idx++ require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") idx++ require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.5-arduino") idx++ require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.6.1-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.6.1-arduino") idx++ require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/ctags/5.8-arduino11") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/ctags/5.8-arduino11") } func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { @@ -134,13 +134,13 @@ func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { idx := 0 require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") idx++ require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") } func TestLoadLotsOfTools(t *testing.T) { @@ -161,38 +161,38 @@ func TestLoadLotsOfTools(t *testing.T) { idx := 0 require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") idx++ require.Equal(t, ":arduino-preprocessor@0.1.5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arduino-preprocessor/0.1.5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arduino-preprocessor/0.1.5") idx++ require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") idx++ require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avr-gcc/4.8.1-arduino5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avr-gcc/4.8.1-arduino5") idx++ require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") idx++ require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/avrdude/6.0.1-arduino5") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avrdude/6.0.1-arduino5") idx++ require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "tools_builtin/avr") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") idx++ require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.5-arduino") idx++ require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, tools[idx].Folder, "downloaded_tools/bossac/1.6.1-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.6.1-arduino") idx++ require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_tools/ctags/5.8-arduino11") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/ctags/5.8-arduino11") idx++ require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].Folder, "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") + requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") } From 2f39b7080c6220c43fa49ab0b378e3af4cf99ee6 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 1 Aug 2018 12:47:32 +0200 Subject: [PATCH 35/57] Changed field name Folder->InstallDir SrcFolder->SourceDir Folder->Dir --- container_find_includes.go | 12 ++++++------ create_cmake_rule.go | 8 ++++---- fail_if_imported_library_is_wrong.go | 8 ++++---- phases/libraries_builder.go | 16 ++++++++-------- print_used_and_not_used_libraries.go | 9 +++++---- print_used_libraries_if_verbose.go | 4 ++-- test/includes_to_include_folders_test.go | 6 +++--- test/libraries_loader_test.go | 8 ++++---- types/types.go | 2 +- 9 files changed, 37 insertions(+), 36 deletions(-) diff --git a/container_find_includes.go b/container_find_includes.go index c1a5b372..743e17c4 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -319,8 +319,8 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t cache.ExpectFile(sourcePath) includes := ctx.IncludeFolders - if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityFolder != nil { - includes = append(includes, library.UtilityFolder) + if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityDir != nil { + includes = append(includes, library.UtilityDir) } var preproc_err error var preproc_stderr []byte @@ -381,10 +381,10 @@ func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile t // include path and queue its source files for further // include scanning ctx.ImportedLibraries = append(ctx.ImportedLibraries, library) - appendIncludeFolder(ctx, cache, sourcePath, include, library.SrcFolder) - sourceFolders := library.SourceDirs() - for _, sourceFolder := range sourceFolders { - queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceFolder.Folder, sourceFolder.Recurse) + appendIncludeFolder(ctx, cache, sourcePath, include, library.SourceDir) + sourceDirs := library.SourceDirs() + for _, sourceDir := range sourceDirs { + queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceDir.Dir, sourceDir.Recurse) } first = false } diff --git a/create_cmake_rule.go b/create_cmake_rule.go index e12984d5..d26fe8fc 100644 --- a/create_cmake_rule.go +++ b/create_cmake_rule.go @@ -79,17 +79,17 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error { // Copy used libraries in the correct folder extensions := func(ext string) bool { return VALID_EXPORT_EXTENSIONS[ext] } for _, library := range ctx.ImportedLibraries { - libFolder := libBaseFolder.Join(library.Name) - utils.CopyDir(library.Folder.String(), libFolder.String(), extensions) + libDir := libBaseFolder.Join(library.Name) + utils.CopyDir(library.InstallDir.String(), libDir.String(), extensions) // Remove examples folder if _, err := libBaseFolder.Join("examples").Stat(); err == nil { - libFolder.Join("examples").RemoveAll() + libDir.Join("examples").RemoveAll() } // Remove stray folders contining incompatible libraries staticLibsExtensions := func(ext string) bool { return DOTAEXTENSION[ext] } mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] var files []string - utils.FindFilesInFolder(&files, libFolder.Join("src").String(), staticLibsExtensions, true) + utils.FindFilesInFolder(&files, libDir.Join("src").String(), staticLibsExtensions, true) for _, file := range files { if !strings.Contains(filepath.Dir(file), mcu) { os.RemoveAll(filepath.Dir(file)) diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index a0dec009..4610a843 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -47,17 +47,17 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { for _, library := range ctx.ImportedLibraries { if !library.IsLegacy { - if isDir, _ := library.Folder.Join(constants.LIBRARY_FOLDER_ARCH).IsDir(); isDir { + if isDir, _ := library.InstallDir.Join(constants.LIBRARY_FOLDER_ARCH).IsDir(); isDir { return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) } for _, propName := range libraries.MandatoryProperties { if _, ok := library.Properties[propName]; !ok { - return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.Folder) + return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.InstallDir) } } if library.Layout == libraries.RecursiveLayout { - if library.UtilityFolder != nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.Folder) + if library.UtilityDir != nil { + return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.InstallDir) } } } diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index 2b473675..f6780542 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -78,7 +78,7 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs libraries.List) e // add library src path to compiler.c.elf.extra_flags // use library.Name as lib name and srcPath/{mcpu} as location mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - path := library.SrcFolder.Join(mcu).String() + path := library.SourceDir.Join(mcu).String() // find all library names in the folder and prepend -l filePaths := []string{} libs_cmd := library.LDflags + " " @@ -128,7 +128,7 @@ func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *p filePaths := []string{} mcu := buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] - err := utils.FindFilesInFolder(&filePaths, library.SrcFolder.Join(mcu).String(), extensions, true) + err := utils.FindFilesInFolder(&filePaths, library.SourceDir.Join(mcu).String(), extensions, true) if err != nil { return nil, i18n.WrapError(err) } @@ -140,7 +140,7 @@ func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *p } if library.Layout == libraries.RecursiveLayout { - libObjectFiles, err := builder_utils.CompileFilesRecursive(ctx, library.SrcFolder, libraryBuildPath, buildProperties, includes) + libObjectFiles, err := builder_utils.CompileFilesRecursive(ctx, library.SourceDir, libraryBuildPath, buildProperties, includes) if err != nil { return nil, i18n.WrapError(err) } @@ -154,18 +154,18 @@ func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *p objectFiles.AddAll(libObjectFiles) } } else { - if library.UtilityFolder != nil { - includes = append(includes, utils.WrapWithHyphenI(library.UtilityFolder.String())) + if library.UtilityDir != nil { + includes = append(includes, utils.WrapWithHyphenI(library.UtilityDir.String())) } - libObjectFiles, err := builder_utils.CompileFiles(ctx, library.SrcFolder, false, libraryBuildPath, buildProperties, includes) + libObjectFiles, err := builder_utils.CompileFiles(ctx, library.SourceDir, false, libraryBuildPath, buildProperties, includes) if err != nil { return nil, i18n.WrapError(err) } objectFiles.AddAll(libObjectFiles) - if library.UtilityFolder != nil { + if library.UtilityDir != nil { utilityBuildPath := libraryBuildPath.Join("utility") - utilityObjectFiles, err := builder_utils.CompileFiles(ctx, library.UtilityFolder, false, utilityBuildPath, buildProperties, includes) + utilityObjectFiles, err := builder_utils.CompileFiles(ctx, library.UtilityDir, false, utilityBuildPath, buildProperties, includes) if err != nil { return nil, i18n.WrapError(err) } diff --git a/print_used_and_not_used_libraries.go b/print_used_and_not_used_libraries.go index b60a6bf0..43ae1c7e 100644 --- a/print_used_and_not_used_libraries.go +++ b/print_used_and_not_used_libraries.go @@ -30,10 +30,11 @@ package builder import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" "os" "time" + + "github.com/arduino/arduino-builder/constants" + "github.com/arduino/arduino-builder/types" ) type PrintUsedAndNotUsedLibraries struct { @@ -58,9 +59,9 @@ func (s *PrintUsedAndNotUsedLibraries) Run(ctx *types.Context) error { for header, libResResult := range libraryResolutionResults { logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR, header) - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_USED, libResResult.Library.Folder) + logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_USED, libResResult.Library.InstallDir) for _, notUsedLibrary := range libResResult.NotUsedLibraries { - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_NOT_USED, notUsedLibrary.Folder) + logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_NOT_USED, notUsedLibrary.InstallDir) } } diff --git a/print_used_libraries_if_verbose.go b/print_used_libraries_if_verbose.go index 3cd4a8dc..f5113839 100644 --- a/print_used_libraries_if_verbose.go +++ b/print_used_libraries_if_verbose.go @@ -52,9 +52,9 @@ func (s *PrintUsedLibrariesIfVerbose) Run(ctx *types.Context) error { legacy = constants.MSG_LIB_LEGACY } if library.Version == constants.EMPTY_STRING { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY, library.Name, library.Folder, legacy) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY, library.Name, library.InstallDir, legacy) } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY_AT_VERSION, library.Name, library.Version, library.Folder, legacy) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY_AT_VERSION, library.Name, library.Version, library.InstallDir, legacy) } } diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index 3b71c754..f6c6a99e 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -219,7 +219,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")) + requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")) } func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatform(t *testing.T) { @@ -257,7 +257,7 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "SPI", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("libraries", "SPI")) + requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("libraries", "SPI")) } func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { @@ -295,7 +295,7 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { sort.Sort(ByLibraryName(importedLibraries)) require.Equal(t, 1, len(importedLibraries)) require.Equal(t, "USBHost", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SrcFolder.String(), filepath.Join("libraries", "USBHost", "src")) + requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("libraries", "USBHost", "src")) } func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 50814e9f..1a7f53e5 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -90,8 +90,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ require.Equal(t, "Adafruit_PN532", libs[idx].Name) - require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].Folder)) - require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].SrcFolder)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].InstallDir)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].SourceDir)) require.Equal(t, 1, len(libs[idx].Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, libs[idx].Architectures[0]) require.False(t, libs[idx].IsLegacy) @@ -106,8 +106,8 @@ func TestLoadLibrariesAVR(t *testing.T) { idx++ bridgeLib := libs[idx] require.Equal(t, "Bridge", bridgeLib.Name) - require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge")).EquivalentTo(bridgeLib.Folder)) - require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge/src")).EquivalentTo(bridgeLib.SrcFolder)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge")).EquivalentTo(bridgeLib.InstallDir)) + require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge/src")).EquivalentTo(bridgeLib.SourceDir)) require.Equal(t, 1, len(bridgeLib.Architectures)) require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Architectures[0]) require.Equal(t, "Arduino", bridgeLib.Author) diff --git a/types/types.go b/types/types.go index 55cebdd3..84b344ab 100644 --- a/types/types.go +++ b/types/types.go @@ -80,7 +80,7 @@ func sourceRoot(ctx *Context, origin interface{}) *paths.Path { case *Sketch: return ctx.SketchBuildPath case *libraries.Library: - return o.SrcFolder + return o.SourceDir default: panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) } From b8512dfa8616122c6a471e56295f58420775d965 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 1 Aug 2018 16:16:47 +0200 Subject: [PATCH 36/57] Changed field name *Folder->*Dir --- arduino-builder/main.go | 12 +- grpc/rpc.go | 18 +- hardware_loader.go | 2 +- libraries_loader.go | 4 +- platform_keys_rewrite_loader.go | 2 +- ...dd_build_board_property_if_missing_test.go | 8 +- test/builder_test.go | 28 +- test/create_build_options_map_test.go | 18 +- test/ctags_runner_test.go | 80 ++--- test/hardware_loader_test.go | 8 +- test/includes_to_include_folders_test.go | 126 +++---- test/libraries_loader_test.go | 32 +- test/load_vid_pid_specific_properties_test.go | 8 +- test/merge_sketch_with_bootloader_test.go | 56 +-- test/platform_keys_rewrite_loader_test.go | 2 +- test/prototypes_adder_test.go | 318 +++++++++--------- test/setup_build_properties_test.go | 40 +-- test/store_build_options_map_test.go | 20 +- test/target_board_resolver_test.go | 24 +- test/tools_loader_test.go | 8 +- test/try_build_of_problematic_sketch_test.go | 18 +- tools_loader.go | 10 +- types/context.go | 36 +- 23 files changed, 439 insertions(+), 439 deletions(-) diff --git a/arduino-builder/main.go b/arduino-builder/main.go index f40225c2..c6815e4b 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -259,9 +259,9 @@ func main() { if hardwareFolders, err := toSliceOfUnquoted(hardwareFoldersFlag); err != nil { printCompleteError(err) } else if len(hardwareFolders) > 0 { - ctx.HardwareFolders = paths.NewPathList(hardwareFolders...) + ctx.HardwareDirs = paths.NewPathList(hardwareFolders...) } - if len(ctx.HardwareFolders) == 0 { + if len(ctx.HardwareDirs) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_HARDWARE + "' is mandatory")) } @@ -269,9 +269,9 @@ func main() { if toolsFolders, err := toSliceOfUnquoted(toolsFoldersFlag); err != nil { printCompleteError(err) } else if len(toolsFolders) > 0 { - ctx.ToolsFolders = paths.NewPathList(toolsFolders...) + ctx.ToolsDirs = paths.NewPathList(toolsFolders...) } - if len(ctx.ToolsFolders) == 0 { + if len(ctx.ToolsDirs) == 0 { printErrorMessageAndFlagUsage(errors.New("Parameter '" + FLAG_TOOLS + "' is mandatory")) } @@ -279,14 +279,14 @@ func main() { if librariesFolders, err := toSliceOfUnquoted(librariesFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesFolders) > 0 { - ctx.OtherLibrariesFolders = paths.NewPathList(librariesFolders...) + ctx.OtherLibrariesDirs = paths.NewPathList(librariesFolders...) } // FLAG_BUILT_IN_LIBRARIES if librariesBuiltInFolders, err := toSliceOfUnquoted(librariesBuiltInFoldersFlag); err != nil { printCompleteError(err) } else if len(librariesBuiltInFolders) > 0 { - ctx.BuiltInLibrariesFolders = paths.NewPathList(librariesBuiltInFolders...) + ctx.BuiltInLibrariesDirs = paths.NewPathList(librariesBuiltInFolders...) } // FLAG_PREFS diff --git a/grpc/rpc.go b/grpc/rpc.go index 9538dbf8..da2dc679 100644 --- a/grpc/rpc.go +++ b/grpc/rpc.go @@ -57,7 +57,7 @@ type builderServer struct { } func (s *builderServer) watch() { - folders := []paths.PathList{s.ctx.HardwareFolders, s.ctx.ToolsFolders, s.ctx.BuiltInLibrariesFolders, s.ctx.OtherLibrariesFolders} + folders := []paths.PathList{s.ctx.HardwareDirs, s.ctx.ToolsDirs, s.ctx.BuiltInLibrariesDirs, s.ctx.OtherLibrariesDirs} for _, category := range folders { for _, folder := range category { @@ -83,10 +83,10 @@ func (s *builderServer) DropCache(ctx context.Context, args *pb.VerboseParams) ( // GetFeature returns the feature at the given point. func (s *builderServer) Autocomplete(ctx context.Context, args *pb.BuildParams) (*pb.Response, error) { - s.ctx.HardwareFolders = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) - s.ctx.ToolsFolders = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) - s.ctx.BuiltInLibrariesFolders = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) - s.ctx.OtherLibrariesFolders = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) + s.ctx.HardwareDirs = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) + s.ctx.ToolsDirs = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) + s.ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) + s.ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) s.ctx.SketchLocation = paths.New(args.SketchLocation) s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion @@ -127,10 +127,10 @@ func (s *builderServer) Autocomplete(ctx context.Context, args *pb.BuildParams) // GetFeature returns the feature at the given point. func (s *builderServer) Build(args *pb.BuildParams, stream pb.Builder_BuildServer) error { - s.ctx.HardwareFolders = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) - s.ctx.ToolsFolders = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) - s.ctx.BuiltInLibrariesFolders = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) - s.ctx.OtherLibrariesFolders = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) + s.ctx.HardwareDirs = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) + s.ctx.ToolsDirs = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) + s.ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) + s.ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) s.ctx.SketchLocation = paths.New(args.SketchLocation) s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion diff --git a/hardware_loader.go b/hardware_loader.go index efc9f8f7..532fa5b0 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -39,7 +39,7 @@ type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { pm := packagemanager.NewPackageManager(nil, nil, nil, nil) - if err := pm.LoadHardwareFromDirectories(ctx.HardwareFolders); err != nil { + if err := pm.LoadHardwareFromDirectories(ctx.HardwareDirs); err != nil { return i18n.WrapError(err) } ctx.PackageManager = pm diff --git a/libraries_loader.go b/libraries_loader.go index c6f52d1f..e6da1f99 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -46,7 +46,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { lm := librariesmanager.NewLibraryManager(nil, nil) ctx.LibrariesManager = lm - builtInLibrariesFolders := ctx.BuiltInLibrariesFolders + builtInLibrariesFolders := ctx.BuiltInLibrariesDirs if err := builtInLibrariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } @@ -64,7 +64,7 @@ func (s *LibrariesLoader) Run(ctx *types.Context) error { } lm.AddPlatformReleaseLibrariesDir(platform, libraries.PlatformBuiltIn) - librariesFolders := ctx.OtherLibrariesFolders + librariesFolders := ctx.OtherLibrariesDirs if err := librariesFolders.ToAbs(); err != nil { return i18n.WrapError(err) } diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go index c491dc26..fb475e53 100644 --- a/platform_keys_rewrite_loader.go +++ b/platform_keys_rewrite_loader.go @@ -45,7 +45,7 @@ import ( type PlatformKeysRewriteLoader struct{} func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { - folders := ctx.HardwareFolders + folders := ctx.HardwareDirs platformKeysRewriteTxtPath, err := findPlatformKeysRewriteTxt(folders) if err != nil { diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index 52011d8b..cc51ecb0 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -52,8 +52,8 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega"), } commands := []types.Command{ @@ -83,8 +83,8 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), } commands := []types.Command{ diff --git a/test/builder_test.go b/test/builder_test.go index 061f1624..f41954f8 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -46,14 +46,14 @@ import ( func prepareBuilderTestContext(t *testing.T, sketchPath *paths.Path, fqbn string) *types.Context { return &types.Context{ - SketchLocation: sketchPath, - FQBN: parseFQBN(t, fqbn), - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - ArduinoAPIVersion: "10600", - Verbose: false, + SketchLocation: sketchPath, + FQBN: parseFQBN(t, fqbn), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + ArduinoAPIVersion: "10600", + Verbose: false, } } @@ -241,8 +241,8 @@ func TestBuilderBridgeRedBearLab(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) + ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -276,8 +276,8 @@ func TestBuilderSketchNoFunctions(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := prepareBuilderTestContext(t, paths.New("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") - ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) + ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() @@ -292,8 +292,8 @@ func TestBuilderSketchWithBackup(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := prepareBuilderTestContext(t, paths.New("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") - ctx.HardwareFolders = append(ctx.HardwareFolders, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsFolders = append(ctx.ToolsFolders, paths.New("downloaded_board_manager_stuff")) + ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) + ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() diff --git a/test/create_build_options_map_test.go b/test/create_build_options_map_test.go index beebd1df..929b0a23 100644 --- a/test/create_build_options_map_test.go +++ b/test/create_build_options_map_test.go @@ -40,15 +40,15 @@ import ( func TestCreateBuildOptionsMap(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("hardware", "hardware2"), - ToolsFolders: paths.NewPathList("tools"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketchLocation"), - FQBN: parseFQBN(t, "my:nice:fqbn"), - ArduinoAPIVersion: "ideVersion", - Verbose: true, - BuildPath: paths.New("buildPath"), - DebugLevel: 5, + HardwareDirs: paths.NewPathList("hardware", "hardware2"), + ToolsDirs: paths.NewPathList("tools"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketchLocation"), + FQBN: parseFQBN(t, "my:nice:fqbn"), + ArduinoAPIVersion: "ideVersion", + Verbose: true, + BuildPath: paths.New("buildPath"), + DebugLevel: 5, } create := builder.CreateBuildOptionsMap{} diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go index c1516b8e..26982a0e 100644 --- a/test/ctags_runner_test.go +++ b/test/ctags_runner_test.go @@ -46,14 +46,14 @@ func TestCTagsRunner(t *testing.T) { sketchLocation := Abs(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino")) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -96,14 +96,14 @@ func TestCTagsRunnerSketchWithClass(t *testing.T) { sketchLocation := Abs(t, paths.New("sketch_with_class", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -144,14 +144,14 @@ func TestCTagsRunnerSketchWithTypename(t *testing.T) { sketchLocation := Abs(t, paths.New("sketch_with_typename", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -191,14 +191,14 @@ func TestCTagsRunnerSketchWithNamespace(t *testing.T) { sketchLocation := Abs(t, paths.New("sketch_with_namespace", "sketch.ino")) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -237,14 +237,14 @@ func TestCTagsRunnerSketchWithTemplates(t *testing.T) { sketchLocation := Abs(t, paths.New("sketch_with_templates_and_shift", "template_and_shift.cpp")) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index 31b550d3..e7f19afa 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -43,7 +43,7 @@ import ( func TestLoadHardware(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), + HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), } commands := []types.Command{ @@ -87,7 +87,7 @@ func TestLoadHardware(t *testing.T) { func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), + HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), } commands := []types.Command{ @@ -157,7 +157,7 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), + HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), } commands := []types.Command{ @@ -205,7 +205,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { func TestLoadLotsOfHardware(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), + HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), } commands := []types.Command{ diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go index f6c6a99e..59f60c4c 100644 --- a/test/includes_to_include_folders_test.go +++ b/test/includes_to_include_folders_test.go @@ -45,14 +45,14 @@ func TestIncludesToIncludeFolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -81,14 +81,14 @@ func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -116,14 +116,14 @@ func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch9", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch9", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -154,14 +154,14 @@ func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch10", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch10", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -189,13 +189,13 @@ func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -226,14 +226,14 @@ func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatfo DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -264,14 +264,14 @@ func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_usbhost", "sketch_usbhost.ino"), - FQBN: parseFQBN(t, "arduino:samd:arduino_zero_native"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_usbhost", "sketch_usbhost.ino"), + FQBN: parseFQBN(t, "arduino:samd:arduino_zero_native"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -302,14 +302,14 @@ func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 1a7f53e5..54e3347e 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -55,10 +55,10 @@ func TestLoadLibrariesAVR(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), } commands := []types.Command{ @@ -165,10 +165,10 @@ func TestLoadLibrariesSAM(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), } commands := []types.Command{ @@ -248,10 +248,10 @@ func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), } commands := []types.Command{ @@ -277,10 +277,10 @@ func TestLoadLibrariesMyAVRPlatform(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), } commands := []types.Command{ diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go index efbc6812..28b706e1 100644 --- a/test/load_vid_pid_specific_properties_test.go +++ b/test/load_vid_pid_specific_properties_test.go @@ -43,8 +43,8 @@ func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools", "./tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: parseFQBN(t, "arduino:avr:micro"), ArduinoAPIVersion: "10600", @@ -73,8 +73,8 @@ func TestLoadVIDPIDSpecificProperties(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools", "./tools_builtin"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools", "./tools_builtin"), SketchLocation: paths.New("sketch1", "sketch.ino"), FQBN: parseFQBN(t, "arduino:avr:micro"), ArduinoAPIVersion: "10600", diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go index 976510b6..a83ee92c 100644 --- a/test/merge_sketch_with_bootloader_test.go +++ b/test/merge_sketch_with_bootloader_test.go @@ -45,13 +45,13 @@ func TestMergeSketchWithBootloader(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -87,13 +87,13 @@ func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -129,13 +129,13 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -167,13 +167,13 @@ func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - ToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + ToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) diff --git a/test/platform_keys_rewrite_loader_test.go b/test/platform_keys_rewrite_loader_test.go index acb4fbbd..b091453b 100644 --- a/test/platform_keys_rewrite_loader_test.go +++ b/test/platform_keys_rewrite_loader_test.go @@ -41,7 +41,7 @@ import ( func TestLoadPlatformKeysRewrite(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), + HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), } commands := []types.Command{ diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go index eb4837eb..f80e4594 100644 --- a/test/prototypes_adder_test.go +++ b/test/prototypes_adder_test.go @@ -49,14 +49,14 @@ func TestPrototypesAdderBridgeExample(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -91,14 +91,14 @@ func TestPrototypesAdderSketchWithIfDef(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -131,14 +131,14 @@ func TestPrototypesAdderBaladuino(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch3", "Baladuino.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch3", "Baladuino.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -171,14 +171,14 @@ func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch4", "CharWithEscapedDoubleQuote.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch4", "CharWithEscapedDoubleQuote.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -211,14 +211,14 @@ func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch5", "IncludeBetweenMultilineComment.ino"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch5", "IncludeBetweenMultilineComment.ino"), + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -251,14 +251,14 @@ func TestPrototypesAdderLineContinuations(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch6", "/LineContinuations.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch6", "/LineContinuations.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -291,14 +291,14 @@ func TestPrototypesAdderStringWithComment(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch7", "StringWithComment.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch7", "StringWithComment.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -331,14 +331,14 @@ func TestPrototypesAdderSketchWithStruct(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch8", "SketchWithStruct.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch8", "SketchWithStruct.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -379,14 +379,14 @@ func TestPrototypesAdderSketchWithConfig(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -425,14 +425,14 @@ func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_no_functions_two_files", "main.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_no_functions_two_files", "main.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -465,14 +465,14 @@ func TestPrototypesAdderSketchNoFunctions(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_no_functions", "main.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketch_no_functions", "main.ino"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -511,14 +511,14 @@ func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -554,14 +554,14 @@ func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -608,14 +608,14 @@ func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -651,14 +651,14 @@ func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -694,13 +694,13 @@ func TestPrototypesAdderSketchWithTypename(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesFolders: paths.NewPathList("libraries", "downloaded_libraries"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInLibrariesDirs: paths.NewPathList("libraries", "downloaded_libraries"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -742,14 +742,14 @@ func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:yun"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:yun"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -788,14 +788,14 @@ func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -834,14 +834,14 @@ func TestPrototypesAdderSketchWithConst(t *testing.T) { quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: sketchLocation, + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) @@ -874,14 +874,14 @@ func TestPrototypesAdderSketchWithDosEol(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("eol_processing", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - Verbose: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("eol_processing", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", + Verbose: true, } buildPath := SetupBuildPath(t, ctx) diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index a1334638..29a293e8 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -44,11 +44,11 @@ func TestSetupBuildProperties(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -110,11 +110,11 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "arduino:avr:uno"), + ArduinoAPIVersion: "10600", CustomBuildProperties: []string{"name=fake name", "tools.avrdude.config.path=non existent path with space and a ="}, } @@ -151,11 +151,11 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) @@ -189,11 +189,11 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), + SketchLocation: paths.New("sketch1", "sketch.ino"), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + ArduinoAPIVersion: "10600", } buildPath := SetupBuildPath(t, ctx) diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go index c04cbc76..9d1719ff 100644 --- a/test/store_build_options_map_test.go +++ b/test/store_build_options_map_test.go @@ -41,16 +41,16 @@ import ( func TestStoreBuildOptionsMap(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList("hardware"), - ToolsFolders: paths.NewPathList("tools"), - BuiltInLibrariesFolders: paths.NewPathList("built-in libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketchLocation"), - FQBN: parseFQBN(t, "my:nice:fqbn"), - ArduinoAPIVersion: "ideVersion", - CustomBuildProperties: []string{"custom=prop"}, - Verbose: true, - DebugLevel: 5, + HardwareDirs: paths.NewPathList("hardware"), + ToolsDirs: paths.NewPathList("tools"), + BuiltInLibrariesDirs: paths.NewPathList("built-in libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + SketchLocation: paths.New("sketchLocation"), + FQBN: parseFQBN(t, "my:nice:fqbn"), + ArduinoAPIVersion: "ideVersion", + CustomBuildProperties: []string{"custom=prop"}, + Verbose: true, + DebugLevel: 5, } buildPath := SetupBuildPath(t, ctx) diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index acf3a462..581d58a8 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -41,8 +41,8 @@ import ( func TestTargetBoardResolverUno(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:uno"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + FQBN: parseFQBN(t, "arduino:avr:uno"), } commands := []types.Command{ @@ -66,8 +66,8 @@ func TestTargetBoardResolverUno(t *testing.T) { func TestTargetBoardResolverDue(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + FQBN: parseFQBN(t, "arduino:sam:arduino_due_x"), } commands := []types.Command{ @@ -91,8 +91,8 @@ func TestTargetBoardResolverDue(t *testing.T) { func TestTargetBoardResolverMega1280(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega1280"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega1280"), } commands := []types.Command{ @@ -117,8 +117,8 @@ func TestTargetBoardResolverMega1280(t *testing.T) { func TestTargetBoardResolverMega2560(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega2560"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), + FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega2560"), } commands := []types.Command{ @@ -143,8 +143,8 @@ func TestTargetBoardResolverMega2560(t *testing.T) { func TestTargetBoardResolverCustomYun(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), } commands := []types.Command{ @@ -169,8 +169,8 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { func TestTargetBoardResolverCustomCore(t *testing.T) { ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "watterott:avr:attiny841:core=spencekonde,info=info"), + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), + FQBN: parseFQBN(t, "watterott:avr:attiny841:core=spencekonde,info=info"), } commands := []types.Command{ diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index 10b053c3..b2499ec4 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -78,7 +78,7 @@ func TestLoadTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) @@ -121,7 +121,7 @@ func TestLoadTools(t *testing.T) { func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), + HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) @@ -147,8 +147,8 @@ func TestLoadLotsOfTools(t *testing.T) { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList("downloaded_board_manager_stuff"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools", "tools_builtin"), + HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), } NoError(t, (&builder.HardwareLoader{}).Run(ctx)) diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go index a1a9f574..f8ea0156 100644 --- a/test/try_build_of_problematic_sketch_test.go +++ b/test/try_build_of_problematic_sketch_test.go @@ -119,7 +119,7 @@ func TestTryBuild019(t *testing.T) { func TestTryBuild020(t *testing.T) { ctx := makeDefaultContext(t) - ctx.OtherLibrariesFolders = paths.NewPathList("dependent_libraries", "libraries") + ctx.OtherLibrariesDirs = paths.NewPathList("dependent_libraries", "libraries") tryPreprocessWithContext(t, ctx, "sketch_with_dependend_libraries", "sketch.ino") } @@ -222,14 +222,14 @@ func makeDefaultContext(t *testing.T) *types.Context { DownloadCoresAndToolsAndLibraries(t) ctx := &types.Context{ - HardwareFolders: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), - BuiltInToolsFolders: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesFolders: paths.NewPathList("downloaded_libraries"), - OtherLibrariesFolders: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10607", - Verbose: true, - DebugPreprocessor: true, + HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), + BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), + BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), + OtherLibrariesDirs: paths.NewPathList("libraries"), + FQBN: parseFQBN(t, "arduino:avr:leonardo"), + ArduinoAPIVersion: "10607", + Verbose: true, + DebugPreprocessor: true, } buildPath := SetupBuildPath(t, ctx) defer buildPath.RemoveAll() diff --git a/tools_loader.go b/tools_loader.go index 0b72106b..05c2ec18 100644 --- a/tools_loader.go +++ b/tools_loader.go @@ -48,19 +48,19 @@ func (s *ToolsLoader) Run(ctx *types.Context) error { folders := paths.NewPathList() builtinFolders := paths.NewPathList() - if ctx.BuiltInToolsFolders != nil || len(ctx.BuiltInLibrariesFolders) == 0 { - folders = ctx.ToolsFolders - builtinFolders = ctx.BuiltInToolsFolders + if ctx.BuiltInToolsDirs != nil || len(ctx.BuiltInLibrariesDirs) == 0 { + folders = ctx.ToolsDirs + builtinFolders = ctx.BuiltInToolsDirs } else { // Auto-detect built-in tools folders (for arduino-builder backward compatibility) // this is a deprecated feature and will be removed in the future - builtinHardwareFolder, err := ctx.BuiltInLibrariesFolders[0].Join("..").Abs() + builtinHardwareFolder, err := ctx.BuiltInLibrariesDirs[0].Join("..").Abs() if err != nil { fmt.Println("Error detecting ") } - for _, folder := range ctx.ToolsFolders { + for _, folder := range ctx.ToolsDirs { if !strings.Contains(folder.String(), builtinHardwareFolder.String()) { // TODO: make a function to check for subfolders folders = append(folders, folder) } else { diff --git a/types/context.go b/types/context.go index 223a6bb2..c718fbd1 100644 --- a/types/context.go +++ b/types/context.go @@ -23,16 +23,16 @@ type ProgressStruct struct { // Context structure type Context struct { // Build options - HardwareFolders paths.PathList - ToolsFolders paths.PathList - BuiltInToolsFolders paths.PathList - BuiltInLibrariesFolders paths.PathList - OtherLibrariesFolders paths.PathList - SketchLocation *paths.Path - WatchedLocations paths.PathList - ArduinoAPIVersion string - FQBN *cores.FQBN - CodeCompleteAt string + HardwareDirs paths.PathList + ToolsDirs paths.PathList + BuiltInToolsDirs paths.PathList + BuiltInLibrariesDirs paths.PathList + OtherLibrariesDirs paths.PathList + SketchLocation *paths.Path + WatchedLocations paths.PathList + ArduinoAPIVersion string + FQBN *cores.FQBN + CodeCompleteAt string // Build options are serialized here BuildOptionsJson string @@ -115,10 +115,10 @@ type Context struct { func (ctx *Context) ExtractBuildOptions() properties.Map { opts := make(properties.Map) - opts["hardwareFolders"] = strings.Join(ctx.HardwareFolders.AsStrings(), ",") - opts["toolsFolders"] = strings.Join(ctx.ToolsFolders.AsStrings(), ",") - opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesFolders.AsStrings(), ",") - opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesFolders.AsStrings(), ",") + opts["hardwareFolders"] = strings.Join(ctx.HardwareDirs.AsStrings(), ",") + opts["toolsFolders"] = strings.Join(ctx.ToolsDirs.AsStrings(), ",") + opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesDirs.AsStrings(), ",") + opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesDirs.AsStrings(), ",") opts["sketchLocation"] = ctx.SketchLocation.String() var additionalFilesRelative []string if ctx.Sketch != nil { @@ -139,10 +139,10 @@ func (ctx *Context) ExtractBuildOptions() properties.Map { } func (ctx *Context) InjectBuildOptions(opts properties.Map) { - ctx.HardwareFolders = paths.NewPathList(strings.Split(opts["hardwareFolders"], ",")...) - ctx.ToolsFolders = paths.NewPathList(strings.Split(opts["toolsFolders"], ",")...) - ctx.BuiltInLibrariesFolders = paths.NewPathList(strings.Split(opts["builtInLibrariesFolders"], ",")...) - ctx.OtherLibrariesFolders = paths.NewPathList(strings.Split(opts["otherLibrariesFolders"], ",")...) + ctx.HardwareDirs = paths.NewPathList(strings.Split(opts["hardwareFolders"], ",")...) + ctx.ToolsDirs = paths.NewPathList(strings.Split(opts["toolsFolders"], ",")...) + ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(opts["builtInLibrariesFolders"], ",")...) + ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(opts["otherLibrariesFolders"], ",")...) ctx.SketchLocation = paths.New(opts["sketchLocation"]) fqbn, err := cores.ParseFQBN(opts["fqbn"]) if err != nil { From 16a67eca11f8557b4ff059582c203a96b86040b7 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 6 Aug 2018 17:41:54 +0200 Subject: [PATCH 37/57] Using semver for versioning --- setup_build_properties.go | 4 ++-- test/tools_loader_test.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/setup_build_properties.go b/setup_build_properties.go index 9d78b08f..8d4395bb 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -100,11 +100,11 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { for _, tool := range ctx.AllTools { buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.InstallDir.String() + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path"] = tool.InstallDir.String() } for _, tool := range ctx.RequiredTools { buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version+".path"] = tool.InstallDir.String() + buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path"] = tool.InstallDir.String() } if !utils.MapStringStringHas(buildProperties, "software") { diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index b2499ec4..d58c90ec 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -52,8 +52,8 @@ func (s ByToolIDAndVersion) Less(i, j int) bool { if s[i].Tool.Name != s[j].Tool.Name { return s[i].Tool.Name < s[j].Tool.Name } - if s[i].Version != s[j].Version { - return s[i].Version < s[j].Version + if !s[i].Version.Equal(s[j].Version) { + return s[i].Version.LessThan(s[j].Version) } return s[i].InstallDir.String() < s[j].InstallDir.String() } From beb2ff2b4213fed28dc055246cc676d2ea7e2900 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 6 Aug 2018 18:29:49 +0200 Subject: [PATCH 38/57] Using semver for versioning (part 2) --- print_used_libraries_if_verbose.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/print_used_libraries_if_verbose.go b/print_used_libraries_if_verbose.go index f5113839..4d8ecb9c 100644 --- a/print_used_libraries_if_verbose.go +++ b/print_used_libraries_if_verbose.go @@ -47,11 +47,11 @@ func (s *PrintUsedLibrariesIfVerbose) Run(ctx *types.Context) error { } for _, library := range ctx.ImportedLibraries { - legacy := constants.EMPTY_STRING + legacy := "" if library.IsLegacy { legacy = constants.MSG_LIB_LEGACY } - if library.Version == constants.EMPTY_STRING { + if library.Version.String() == "" { logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY, library.Name, library.InstallDir, legacy) } else { logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY_AT_VERSION, library.Name, library.Version, library.InstallDir, legacy) From e8663728752c05c46381b799e0bc49ba41354a85 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 8 Aug 2018 18:30:25 +0200 Subject: [PATCH 39/57] Moving under github.com/arduino imports --- add_additional_entries_to_context.go | 2 +- arduino-builder/main.go | 7 +++---- container_find_includes.go | 2 +- fail_if_imported_library_is_wrong.go | 2 +- grpc/rpc.go | 2 +- hardware_loader.go | 2 +- libraries_loader.go | 7 +++---- phases/libraries_builder.go | 2 +- resolve_library.go | 2 +- rewrite_hardware_keys.go | 2 +- setup_build_properties.go | 2 +- test/add_build_board_property_if_missing_test.go | 5 ++--- test/helper.go | 2 +- test/helper_tools_downloader.go | 3 +-- test/libraries_loader_test.go | 2 +- test/rewrite_hardware_keys_test.go | 2 +- test/sketch_source_merger_test.go | 3 +-- test/tools_loader_test.go | 2 +- test/unused_compiled_libraries_remover_test.go | 2 +- types/context.go | 11 +++++------ types/types.go | 2 +- unused_compiled_libraries_remover.go | 2 +- warn_about_platform_rewrites.go | 2 +- 23 files changed, 32 insertions(+), 38 deletions(-) diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go index ab26bcc9..eaf32700 100644 --- a/add_additional_entries_to_context.go +++ b/add_additional_entries_to_context.go @@ -33,7 +33,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/cores" + "github.com/arduino/arduino-cli/arduino/cores" ) type AddAdditionalEntriesToContext struct{} diff --git a/arduino-builder/main.go b/arduino-builder/main.go index c6815e4b..1ddfe464 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -38,20 +38,19 @@ import ( "os" "os/exec" "runtime" - "strings" - "syscall" - "runtime/pprof" "runtime/trace" + "strings" + "syscall" "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/grpc" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/go-errors/errors" ) diff --git a/container_find_includes.go b/container_find_includes.go index 743e17c4..a087805e 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -117,8 +117,8 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/go-errors/errors" ) diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 4610a843..940e8cc3 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -33,7 +33,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries" ) type FailIfImportedLibraryIsWrong struct{} diff --git a/grpc/rpc.go b/grpc/rpc.go index da2dc679..c01f290e 100644 --- a/grpc/rpc.go +++ b/grpc/rpc.go @@ -8,8 +8,8 @@ import ( "os" "strings" + "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/cores" builder "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/i18n" diff --git a/hardware_loader.go b/hardware_loader.go index 532fa5b0..e337592c 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -32,7 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" + "github.com/arduino/arduino-cli/arduino/cores/packagemanager" ) type HardwareLoader struct{} diff --git a/libraries_loader.go b/libraries_loader.go index e6da1f99..37dc3820 100644 --- a/libraries_loader.go +++ b/libraries_loader.go @@ -32,12 +32,11 @@ package builder import ( "os" - "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" - "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesresolver" - "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" + "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" ) type LibrariesLoader struct{} diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index f6780542..a6a2a581 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -38,9 +38,9 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC = map[string]bool{".a": true} diff --git a/resolve_library.go b/resolve_library.go index 4b9b4412..2760b8ae 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -33,7 +33,7 @@ import ( "fmt" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries" ) func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go index 5f3ce87a..d4a02d18 100644 --- a/rewrite_hardware_keys.go +++ b/rewrite_hardware_keys.go @@ -32,7 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/cores" + "github.com/arduino/arduino-cli/arduino/cores" ) type RewriteHardwareKeys struct{} diff --git a/setup_build_properties.go b/setup_build_properties.go index 8d4395bb..b7b14c9f 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -38,9 +38,9 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/go-properties-map" "github.com/arduino/go-timeutils" - "github.com/bcmi-labs/arduino-cli/arduino/cores" ) type SetupBuildProperties struct{} diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index cc51ecb0..ed6afce2 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -33,12 +33,11 @@ import ( "path/filepath" "testing" - "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/cores" - "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/cores" + "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) diff --git a/test/helper.go b/test/helper.go index ba8b6014..1f2e68d6 100644 --- a/test/helper.go +++ b/test/helper.go @@ -40,8 +40,8 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/arduino-cli/arduino/libraries" paths "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/go-errors/errors" "github.com/stretchr/testify/assert" ) diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index 30a1826a..766b6b68 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -42,12 +42,11 @@ import ( "strings" "testing" - "github.com/arduino/go-paths-helper" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/utils" + "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" "github.com/go-errors/errors" ) diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go index 54e3347e..294f40c9 100644 --- a/test/libraries_loader_test.go +++ b/test/libraries_loader_test.go @@ -37,8 +37,8 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/libraries" paths "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/stretchr/testify/require" ) diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go index 1bb25ecb..f126c8d9 100644 --- a/test/rewrite_hardware_keys_test.go +++ b/test/rewrite_hardware_keys_test.go @@ -34,8 +34,8 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/cores" properties "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/stretchr/testify/require" ) diff --git a/test/sketch_source_merger_test.go b/test/sketch_source_merger_test.go index c88b82f5..44cdb5f7 100644 --- a/test/sketch_source_merger_test.go +++ b/test/sketch_source_merger_test.go @@ -35,10 +35,9 @@ import ( "strings" "testing" - "github.com/arduino/go-paths-helper" - "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go index d58c90ec..322cdc58 100644 --- a/test/tools_loader_test.go +++ b/test/tools_loader_test.go @@ -35,8 +35,8 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/cores" paths "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/cores" "github.com/stretchr/testify/require" ) diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go index 402d8942..7f82564c 100644 --- a/test/unused_compiled_libraries_remover_test.go +++ b/test/unused_compiled_libraries_remover_test.go @@ -34,8 +34,8 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/arduino/libraries" paths "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" "github.com/stretchr/testify/require" ) diff --git a/types/context.go b/types/context.go index c718fbd1..b84b9cf1 100644 --- a/types/context.go +++ b/types/context.go @@ -3,15 +3,14 @@ package types import ( "strings" - "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesmanager" - "github.com/bcmi-labs/arduino-cli/arduino/libraries/librariesresolver" - "github.com/arduino/arduino-builder/i18n" + "github.com/arduino/arduino-cli/arduino/cores" + "github.com/arduino/arduino-cli/arduino/cores/packagemanager" + "github.com/arduino/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" + "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" "github.com/arduino/go-paths-helper" "github.com/arduino/go-properties-map" - "github.com/bcmi-labs/arduino-cli/arduino/cores" - "github.com/bcmi-labs/arduino-cli/arduino/cores/packagemanager" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type ProgressStruct struct { diff --git a/types/types.go b/types/types.go index 84b344ab..347925d7 100644 --- a/types/types.go +++ b/types/types.go @@ -33,8 +33,8 @@ import ( "fmt" "strconv" + "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/go-paths-helper" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" ) type SourceFile struct { diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go index 2599d242..93576ff3 100644 --- a/unused_compiled_libraries_remover.go +++ b/unused_compiled_libraries_remover.go @@ -33,7 +33,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "github.com/bcmi-labs/arduino-cli/arduino/libraries" + "github.com/arduino/arduino-cli/arduino/libraries" ) type UnusedCompiledLibrariesRemover struct{} diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go index 7ff2c5fa..bdc930dc 100644 --- a/warn_about_platform_rewrites.go +++ b/warn_about_platform_rewrites.go @@ -34,7 +34,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/bcmi-labs/arduino-cli/arduino/cores" + "github.com/arduino/arduino-cli/arduino/cores" ) type WarnAboutPlatformRewrites struct{} From 8a51a33ba700749a9e5028e09985a2cb75f16e0e Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 Aug 2018 12:09:50 +0200 Subject: [PATCH 40/57] Renamed field Board.BoardId -> Board.BoardID --- add_build_board_property_if_missing.go | 4 ++-- target_board_resolver.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go index 8c19e15a..61888693 100644 --- a/add_build_board_property_if_missing.go +++ b/add_build_board_property_if_missing.go @@ -48,14 +48,14 @@ func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { for _, platformRelease := range platform.Releases { for _, board := range platformRelease.Boards { if board.Properties["build.board"] == "" { - board.Properties["build.board"] = strings.ToUpper(platform.Architecture + "_" + board.BoardId) + board.Properties["build.board"] = strings.ToUpper(platform.Architecture + "_" + board.BoardID) logger.Fprintln( os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_MISSING_BUILD_BOARD, aPackage.Name, platform.Architecture, - board.BoardId, + board.BoardID, board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) } } diff --git a/target_board_resolver.go b/target_board_resolver.go index 9c09fc4a..4463ea9b 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -57,7 +57,7 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { core = core[strings.Index(core, ":")+1:] if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardId, targetPlatform.InstallDir) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardID, targetPlatform.InstallDir) logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.InstallDir) } From f99ab5a8093d682b710b9eebf67304aa829f5b15 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 Aug 2018 13:51:25 +0200 Subject: [PATCH 41/57] Renamed field Board.BoardId -> Board.BoardID (part 2...) --- ...add_build_board_property_if_missing_test.go | 4 ++-- test/hardware_loader_test.go | 18 +++++++++--------- test/target_board_resolver_test.go | 12 ++++++------ 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index ed6afce2..dfea70c4 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -73,7 +73,7 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { require.NotNil(t, targetPlatform.Platform) require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardId) + require.Equal(t, "mymega", targetBoard.BoardID) require.Equal(t, constants.EMPTY_STRING, targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) require.Equal(t, "AVR_MYMEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) } @@ -102,7 +102,7 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardId) + require.Equal(t, "mymega", targetBoard.BoardID) require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) require.Equal(t, "AVR_MEGA2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) } diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index e7f19afa..c0b60f4c 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -60,15 +60,15 @@ func TestLoadHardware(t *testing.T) { require.NotNil(t, packages.Packages["arduino"]) require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) + require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardId) + require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties["menu.cpu.atmega123"]) @@ -114,15 +114,15 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.NotNil(t, packages.Packages["arduino"]) require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardId) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardId) + require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardId) + require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) avrPlatform := packages.Packages["arduino"].Platforms["avr"].Releases[""] require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties["name"]) @@ -140,7 +140,7 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { myAVRPlatform := packages.Packages["my_avr_platform"] //require.Equal(t, "hello world", myAVRPlatform.Properties["example"]) myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"].Releases[""] - require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardId) + require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardID) require.False(t, utils.MapStringStringHas(myAVRPlatformAvrArch.Properties, "preproc.includes.flags")) @@ -181,7 +181,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { samdPlatform := packages.Packages["arduino"].Platforms["samd"].Releases["1.6.5"] require.Equal(t, 3, len(samdPlatform.Boards)) - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardId) + require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardID) require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties["_id"]) require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties["build.variant"]) @@ -198,7 +198,7 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases["1.0.0"] require.Equal(t, 3, len(avrRedBearPlatform.Boards)) - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardId) + require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardID) require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties["_id"]) require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties["build.core"]) } diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index 581d58a8..ee2dd903 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -60,7 +60,7 @@ func TestTargetBoardResolverUno(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "uno", targetBoard.BoardId) + require.Equal(t, "uno", targetBoard.BoardID) require.Equal(t, "atmega328p", targetBoard.Properties["build.mcu"]) } @@ -85,7 +85,7 @@ func TestTargetBoardResolverDue(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "sam", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "arduino_due_x", targetBoard.BoardId) + require.Equal(t, "arduino_due_x", targetBoard.BoardID) require.Equal(t, "cortex-m3", targetBoard.Properties["build.mcu"]) } @@ -110,7 +110,7 @@ func TestTargetBoardResolverMega1280(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardId) + require.Equal(t, "mega", targetBoard.BoardID) require.Equal(t, "atmega1280", targetBoard.Properties["build.mcu"]) require.Equal(t, "AVR_MEGA", targetBoard.Properties["build.board"]) } @@ -136,7 +136,7 @@ func TestTargetBoardResolverMega2560(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardId) + require.Equal(t, "mega", targetBoard.BoardID) require.Equal(t, "atmega2560", targetBoard.Properties["build.mcu"]) require.Equal(t, "AVR_MEGA2560", targetBoard.Properties["build.board"]) } @@ -162,7 +162,7 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "custom_yun", targetBoard.BoardId) + require.Equal(t, "custom_yun", targetBoard.BoardID) require.Equal(t, "atmega32u4", targetBoard.Properties["build.mcu"]) require.Equal(t, "AVR_YUN", targetBoard.Properties["build.board"]) } @@ -188,7 +188,7 @@ func TestTargetBoardResolverCustomCore(t *testing.T) { targetPlatform := ctx.TargetPlatform require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard - require.Equal(t, "attiny841", targetBoard.BoardId) + require.Equal(t, "attiny841", targetBoard.BoardID) require.Equal(t, "tiny841", ctx.BuildCore) require.Equal(t, "tiny14", targetBoard.Properties["build.variant"]) } From f9276b5710cc5f2300d5e0bb352ed0771864b876 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 Aug 2018 16:59:09 +0200 Subject: [PATCH 42/57] go-paths-helper API change --- container_find_includes.go | 2 +- fail_if_imported_library_is_wrong.go | 2 +- load_previous_build_options.go | 9 +-- merge_sketch_with_bootloader.go | 6 +- phases/sketch_builder.go | 2 +- platform_keys_rewrite_loader.go | 2 +- test/additional_sketch_files_copier_test.go | 2 +- test/builder_test.go | 78 +++++++++---------- test/helper_tools_downloader.go | 54 ++++++------- test/merge_sketch_with_bootloader_test.go | 2 +- test/store_build_options_map_test.go | 2 +- .../unused_compiled_libraries_remover_test.go | 12 +-- ...uild_path_if_build_options_changed_test.go | 8 +- unused_compiled_libraries_remover.go | 4 +- 14 files changed, 90 insertions(+), 95 deletions(-) diff --git a/container_find_includes.go b/container_find_includes.go index a087805e..db5a591d 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -144,7 +144,7 @@ func (s *ContainerFindIncludes) Run(ctx *types.Context) error { sourceFilePaths := ctx.CollectedSourceFiles queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, ctx.SketchBuildPath, false /* recurse */) srcSubfolderPath := ctx.SketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) - if isDir, _ := srcSubfolderPath.IsDir(); isDir { + if srcSubfolderPath.IsDir() { queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, srcSubfolderPath, true /* recurse */) } diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 940e8cc3..60068145 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -47,7 +47,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { for _, library := range ctx.ImportedLibraries { if !library.IsLegacy { - if isDir, _ := library.InstallDir.Join(constants.LIBRARY_FOLDER_ARCH).IsDir(); isDir { + if library.InstallDir.Join(constants.LIBRARY_FOLDER_ARCH).IsDir() { return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) } for _, propName := range libraries.MandatoryProperties { diff --git a/load_previous_build_options.go b/load_previous_build_options.go index 93997271..2c22d2e8 100644 --- a/load_previous_build_options.go +++ b/load_previous_build_options.go @@ -40,12 +40,8 @@ type LoadPreviousBuildOptionsMap struct{} func (s *LoadPreviousBuildOptionsMap) Run(ctx *types.Context) error { buildOptionsFile := ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE) - if exist, err := buildOptionsFile.Exist(); err == nil { - if !exist { - return nil - } - } else { - return i18n.WrapError(err) + if buildOptionsFile.NotExist() { + return nil } bytes, err := buildOptionsFile.ReadFile() @@ -54,6 +50,5 @@ func (s *LoadPreviousBuildOptionsMap) Run(ctx *types.Context) error { } ctx.BuildOptionsJsonPrevious = string(bytes) - return nil } diff --git a/merge_sketch_with_bootloader.go b/merge_sketch_with_bootloader.go index 9df6c911..d0fdd5cd 100644 --- a/merge_sketch_with_bootloader.go +++ b/merge_sketch_with_bootloader.go @@ -58,9 +58,9 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { sketchInSubfolder := buildPath.Join(constants.FOLDER_SKETCH, sketchFileName+".hex") var builtSketchPath *paths.Path - if exist, _ := sketchInBuildPath.Exist(); exist { + if sketchInBuildPath.Exist() { builtSketchPath = sketchInBuildPath - } else if exist, _ := sketchInSubfolder.Exist(); exist { + } else if sketchInSubfolder.Exist() { builtSketchPath = sketchInSubfolder } else { return nil @@ -75,7 +75,7 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { bootloader = buildProperties.ExpandPropsInString(bootloader) bootloaderPath := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH).Join(constants.FOLDER_BOOTLOADERS, bootloader) - if exist, _ := bootloaderPath.Exist(); !exist { + if bootloaderPath.NotExist() { logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_BOOTLOADER_FILE_MISSING, bootloaderPath) return nil } diff --git a/phases/sketch_builder.go b/phases/sketch_builder.go index 01acfe62..55c88e50 100644 --- a/phases/sketch_builder.go +++ b/phases/sketch_builder.go @@ -55,7 +55,7 @@ func (s *SketchBuilder) Run(ctx *types.Context) error { // The "src/" subdirectory of a sketch is compiled recursively sketchSrcPath := sketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) - if isDir, _ := sketchSrcPath.IsDir(); isDir { + if sketchSrcPath.IsDir() { srcObjectFiles, err := builder_utils.CompileFiles(ctx, sketchSrcPath, true, sketchSrcPath, buildProperties, includes) if err != nil { return i18n.WrapError(err) diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go index fb475e53..9b0fd67d 100644 --- a/platform_keys_rewrite_loader.go +++ b/platform_keys_rewrite_loader.go @@ -89,7 +89,7 @@ func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { func findPlatformKeysRewriteTxt(folders paths.PathList) (*paths.Path, error) { for _, folder := range folders { txtPath := folder.Join(constants.FILE_PLATFORM_KEYS_REWRITE_TXT) - if exist, err := txtPath.Exist(); exist { + if exist, err := txtPath.ExistCheck(); exist { return txtPath, nil } else if err != nil { return nil, i18n.WrapError(err) diff --git a/test/additional_sketch_files_copier_test.go b/test/additional_sketch_files_copier_test.go index c6a901ab..7656ab34 100644 --- a/test/additional_sketch_files_copier_test.go +++ b/test/additional_sketch_files_copier_test.go @@ -74,7 +74,7 @@ func TestCopyOtherFiles(t *testing.T) { NoError(t, err) } - exist, err1 := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Exist() + exist, err1 := buildPath.Join(constants.FOLDER_SKETCH, "header.h").ExistCheck() NoError(t, err1) require.True(t, exist) diff --git a/test/builder_test.go b/test/builder_test.go index f41954f8..78317b55 100644 --- a/test/builder_test.go +++ b/test/builder_test.go @@ -71,19 +71,19 @@ func TestBuilderEmptySketch(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("sketch.ino.elf").Exist() + exist, err = buildPath.Join("sketch.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("sketch.ino.hex").Exist() + exist, err = buildPath.Join("sketch.ino.hex").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -101,22 +101,22 @@ func TestBuilderBridge(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").Exist() + exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").Exist() + exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -134,22 +134,22 @@ func TestBuilderSketchWithConfig(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("sketch_with_config.ino.elf").Exist() + exist, err = buildPath.Join("sketch_with_config.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("sketch_with_config.ino.hex").Exist() + exist, err = buildPath.Join("sketch_with_config.ino.hex").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -172,22 +172,22 @@ func TestBuilderBridgeTwice(t *testing.T) { err = command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").Exist() + exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").Exist() + exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -206,28 +206,28 @@ func TestBuilderBridgeSAM(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "syscalls_sam3.c.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "syscalls_sam3.c.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_CORE, "avr", "dtostrf.c.d").Exist() + exist, err = buildPath.Join(constants.FOLDER_CORE, "avr", "dtostrf.c.d").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").Exist() + exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.bin").Exist() + exist, err = buildPath.Join("Bridge.ino.bin").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) @@ -252,22 +252,22 @@ func TestBuilderBridgeRedBearLab(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").Exist() + exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).Exist() + exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").Exist() + exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").Exist() + exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").Exist() + exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").Exist() + exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -347,10 +347,10 @@ func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testin err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join("libraries", "SPI").Exist() + exist, err := buildPath.Join("libraries", "SPI").ExistCheck() NoError(t, err) require.False(t, exist) - exist, err = buildPath.Join("libraries", "Bridge").Exist() + exist, err = buildPath.Join("libraries", "Bridge").ExistCheck() NoError(t, err) require.True(t, exist) } diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index 5ff2f824..c3b32ff0 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -317,7 +317,7 @@ func downloadToolsMultipleVersions(tools []Tool, index map[string]interface{}) e for _, tool := range tools { if !toolAlreadyDownloadedAndUnpacked(toolsFolder, tool) { - if exist, _ := toolsFolder.Join(tool.Name).Exist(); exist { + if toolsFolder.Join(tool.Name).Exist() { if err := toolsFolder.Join(tool.Name).RemoveAll(); err != nil { return i18n.WrapError(err) } @@ -366,8 +366,7 @@ func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, c } func boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) bool { - exist, _ := targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).Exist() - return exist + return targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).Exist() } func allCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) (bool, error) { @@ -386,7 +385,7 @@ func allCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) func coreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) (bool, error) { corePath := targetPath.Join(core.Maintainer, core.Arch) - if exist, _ := corePath.Exist(); !exist { + if corePath.NotExist() { return false, nil } platform, err := properties.LoadFromPath(corePath.Join("platform.txt")) @@ -412,8 +411,7 @@ func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, t } func boardManagerToolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { - exist, _ := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).Exist() - return exist + return targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).Exist() } func allToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) bool { @@ -426,8 +424,7 @@ func allToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) } func toolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { - exist, _ := targetPath.Join(tool.Name, tool.Version).Exist() - return exist + return targetPath.Join(tool.Name, tool.Version).Exist() } func allLibrariesAlreadyDownloadedAndUnpacked(targetPath *paths.Path, libraries []Library) bool { @@ -440,12 +437,12 @@ func allLibrariesAlreadyDownloadedAndUnpacked(targetPath *paths.Path, libraries } func libraryAlreadyDownloadedAndUnpacked(targetPath *paths.Path, library Library) bool { - exist, _ := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).Exist() - if !exist { + libPath := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)) + if !libPath.Exist() { return false } - libProps, err := properties.LoadFromPath(targetPath.Join(strings.Replace(library.Name, " ", "_", -1), "library.properties")) + libProps, err := properties.LoadFromPath(libPath.Join("library.properties")) if err != nil { return false } @@ -474,7 +471,7 @@ func downloadAndUnpackCore(core Core, url string, targetPath *paths.Path) error packagerPath := targetPath.Join(core.Maintainer) corePath := targetPath.Join(core.Maintainer, core.Arch) - if exist, _ := corePath.Exist(); exist { + if corePath.Exist() { if err := corePath.RemoveAll(); err != nil { return i18n.WrapError(err) } @@ -518,26 +515,27 @@ func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath *paths. } defer unpackFolder.RemoveAll() - if exist, _ := targetPath.Join(core.Maintainer, "hardware", core.Arch).Exist(); exist { - if err := targetPath.Join(core.Maintainer, "hardware", core.Arch).RemoveAll(); err != nil { + corePath := targetPath.Join(core.Maintainer, "hardware", core.Arch) + if corePath.Exist() { + if err := corePath.RemoveAll(); err != nil { return i18n.WrapError(err) } } if len(files) == 1 && files[0].IsDir() { - if err := targetPath.Join(core.Maintainer, "hardware", core.Arch).MkdirAll(); err != nil { + if err := corePath.MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), corePath.Join(core.Version)) if err != nil { return i18n.WrapError(err) } } else { - if err := targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).MkdirAll(); err != nil { + if err := corePath.Join(core.Version).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), corePath.Join(core.Version, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -600,28 +598,29 @@ func downloadAndUnpackTool(tool Tool, url string, targetPath *paths.Path, delete } defer unpackFolder.RemoveAll() + toolPath := targetPath.Join(tool.Name) if deleteIfMissing { - if exist, _ := targetPath.Join(tool.Name).Exist(); exist { - if err := targetPath.Join(tool.Name).MkdirAll(); err != nil { + if toolPath.Exist() { + if err := toolPath.MkdirAll(); err != nil { return i18n.WrapError(err) } } } if len(files) == 1 && files[0].IsDir() { - if err := targetPath.Join(tool.Name).MkdirAll(); err != nil { + if err := toolPath.MkdirAll(); err != nil { return i18n.WrapError(err) } - err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(tool.Name, tool.Version)) + err = copyRecursive(unpackFolder.Join(files[0].Name()), toolPath.Join(tool.Version)) if err != nil { return i18n.WrapError(err) } } else { - if err := targetPath.Join(tool.Name, tool.Version).MkdirAll(); err != nil { + if err := toolPath.Join(tool.Version).MkdirAll(); err != nil { return i18n.WrapError(err) } for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(tool.Name, tool.Version, file.Name())) + err = copyRecursive(unpackFolder.Join(file.Name()), toolPath.Join(tool.Version, file.Name())) if err != nil { return i18n.WrapError(err) } @@ -783,13 +782,14 @@ func downloadAndUnpackLibrary(library Library, url string, targetPath *paths.Pat } defer unpackFolder.RemoveAll() - if exist, _ := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).Exist(); exist { - if err := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)).RemoveAll(); err != nil { + libPath := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)) + if libPath.Exist() { + if err := libPath.RemoveAll(); err != nil { return i18n.WrapError(err) } } - err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(strings.Replace(library.Name, " ", "_", -1))) + err = copyRecursive(unpackFolder.Join(files[0].Name()), libPath) if err != nil { return i18n.WrapError(err) } diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go index a83ee92c..4a3c0898 100644 --- a/test/merge_sketch_with_bootloader_test.go +++ b/test/merge_sketch_with_bootloader_test.go @@ -158,7 +158,7 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { err := command.Run(ctx) NoError(t, err) - exist, err := buildPath.Join("sketch.ino.with_bootloader.hex").Exist() + exist, err := buildPath.Join("sketch.ino.with_bootloader.hex").ExistCheck() require.NoError(t, err) require.False(t, exist) } diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go index 9d1719ff..da6e2af7 100644 --- a/test/store_build_options_map_test.go +++ b/test/store_build_options_map_test.go @@ -66,7 +66,7 @@ func TestStoreBuildOptionsMap(t *testing.T) { NoError(t, err) } - exist, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).Exist() + exist, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).ExistCheck() NoError(t, err) require.True(t, exist) diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go index 7f82564c..08cfbc05 100644 --- a/test/unused_compiled_libraries_remover_test.go +++ b/test/unused_compiled_libraries_remover_test.go @@ -56,13 +56,13 @@ func TestUnusedCompiledLibrariesRemover(t *testing.T) { err = cmd.Run(ctx) NoError(t, err) - exist, err := temp.Join("SPI").Exist() + exist, err := temp.Join("SPI").ExistCheck() require.NoError(t, err) require.False(t, exist) - exist, err = temp.Join("Bridge").Exist() + exist, err = temp.Join("Bridge").ExistCheck() NoError(t, err) require.True(t, exist) - exist, err = temp.Join("dummy_file").Exist() + exist, err = temp.Join("dummy_file").ExistCheck() NoError(t, err) require.True(t, exist) } @@ -94,13 +94,13 @@ func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { err = cmd.Run(ctx) NoError(t, err) - exist, err := temp.Join("SPI").Exist() + exist, err := temp.Join("SPI").ExistCheck() require.NoError(t, err) require.False(t, exist) - exist, err = temp.Join("Bridge").Exist() + exist, err = temp.Join("Bridge").ExistCheck() require.NoError(t, err) require.False(t, exist) - exist, err = temp.Join("dummy_file").Exist() + exist, err = temp.Join("dummy_file").ExistCheck() NoError(t, err) require.True(t, exist) } diff --git a/test/wipeout_build_path_if_build_options_changed_test.go b/test/wipeout_build_path_if_build_options_changed_test.go index b0498a59..64212fa0 100644 --- a/test/wipeout_build_path_if_build_options_changed_test.go +++ b/test/wipeout_build_path_if_build_options_changed_test.go @@ -58,7 +58,7 @@ func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { NoError(t, err) } - exist, err := buildPath.Exist() + exist, err := buildPath.ExistCheck() NoError(t, err) require.True(t, exist) @@ -66,7 +66,7 @@ func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { NoError(t, err) require.Equal(t, 0, len(files)) - exist, err = buildPath.Join("should_be_deleted.txt").Exist() + exist, err = buildPath.Join("should_be_deleted.txt").ExistCheck() require.NoError(t, err) require.False(t, exist) } @@ -90,7 +90,7 @@ func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing. NoError(t, err) } - exist, err := buildPath.Exist() + exist, err := buildPath.ExistCheck() NoError(t, err) require.True(t, exist) @@ -98,7 +98,7 @@ func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing. NoError(t, err) require.Equal(t, 1, len(files)) - exist, err = buildPath.Join("should_not_be_deleted.txt").Exist() + exist, err = buildPath.Join("should_not_be_deleted.txt").ExistCheck() NoError(t, err) require.True(t, exist) } diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go index 93576ff3..7a940859 100644 --- a/unused_compiled_libraries_remover.go +++ b/unused_compiled_libraries_remover.go @@ -41,7 +41,7 @@ type UnusedCompiledLibrariesRemover struct{} func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { librariesBuildPath := ctx.LibrariesBuildPath - if exist, _ := librariesBuildPath.Exist(); !exist { + if librariesBuildPath.NotExist() { return nil } @@ -52,7 +52,7 @@ func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { return i18n.WrapError(err) } for _, file := range files { - if isDir, _ := file.IsDir(); isDir { + if file.IsDir() { if !utils.SliceContains(libraryNames, file.Base()) { if err := file.RemoveAll(); err != nil { return i18n.WrapError(err) From bb7d413ce08a6f05710f4a511680fbb1eee87720 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Wed, 12 Sep 2018 14:54:40 +0200 Subject: [PATCH 43/57] Use ctx.PackageManager.GetInstalledPlatformRelease instead of PlatformRelease.GetInstalled --- hardware_loader.go | 12 +++++++----- setup_build_properties.go | 9 +++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/hardware_loader.go b/hardware_loader.go index e337592c..ecea2cc9 100644 --- a/hardware_loader.go +++ b/hardware_loader.go @@ -38,11 +38,13 @@ import ( type HardwareLoader struct{} func (s *HardwareLoader) Run(ctx *types.Context) error { - pm := packagemanager.NewPackageManager(nil, nil, nil, nil) - if err := pm.LoadHardwareFromDirectories(ctx.HardwareDirs); err != nil { - return i18n.WrapError(err) + if ctx.PackageManager == nil { + pm := packagemanager.NewPackageManager(nil, nil, nil, nil) + if err := pm.LoadHardwareFromDirectories(ctx.HardwareDirs); err != nil { + return i18n.WrapError(err) + } + ctx.PackageManager = pm } - ctx.PackageManager = pm - ctx.Hardware = pm.GetPackages() + ctx.Hardware = ctx.PackageManager.GetPackages() return nil } diff --git a/setup_build_properties.go b/setup_build_properties.go index b7b14c9f..4b977e27 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -87,15 +87,16 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { if variant == "" { buildProperties["build.variant.path"] = "" } else { - var variantPlatform *cores.PlatformRelease + var variantPlatformRelease *cores.PlatformRelease variantParts := strings.Split(variant, ":") if len(variantParts) > 1 { - variantPlatform = packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture].GetInstalled() + variantPlatform := packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture] + variantPlatformRelease = ctx.PackageManager.GetInstalledPlatformRelease(variantPlatform) variant = variantParts[1] } else { - variantPlatform = targetPlatform + variantPlatformRelease = targetPlatform } - buildProperties["build.variant.path"] = variantPlatform.InstallDir.Join("variants", variant).String() + buildProperties["build.variant.path"] = variantPlatformRelease.InstallDir.Join("variants", variant).String() } for _, tool := range ctx.AllTools { From e74320a377f2fa14be4f7d4b3588666a240a4878 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 2 Oct 2018 13:44:26 +0200 Subject: [PATCH 44/57] Adopting ordered properties map --- add_build_board_property_if_missing.go | 6 +- arduino-builder/main.go | 4 +- builder_utils/utils.go | 42 +++---- container_build_options.go | 1 - container_find_includes.go | 2 +- create_build_options_map.go | 1 + create_cmake_rule.go | 8 +- ctags/ctags_properties.go | 6 +- ctags_runner.go | 2 +- dump_build_properties.go | 2 +- gcc_preproc_runner.go | 6 +- load_vid_pid_specific_properties.go | 8 +- merge_sketch_with_bootloader.go | 9 +- phases/core_builder.go | 6 +- phases/libraries_builder.go | 14 ++- phases/linker.go | 18 +-- phases/sizer.go | 22 ++-- preprocess_sketch.go | 12 +- recipe_runner.go | 7 +- rewrite_hardware_keys.go | 6 +- set_custom_build_properties.go | 6 +- setup_build_properties.go | 56 ++++----- target_board_resolver.go | 2 +- ...dd_build_board_property_if_missing_test.go | 8 +- test/hardware_loader_test.go | 77 ++++++------ test/load_vid_pid_specific_properties_test.go | 14 +-- test/merge_sketch_with_bootloader_test.go | 4 +- test/recipe_runner_test.go | 6 +- test/rewrite_hardware_keys_test.go | 14 +-- test/setup_build_properties_test.go | 115 +++++++++--------- test/target_board_resolver_test.go | 18 +-- types/context.go | 44 +++---- utils/utils.go | 5 - warn_about_arch_incompatible_libraries.go | 2 +- warn_about_platform_rewrites.go | 6 +- 35 files changed, 278 insertions(+), 281 deletions(-) diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go index 61888693..c94b7a14 100644 --- a/add_build_board_property_if_missing.go +++ b/add_build_board_property_if_missing.go @@ -47,8 +47,8 @@ func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { for _, platform := range aPackage.Platforms { for _, platformRelease := range platform.Releases { for _, board := range platformRelease.Boards { - if board.Properties["build.board"] == "" { - board.Properties["build.board"] = strings.ToUpper(platform.Architecture + "_" + board.BoardID) + 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, @@ -56,7 +56,7 @@ func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { aPackage.Name, platform.Architecture, board.BoardID, - board.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + board.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) } } } diff --git a/arduino-builder/main.go b/arduino-builder/main.go index 6ef081aa..a8199de1 100644 --- a/arduino-builder/main.go +++ b/arduino-builder/main.go @@ -50,7 +50,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" "github.com/go-errors/errors" ) @@ -240,7 +240,7 @@ func main() { } if *buildOptionsFileFlag != "" { - buildOptions := make(properties.Map) + buildOptions := properties.NewMap() if _, err := os.Stat(*buildOptionsFileFlag); err == nil { data, err := ioutil.ReadFile(*buildOptionsFileFlag) if err != nil { diff --git a/builder_utils/utils.go b/builder_utils/utils.go index 558da29a..194dceea 100644 --- a/builder_utils/utils.go +++ b/builder_utils/utils.go @@ -42,7 +42,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) { @@ -58,7 +58,7 @@ func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) { } } -func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { +func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { objectFiles, err := CompileFiles(ctx, sourcePath, false, buildPath, buildProperties, includes) if err != nil { return nil, i18n.WrapError(err) @@ -80,7 +80,7 @@ func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath return objectFiles, nil } -func CompileFiles(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { +func CompileFiles(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { sObjectFiles, err := compileFilesWithExtensionWithRecipe(ctx, sourcePath, recurse, buildPath, buildProperties, includes, ".S", constants.RECIPE_S_PATTERN) if err != nil { return nil, i18n.WrapError(err) @@ -100,7 +100,7 @@ func CompileFiles(ctx *types.Context, sourcePath *paths.Path, recurse bool, buil return objectFiles, nil } -func compileFilesWithExtensionWithRecipe(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties properties.Map, includes []string, extension string, recipe string) (paths.PathList, error) { +func compileFilesWithExtensionWithRecipe(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties *properties.Map, includes []string, extension string, recipe string) (paths.PathList, error) { sources, err := findFilesInFolder(sourcePath, extension, recurse) if err != nil { return nil, i18n.WrapError(err) @@ -164,7 +164,7 @@ func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) { return sources, nil } -func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources paths.PathList, buildPath *paths.Path, buildProperties properties.Map, includes []string, recipe string) (paths.PathList, error) { +func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources paths.PathList, buildPath *paths.Path, buildProperties *properties.Map, includes []string, recipe string) (paths.PathList, error) { objectFiles := paths.NewPathList() if len(sources) == 0 { return objectFiles, nil @@ -212,19 +212,19 @@ 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) { +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[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] - properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includes, constants.SPACE) - properties[constants.BUILD_PROPERTIES_SOURCE_FILE] = source.String() + 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)) + properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, source) relativeSource, err := sourcePath.RelTo(source) if err != nil { return nil, i18n.WrapError(err) } - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = buildPath.JoinPath(relativeSource).String() + ".o" + properties.Set(constants.BUILD_PROPERTIES_OBJECT_FILE, buildPath.JoinPath(relativeSource).String()+".o") - err = paths.New(properties[constants.BUILD_PROPERTIES_OBJECT_FILE]).Parent().MkdirAll() + err = properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE).Parent().MkdirAll() if err != nil { return nil, i18n.WrapError(err) } @@ -240,10 +240,10 @@ func compileFileWithRecipe(ctx *types.Context, sourcePath *paths.Path, source *p return nil, i18n.WrapError(err) } } else if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, properties[constants.BUILD_PROPERTIES_OBJECT_FILE]) + logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, properties.Get(constants.BUILD_PROPERTIES_OBJECT_FILE)) } - return paths.New(properties[constants.BUILD_PROPERTIES_OBJECT_FILE]), nil + return properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE), nil } func ObjFileIsUpToDate(ctx *types.Context, sourceFile, objectFile, dependencyFile *paths.Path) (bool, error) { @@ -430,7 +430,7 @@ func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile *paths.Path) return true } -func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile *paths.Path, objectFilesToArchive paths.PathList, buildProperties properties.Map) (*paths.Path, error) { +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) @@ -463,9 +463,9 @@ func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile for _, objectFile := range objectFilesToArchive { properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = archiveFilePath.Base() - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = archiveFilePath.String() - properties[constants.BUILD_PROPERTIES_OBJECT_FILE] = objectFile.String() + properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE, archiveFilePath.Base()) + properties.SetPath(constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH, archiveFilePath) + properties.SetPath(constants.BUILD_PROPERTIES_OBJECT_FILE, objectFile) _, _, err := ExecRecipe(ctx, properties, constants.RECIPE_AR_PATTERN, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) if err != nil { @@ -476,7 +476,7 @@ func ArchiveCompiledFiles(ctx *types.Context, buildPath *paths.Path, archiveFile return archiveFilePath, nil } -func ExecRecipe(ctx *types.Context, buildProperties properties.Map, recipe string, removeUnsetProperties bool, stdout int, stderr int) ([]byte, []byte, error) { +func ExecRecipe(ctx *types.Context, buildProperties *properties.Map, recipe string, removeUnsetProperties bool, stdout int, stderr int) ([]byte, []byte, error) { // See util.ExecCommand for stdout/stderr arguments command, err := PrepareCommandForRecipe(ctx, buildProperties, recipe, removeUnsetProperties) if err != nil { @@ -488,9 +488,9 @@ func ExecRecipe(ctx *types.Context, buildProperties properties.Map, recipe strin const COMMANDLINE_LIMIT = 30000 -func PrepareCommandForRecipe(ctx *types.Context, buildProperties properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) { +func PrepareCommandForRecipe(ctx *types.Context, buildProperties *properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) { logger := ctx.GetLogger() - pattern := buildProperties[recipe] + pattern := buildProperties.Get(recipe) if pattern == "" { return nil, i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, recipe) } @@ -504,7 +504,7 @@ func PrepareCommandForRecipe(ctx *types.Context, buildProperties properties.Map, relativePath := "" if len(commandLine) > COMMANDLINE_LIMIT { - relativePath = buildProperties["build.path"] + relativePath = buildProperties.Get("build.path") } command, err := utils.PrepareCommand(commandLine, logger, relativePath) diff --git a/container_build_options.go b/container_build_options.go index d2e22513..67bd8917 100644 --- a/container_build_options.go +++ b/container_build_options.go @@ -53,5 +53,4 @@ func (s *ContainerBuildOptions) Run(ctx *types.Context) error { } return nil - } diff --git a/container_find_includes.go b/container_find_includes.go index c469c820..e84aaabb 100644 --- a/container_find_includes.go +++ b/container_find_includes.go @@ -130,7 +130,7 @@ func (s *ContainerFindIncludes) Run(ctx *types.Context) error { cache := readCache(cachePath) appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_CORE_PATH)) - if ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH] != "" { + if ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH) != "" { appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH)) } diff --git a/create_build_options_map.go b/create_build_options_map.go index 0a11cc29..f32019c3 100644 --- a/create_build_options_map.go +++ b/create_build_options_map.go @@ -31,6 +31,7 @@ package builder import ( "encoding/json" + "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" ) diff --git a/create_cmake_rule.go b/create_cmake_rule.go index d26fe8fc..d127ec94 100644 --- a/create_cmake_rule.go +++ b/create_cmake_rule.go @@ -87,7 +87,7 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error { } // Remove stray folders contining incompatible libraries staticLibsExtensions := func(ext string) bool { return DOTAEXTENSION[ext] } - mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] + mcu := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) var files []string utils.FindFilesInFolder(&files, libDir.Join("src").String(), staticLibsExtensions, true) for _, file := range files { @@ -98,11 +98,11 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error { } // Copy core + variant in use + preprocessed sketch in the correct folders - err := utils.CopyDir(ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_CORE_PATH], coreFolder.String(), extensions) + err := utils.CopyDir(ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_CORE_PATH), coreFolder.String(), extensions) if err != nil { fmt.Println(err) } - err = utils.CopyDir(ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH], coreFolder.Join("variant").String(), extensions) + err = utils.CopyDir(ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH), coreFolder.Join("variant").String(), extensions) if err != nil { fmt.Println(err) } @@ -202,7 +202,7 @@ func (s *ExportProjectCMake) Run(ctx *types.Context) error { } func canExportCmakeProject(ctx *types.Context) bool { - return ctx.BuildProperties["compiler.export_cmake"] != "" + return ctx.BuildProperties.Get("compiler.export_cmake") != "" } func extractCompileFlags(ctx *types.Context, receipe string, defines, libs, linkerflags, linkDirectories *[]string, logger i18n.Logger) { diff --git a/ctags/ctags_properties.go b/ctags/ctags_properties.go index 897e36a8..38f15ecf 100644 --- a/ctags/ctags_properties.go +++ b/ctags/ctags_properties.go @@ -29,10 +29,10 @@ package ctags -import properties "github.com/arduino/go-properties-map" +import properties "github.com/arduino/go-properties-orderedmap" // CtagsProperties are the platform properties needed to run ctags -var CtagsProperties = properties.Map{ +var CtagsProperties = properties.NewFromHashmap(map[string]string{ // Ctags "tools.ctags.path": "{runtime.tools.ctags.path}", "tools.ctags.cmd.path": "{path}/ctags", @@ -44,4 +44,4 @@ var CtagsProperties = properties.Map{ "preproc.macros.flags": "-w -x c++ -E -CC", //"preproc.macros.compatibility_flags": `{build.mbed_api_include} {build.nRF51822_api_include} {build.ble_api_include} {compiler.libsam.c.flags} {compiler.arm.cmsis.path} {build.variant_system_include}`, //"recipe.preproc.macros": `"{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} {preproc.macros.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {preproc.macros.compatibility_flags} {includes} "{source_file}" -o "{preprocessed_file_path}"`, -} +}) diff --git a/ctags_runner.go b/ctags_runner.go index 037d98b8..7933bd41 100644 --- a/ctags_runner.go +++ b/ctags_runner.go @@ -48,7 +48,7 @@ func (s *CTagsRunner) Run(ctx *types.Context) error { properties.Merge(buildProperties.SubTree(constants.BUILD_PROPERTIES_TOOLS_KEY).SubTree(constants.CTAGS)) properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, ctagsTargetFilePath) - pattern := properties[constants.BUILD_PROPERTIES_PATTERN] + pattern := properties.Get(constants.BUILD_PROPERTIES_PATTERN) if pattern == constants.EMPTY_STRING { return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, constants.CTAGS) } diff --git a/dump_build_properties.go b/dump_build_properties.go index 36959161..b64caa8e 100644 --- a/dump_build_properties.go +++ b/dump_build_properties.go @@ -45,7 +45,7 @@ func (s *DumpBuildProperties) Run(ctx *types.Context) error { sort.Strings(keys) for _, key := range keys { - fmt.Println(key + "=" + buildProperties[key]) + fmt.Println(key + "=" + buildProperties.Get(key)) } return nil diff --git a/gcc_preproc_runner.go b/gcc_preproc_runner.go index ade7ee49..e084d8af 100644 --- a/gcc_preproc_runner.go +++ b/gcc_preproc_runner.go @@ -75,11 +75,11 @@ func prepareGCCPreprocRecipeProperties(ctx *types.Context, sourceFilePath *paths properties.SetPath(constants.BUILD_PROPERTIES_PREPROCESSED_FILE_PATH, targetFilePath) includesStrings := utils.Map(includes.AsStrings(), utils.WrapWithHyphenI) - properties[constants.BUILD_PROPERTIES_INCLUDES] = strings.Join(includesStrings, constants.SPACE) + properties.Set(constants.BUILD_PROPERTIES_INCLUDES, strings.Join(includesStrings, constants.SPACE)) - if properties[constants.RECIPE_PREPROC_MACROS] == constants.EMPTY_STRING { + if properties.Get(constants.RECIPE_PREPROC_MACROS) == "" { //generate PREPROC_MACROS from RECIPE_CPP_PATTERN - properties[constants.RECIPE_PREPROC_MACROS] = GeneratePreprocPatternFromCompile(properties[constants.RECIPE_CPP_PATTERN]) + properties.Set(constants.RECIPE_PREPROC_MACROS, GeneratePreprocPatternFromCompile(properties.Get(constants.RECIPE_CPP_PATTERN))) } cmd, err := builder_utils.PrepareCommandForRecipe(ctx, properties, constants.RECIPE_PREPROC_MACROS, true) diff --git a/load_vid_pid_specific_properties.go b/load_vid_pid_specific_properties.go index df3cc434..ea59c60e 100644 --- a/load_vid_pid_specific_properties.go +++ b/load_vid_pid_specific_properties.go @@ -36,7 +36,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type LoadVIDPIDSpecificProperties struct{} @@ -67,10 +67,10 @@ func (s *LoadVIDPIDSpecificProperties) Run(ctx *types.Context) error { return nil } -func findVIDPIDIndex(buildProperties properties.Map, vid, pid string) (int, error) { - for key, value := range buildProperties.SubTree(constants.BUILD_PROPERTIES_VID) { +func findVIDPIDIndex(buildProperties *properties.Map, vid, pid string) (int, error) { + for key, value := range buildProperties.SubTree(constants.BUILD_PROPERTIES_VID).AsMap() { if !strings.Contains(key, ".") { - if vid == strings.ToLower(value) && pid == strings.ToLower(buildProperties[constants.BUILD_PROPERTIES_PID+"."+key]) { + if vid == strings.ToLower(value) && pid == strings.ToLower(buildProperties.Get(constants.BUILD_PROPERTIES_PID+"."+key)) { return strconv.Atoi(key) } } diff --git a/merge_sketch_with_bootloader.go b/merge_sketch_with_bootloader.go index d0fdd5cd..0fcc2488 100644 --- a/merge_sketch_with_bootloader.go +++ b/merge_sketch_with_bootloader.go @@ -38,14 +38,13 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" ) type MergeSketchWithBootloader struct{} func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { buildProperties := ctx.BuildProperties - if !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) && !utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_FILE) { + if !buildProperties.ContainsKey(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) && !buildProperties.ContainsKey(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) { return nil } @@ -67,10 +66,10 @@ func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { } bootloader := constants.EMPTY_STRING - if utils.MapStringStringHas(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) { - bootloader = buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK] + if bootloaderNoBlink, ok := buildProperties.GetOk(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK); ok { + bootloader = bootloaderNoBlink } else { - bootloader = buildProperties[constants.BUILD_PROPERTIES_BOOTLOADER_FILE] + bootloader = buildProperties.Get(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) } bootloader = buildProperties.ExpandPropsInString(bootloader) diff --git a/phases/core_builder.go b/phases/core_builder.go index 6dafd71c..d3220a1f 100644 --- a/phases/core_builder.go +++ b/phases/core_builder.go @@ -38,7 +38,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type CoreBuilder struct{} @@ -69,7 +69,7 @@ func (s *CoreBuilder) Run(ctx *types.Context) error { return nil } -func compileCore(ctx *types.Context, buildPath *paths.Path, buildCachePath *paths.Path, buildProperties properties.Map) (*paths.Path, paths.PathList, 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(constants.BUILD_PROPERTIES_BUILD_CORE_PATH) variantFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH) @@ -98,7 +98,7 @@ func compileCore(ctx *types.Context, buildPath *paths.Path, buildCachePath *path var targetArchivedCore *paths.Path if buildCachePath != nil { - archivedCoreName := builder_utils.GetCachedCoreArchiveFileName(buildProperties[constants.BUILD_PROPERTIES_FQBN], realCoreFolder) + archivedCoreName := builder_utils.GetCachedCoreArchiveFileName(buildProperties.Get(constants.BUILD_PROPERTIES_FQBN), realCoreFolder) targetArchivedCore = buildCachePath.Join(archivedCoreName) canUseArchivedCore := !builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, targetArchivedCore) diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go index a6a2a581..d9a151ca 100644 --- a/phases/libraries_builder.go +++ b/phases/libraries_builder.go @@ -40,7 +40,7 @@ import ( "github.com/arduino/arduino-builder/utils" "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC = map[string]bool{".a": true} @@ -77,7 +77,7 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs libraries.List) e if library.Precompiled { // add library src path to compiler.c.elf.extra_flags // use library.Name as lib name and srcPath/{mcpu} as location - mcu := ctx.BuildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] + mcu := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) path := library.SourceDir.Join(mcu).String() // find all library names in the folder and prepend -l filePaths := []string{} @@ -90,13 +90,15 @@ func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs libraries.List) e name = strings.Replace(name, "lib", "", 1) libs_cmd += "-l" + name + " " } - ctx.BuildProperties[constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS] += "\"-L" + path + "\" " + libs_cmd + " " + + currLDFlags := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS) + ctx.BuildProperties.Set(constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS, currLDFlags+"\"-L"+path+"\" "+libs_cmd+" ") } } return nil } -func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { +func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { objectFiles := paths.NewPathList() for _, library := range libraries { libraryObjectFiles, err := compileLibrary(ctx, library, buildPath, buildProperties, includes) @@ -109,7 +111,7 @@ func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *p return objectFiles, nil } -func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *paths.Path, buildProperties properties.Map, includes []string) (paths.PathList, error) { +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, "Compiling library \"{0}\"", library.Name) @@ -127,7 +129,7 @@ func compileLibrary(ctx *types.Context, library *libraries.Library, buildPath *p extensions := func(ext string) bool { return PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC[ext] } filePaths := []string{} - mcu := buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] + mcu := buildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) err := utils.FindFilesInFolder(&filePaths, library.SourceDir.Join(mcu).String(), extensions, true) if err != nil { return nil, i18n.WrapError(err) diff --git a/phases/linker.go b/phases/linker.go index c94419e3..e3e140ae 100644 --- a/phases/linker.go +++ b/phases/linker.go @@ -38,7 +38,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type Linker struct{} @@ -70,18 +70,18 @@ func (s *Linker) Run(ctx *types.Context) error { return nil } -func link(ctx *types.Context, objectFiles paths.PathList, coreDotARelPath *paths.Path, coreArchiveFilePath *paths.Path, buildProperties properties.Map) error { +func link(ctx *types.Context, objectFiles paths.PathList, coreDotARelPath *paths.Path, coreArchiveFilePath *paths.Path, buildProperties *properties.Map) error { optRelax := addRelaxTrickIfATMEGA2560(buildProperties) quotedObjectFiles := utils.Map(objectFiles.AsStrings(), wrapWithDoubleQuotes) objectFileList := strings.Join(quotedObjectFiles, constants.SPACE) properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS] + optRelax - properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE] = coreDotARelPath.String() - properties[constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH] = coreArchiveFilePath.String() - properties[constants.BUILD_PROPERTIES_OBJECT_FILES] = objectFileList + properties.Set(constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS)+optRelax) + properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel)) + properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE, coreDotARelPath.String()) + properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH, coreArchiveFilePath.String()) + properties.Set(constants.BUILD_PROPERTIES_OBJECT_FILES, objectFileList) _, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_C_COMBINE_PATTERN, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) return err @@ -91,8 +91,8 @@ func wrapWithDoubleQuotes(value string) string { return "\"" + value + "\"" } -func addRelaxTrickIfATMEGA2560(buildProperties properties.Map) string { - if buildProperties[constants.BUILD_PROPERTIES_BUILD_MCU] == "atmega2560" { +func addRelaxTrickIfATMEGA2560(buildProperties *properties.Map) string { + if buildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) == "atmega2560" { return ",--relax" } return constants.EMPTY_STRING diff --git a/phases/sizer.go b/phases/sizer.go index fa719e18..04aa161d 100644 --- a/phases/sizer.go +++ b/phases/sizer.go @@ -39,7 +39,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type Sizer struct { @@ -62,14 +62,14 @@ func (s *Sizer) Run(ctx *types.Context) error { return nil } -func checkSize(ctx *types.Context, buildProperties properties.Map) error { +func checkSize(ctx *types.Context, buildProperties *properties.Map) error { logger := ctx.GetLogger() properties := buildProperties.Clone() - properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS] = properties[constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel] + properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel)) - maxTextSizeString := properties[constants.PROPERTY_UPLOAD_MAX_SIZE] - maxDataSizeString := properties[constants.PROPERTY_UPLOAD_MAX_DATA_SIZE] + maxTextSizeString := properties.Get(constants.PROPERTY_UPLOAD_MAX_SIZE) + maxDataSizeString := properties.Get(constants.PROPERTY_UPLOAD_MAX_DATA_SIZE) if maxTextSizeString == "" { return nil @@ -113,8 +113,8 @@ func checkSize(ctx *types.Context, buildProperties properties.Map) error { return errors.New("") } - if properties[constants.PROPERTY_WARN_DATA_PERCENT] != "" { - warnDataPercentage, err := strconv.Atoi(properties[constants.PROPERTY_WARN_DATA_PERCENT]) + if properties.Get(constants.PROPERTY_WARN_DATA_PERCENT) != "" { + warnDataPercentage, err := strconv.Atoi(properties.Get(constants.PROPERTY_WARN_DATA_PERCENT)) if err != nil { return err } @@ -126,7 +126,7 @@ func checkSize(ctx *types.Context, buildProperties properties.Map) error { return nil } -func execSizeRecipe(ctx *types.Context, properties properties.Map) (textSize int, dataSize int, eepromSize int, resErr error) { +func execSizeRecipe(ctx *types.Context, properties *properties.Map) (textSize int, dataSize int, eepromSize int, resErr error) { out, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_SIZE_PATTERN, false /* stdout */, utils.Capture /* stderr */, utils.Show) if err != nil { resErr = errors.New("Error while determining sketch size: " + err.Error()) @@ -136,7 +136,7 @@ func execSizeRecipe(ctx *types.Context, properties properties.Map) (textSize int // force multiline match prepending "(?m)" to the actual regexp // return an error if RECIPE_SIZE_REGEXP doesn't exist - textSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP], out) + textSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP), out) if err != nil { resErr = errors.New("Invalid size regexp: " + err.Error()) return @@ -146,13 +146,13 @@ func execSizeRecipe(ctx *types.Context, properties properties.Map) (textSize int return } - dataSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP_DATA], out) + dataSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP_DATA), out) if err != nil { resErr = errors.New("Invalid data size regexp: " + err.Error()) return } - eepromSize, err = computeSize(properties[constants.RECIPE_SIZE_REGEXP_EEPROM], out) + eepromSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP_EEPROM), out) if err != nil { resErr = errors.New("Invalid eeprom size regexp: " + err.Error()) return diff --git a/preprocess_sketch.go b/preprocess_sketch.go index c0b2be7b..c509b8d1 100644 --- a/preprocess_sketch.go +++ b/preprocess_sketch.go @@ -41,18 +41,18 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" - properties "github.com/arduino/go-properties-map" + properties "github.com/arduino/go-properties-orderedmap" ) // ArduinoPreprocessorProperties are the platform properties needed to run arduino-preprocessor -var ArduinoPreprocessorProperties = properties.Map{ +var ArduinoPreprocessorProperties = properties.NewFromHashmap(map[string]string{ // Ctags "tools.arduino-preprocessor.path": "{runtime.tools.arduino-preprocessor.path}", "tools.arduino-preprocessor.cmd.path": "{path}/arduino-preprocessor", "tools.arduino-preprocessor.pattern": `"{cmd.path}" "{source_file}" "{codecomplete}" -- -std=gnu++11`, "preproc.macros.flags": "-w -x c++ -E -CC", -} +}) type PreprocessSketchArduino struct{} @@ -107,12 +107,12 @@ func (s *ArduinoPreprocessorRunner) Run(ctx *types.Context) error { ctx.CodeCompleteAt = strings.Join(splt[1:], ":") } } - properties["codecomplete"] = "-output-code-completions=" + ctx.CodeCompleteAt + properties.Set("codecomplete", "-output-code-completions="+ctx.CodeCompleteAt) } else { - properties["codecomplete"] = "" + properties.Set("codecomplete", "") } - pattern := properties[constants.BUILD_PROPERTIES_PATTERN] + pattern := properties.Get(constants.BUILD_PROPERTIES_PATTERN) if pattern == constants.EMPTY_STRING { return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, "arduino-preprocessor") } diff --git a/recipe_runner.go b/recipe_runner.go index bb1bb962..0fd9e6d4 100644 --- a/recipe_runner.go +++ b/recipe_runner.go @@ -39,6 +39,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" + properties "github.com/arduino/go-properties-orderedmap" ) type RecipeByPrefixSuffixRunner struct { @@ -70,10 +71,10 @@ func (s *RecipeByPrefixSuffixRunner) Run(ctx *types.Context) error { } -func findRecipes(buildProperties map[string]string, patternPrefix string, patternSuffix string) []string { +func findRecipes(buildProperties *properties.Map, patternPrefix string, patternSuffix string) []string { var recipes []string - for key, _ := range buildProperties { - if strings.HasPrefix(key, patternPrefix) && strings.HasSuffix(key, patternSuffix) && buildProperties[key] != constants.EMPTY_STRING { + for _, key := range buildProperties.Keys() { + if strings.HasPrefix(key, patternPrefix) && strings.HasSuffix(key, patternSuffix) && buildProperties.Get(key) != "" { recipes = append(recipes, key) } } diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go index d4a02d18..56cf17e5 100644 --- a/rewrite_hardware_keys.go +++ b/rewrite_hardware_keys.go @@ -49,10 +49,10 @@ func (s *RewriteHardwareKeys) Run(ctx *types.Context) error { for _, aPackage := range packages.Packages { for _, platform := range aPackage.Platforms { for _, platformRelease := range platform.Releases { - if platformRelease.Properties[constants.REWRITING] != constants.REWRITING_DISABLED { + if platformRelease.Properties.Get(constants.REWRITING) != constants.REWRITING_DISABLED { for _, rewrite := range platformKeysRewrite.Rewrites { - if platformRelease.Properties[rewrite.Key] != "" && platformRelease.Properties[rewrite.Key] == rewrite.OldValue { - platformRelease.Properties[rewrite.Key] = rewrite.NewValue + if platformRelease.Properties.Get(rewrite.Key) == rewrite.OldValue { + platformRelease.Properties.Set(rewrite.Key, rewrite.NewValue) appliedRewrites := rewritesAppliedToPlatform(platformRelease, hardwareRewriteResults) appliedRewrites = append(appliedRewrites, rewrite) hardwareRewriteResults[platformRelease] = appliedRewrites diff --git a/set_custom_build_properties.go b/set_custom_build_properties.go index 12b3467a..689dddc6 100644 --- a/set_custom_build_properties.go +++ b/set_custom_build_properties.go @@ -32,7 +32,7 @@ package builder import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type SetCustomBuildProperties struct{} @@ -44,9 +44,7 @@ func (s *SetCustomBuildProperties) Run(ctx *types.Context) error { return i18n.WrapError(err) } - for key, value := range customBuildProperties { - buildProperties[key] = value - } + buildProperties.Merge(customBuildProperties) return nil } diff --git a/setup_build_properties.go b/setup_build_properties.go index 4b977e27..1be22b56 100644 --- a/setup_build_properties.go +++ b/setup_build_properties.go @@ -39,7 +39,7 @@ import ( "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-builder/utils" "github.com/arduino/arduino-cli/arduino/cores" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" "github.com/arduino/go-timeutils" ) @@ -52,7 +52,7 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { actualPlatform := ctx.ActualPlatform targetBoard := ctx.TargetBoard - buildProperties := make(properties.Map) + buildProperties := properties.NewMap() buildProperties.Merge(actualPlatform.Properties) buildProperties.Merge(targetPlatform.Properties) buildProperties.Merge(targetBoard.Properties) @@ -61,9 +61,9 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { buildProperties.SetPath("build.path", ctx.BuildPath) } if ctx.Sketch != nil { - buildProperties["build.project_name"] = ctx.Sketch.MainFile.Name.Base() + buildProperties.Set("build.project_name", ctx.Sketch.MainFile.Name.Base()) } - buildProperties["build.arch"] = strings.ToUpper(targetPlatform.Platform.Architecture) + buildProperties.Set("build.arch", strings.ToUpper(targetPlatform.Platform.Architecture)) // get base folder and use it to populate BUILD_PROPERTIES_RUNTIME_IDE_PATH (arduino and arduino-builder live in the same dir) ex, err := os.Executable() @@ -72,20 +72,20 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { exPath = filepath.Dir(ex) } - buildProperties["build.core"] = ctx.BuildCore - buildProperties["build.core.path"] = actualPlatform.InstallDir.Join("cores", buildProperties["build.core"]).String() - buildProperties["build.system.path"] = actualPlatform.InstallDir.Join("system").String() - buildProperties["runtime.platform.path"] = targetPlatform.InstallDir.String() - buildProperties["runtime.hardware.path"] = targetPlatform.InstallDir.Join("..").String() - buildProperties["runtime.ide.version"] = ctx.ArduinoAPIVersion - buildProperties["runtime.ide.path"] = exPath - buildProperties["build.fqbn"] = ctx.FQBN.String() - buildProperties["ide_version"] = ctx.ArduinoAPIVersion - buildProperties["runtime.os"] = utils.PrettyOSName() - - variant := buildProperties["build.variant"] + buildProperties.Set("build.core", ctx.BuildCore) + buildProperties.SetPath("build.core.path", actualPlatform.InstallDir.Join("cores", buildProperties.Get("build.core"))) + buildProperties.Set("build.system.path", actualPlatform.InstallDir.Join("system").String()) + buildProperties.Set("runtime.platform.path", targetPlatform.InstallDir.String()) + buildProperties.Set("runtime.hardware.path", targetPlatform.InstallDir.Join("..").String()) + buildProperties.Set("runtime.ide.version", ctx.ArduinoAPIVersion) + buildProperties.Set("runtime.ide.path", exPath) + buildProperties.Set("build.fqbn", ctx.FQBN.String()) + buildProperties.Set("ide_version", ctx.ArduinoAPIVersion) + buildProperties.Set("runtime.os", utils.PrettyOSName()) + + variant := buildProperties.Get("build.variant") if variant == "" { - buildProperties["build.variant.path"] = "" + buildProperties.Set("build.variant.path", "") } else { var variantPlatformRelease *cores.PlatformRelease variantParts := strings.Split(variant, ":") @@ -96,20 +96,20 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } else { variantPlatformRelease = targetPlatform } - buildProperties["build.variant.path"] = variantPlatformRelease.InstallDir.Join("variants", variant).String() + buildProperties.SetPath("build.variant.path", variantPlatformRelease.InstallDir.Join("variants", variant)) } for _, tool := range ctx.AllTools { - buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path"] = tool.InstallDir.String() + buildProperties.SetPath("runtime.tools."+tool.Tool.Name+".path", tool.InstallDir) + buildProperties.SetPath("runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path", tool.InstallDir) } for _, tool := range ctx.RequiredTools { - buildProperties["runtime.tools."+tool.Tool.Name+".path"] = tool.InstallDir.String() - buildProperties["runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path"] = tool.InstallDir.String() + buildProperties.SetPath("runtime.tools."+tool.Tool.Name+".path", tool.InstallDir) + buildProperties.SetPath("runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path", tool.InstallDir) } - if !utils.MapStringStringHas(buildProperties, "software") { - buildProperties["software"] = DEFAULT_SOFTWARE + if !buildProperties.ContainsKey("software") { + buildProperties.Set("software", DEFAULT_SOFTWARE) } if ctx.SketchLocation != nil { @@ -122,10 +122,10 @@ func (s *SetupBuildProperties) Run(ctx *types.Context) error { } now := time.Now() - buildProperties["extra.time.utc"] = strconv.FormatInt(now.Unix(), 10) - buildProperties["extra.time.local"] = strconv.FormatInt(timeutils.LocalUnix(now), 10) - buildProperties["extra.time.zone"] = strconv.Itoa(timeutils.TimezoneOffsetNoDST(now)) - buildProperties["extra.time.dst"] = strconv.Itoa(timeutils.DaylightSavingsOffset(now)) + buildProperties.Set("extra.time.utc", strconv.FormatInt(now.Unix(), 10)) + buildProperties.Set("extra.time.local", strconv.FormatInt(timeutils.LocalUnix(now), 10)) + buildProperties.Set("extra.time.zone", strconv.Itoa(timeutils.TimezoneOffsetNoDST(now))) + buildProperties.Set("extra.time.dst", strconv.Itoa(timeutils.DaylightSavingsOffset(now))) ctx.BuildProperties = buildProperties diff --git a/target_board_resolver.go b/target_board_resolver.go index 4463ea9b..4b361403 100644 --- a/target_board_resolver.go +++ b/target_board_resolver.go @@ -49,7 +49,7 @@ func (s *TargetBoardResolver) Run(ctx *types.Context) error { targetBoard.Properties = buildProperties // FIXME.... - core := targetBoard.Properties["build.core"] + core := targetBoard.Properties.Get("build.core") if core == "" { core = "arduino" } diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index dfea70c4..9293078b 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -74,8 +74,8 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, constants.EMPTY_STRING, targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MYMEGA", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + require.Equal(t, "", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_MCU)) + require.Equal(t, "AVR_MYMEGA", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) } func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { @@ -103,6 +103,6 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, "atmega2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_MCU]) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties[constants.BUILD_PROPERTIES_BUILD_BOARD]) + require.Equal(t, "atmega2560", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_MCU)) + require.Equal(t, "AVR_MEGA2560", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) } diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go index c0b60f4c..37acae17 100644 --- a/test/hardware_loader_test.go +++ b/test/hardware_loader_test.go @@ -36,7 +36,6 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -61,28 +60,28 @@ func TestLoadHardware(t *testing.T) { require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties.Get("_id")) require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) + require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties.Get("upload.wait_for_upload_port")) - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) + require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties.Get("build.extra_flags")) require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) - require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties["menu.cpu.atmega123"]) + require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties.Get("menu.cpu.atmega123")) avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties["name"]) - require.Equal(t, "-v", avrPlatform.Releases[""].Properties["tools.avrdude.bootloader.params.verbose"]) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Releases[""].Properties["tools.avrdude.cmd.path"]) + require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties.Get("name")) + require.Equal(t, "-v", avrPlatform.Releases[""].Properties.Get("tools.avrdude.bootloader.params.verbose")) + require.Equal(t, "/my/personal/avrdude", avrPlatform.Releases[""].Properties.Get("tools.avrdude.cmd.path")) - require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"]["name"]) + require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"].Get("name")) - //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - //require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) + //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties.Get("tools.ctags.path"]) + //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties.Get("tools.ctags.pattern"]) + //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties.Get("tools.avrdude.path"]) + //require.Equal(t, "-w -x c++ -E -CC", packages.Properties.Get("preproc.macros.flags"]) } func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { @@ -115,39 +114,39 @@ func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties["_id"]) + require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties.Get("_id")) require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties["upload.wait_for_upload_port"]) + require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties.Get("upload.wait_for_upload_port")) - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties["build.extra_flags"]) + require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties.Get("build.extra_flags")) require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) avrPlatform := packages.Packages["arduino"].Platforms["avr"].Releases[""] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties["name"]) - require.Equal(t, "-v", avrPlatform.Properties["tools.avrdude.bootloader.params.verbose"]) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties["tools.avrdude.cmd.path"]) + require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties.Get("name")) + require.Equal(t, "-v", avrPlatform.Properties.Get("tools.avrdude.bootloader.params.verbose")) + require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties.Get("tools.avrdude.cmd.path")) - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"]["name"]) + require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"].Get("name")) - require.Equal(t, "-w -x c++ -M -MG -MP", avrPlatform.Properties["preproc.includes.flags"]) - require.Equal(t, "-w -x c++ -E -CC", avrPlatform.Properties["preproc.macros.flags"]) - require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties["recipe.preproc.includes"]) - require.False(t, utils.MapStringStringHas(avrPlatform.Properties, "preproc.macros.compatibility_flags")) + require.Equal(t, "-w -x c++ -M -MG -MP", avrPlatform.Properties.Get("preproc.includes.flags")) + require.Equal(t, "-w -x c++ -E -CC", avrPlatform.Properties.Get("preproc.macros.flags")) + require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties.Get("recipe.preproc.includes")) + require.False(t, avrPlatform.Properties.ContainsKey("preproc.macros.compatibility_flags")) require.NotNil(t, packages.Packages["my_avr_platform"]) myAVRPlatform := packages.Packages["my_avr_platform"] - //require.Equal(t, "hello world", myAVRPlatform.Properties["example"]) + //require.Equal(t, "hello world", myAVRPlatform.Properties.Get("example")) myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"].Releases[""] require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardID) - require.False(t, utils.MapStringStringHas(myAVRPlatformAvrArch.Properties, "preproc.includes.flags")) + require.False(t, myAVRPlatformAvrArch.Properties.ContainsKey("preproc.includes.flags")) - //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties["tools.ctags.path"]) - //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties["tools.ctags.pattern"]) - //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties["tools.avrdude.path"]) - //require.Equal(t, "-w -x c++ -E -CC", packages.Properties["preproc.macros.flags"]) + //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties.Get("tools.ctags.path")) + //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties.Get("tools.ctags.pattern")) + //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties.Get("tools.avrdude.path")) + //require.Equal(t, "-w -x c++ -E -CC", packages.Properties.Get("preproc.macros.flags")) if runtime.GOOS != "windows" { require.NotNil(t, packages.Packages["my_symlinked_avr_platform"]) @@ -182,25 +181,25 @@ func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { require.Equal(t, 3, len(samdPlatform.Boards)) require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardID) - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties["_id"]) + require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties.Get("_id")) - require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties["build.variant"]) - require.Equal(t, "-D__SAMD21G18A__ {build.usb_flags}", samdPlatform.Boards["arduino_zero_native"].Properties["build.extra_flags"]) + require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties.Get("build.variant")) + require.Equal(t, "-D__SAMD21G18A__ {build.usb_flags}", samdPlatform.Boards["arduino_zero_native"].Properties.Get("build.extra_flags")) - require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties["name"]) - require.Equal(t, "-d3", samdPlatform.Properties["tools.openocd.erase.params.verbose"]) + require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties.Get("name")) + require.Equal(t, "-d3", samdPlatform.Properties.Get("tools.openocd.erase.params.verbose")) require.Equal(t, 3, len(samdPlatform.Programmers)) - require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"]["name"]) - require.Equal(t, "openocd", samdPlatform.Programmers["edbg"]["program.tool"]) + require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"].Get("name")) + require.Equal(t, "openocd", samdPlatform.Programmers["edbg"].Get("program.tool")) avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases["1.0.0"] require.Equal(t, 3, len(avrRedBearPlatform.Boards)) require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardID) - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties["_id"]) - require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties["build.core"]) + require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties.Get("_id")) + require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties.Get("build.core")) } func TestLoadLotsOfHardware(t *testing.T) { diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go index 28b706e1..9a6e0335 100644 --- a/test/load_vid_pid_specific_properties_test.go +++ b/test/load_vid_pid_specific_properties_test.go @@ -64,9 +64,9 @@ func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "0x0037", buildProperties["pid.0"]) - require.Equal(t, "\"Genuino Micro\"", buildProperties["vid.4.build.usb_product"]) - require.Equal(t, "0x8037", buildProperties["build.pid"]) + require.Equal(t, "0x0037", buildProperties.Get("pid.0")) + require.Equal(t, "\"Genuino Micro\"", buildProperties.Get("vid.4.build.usb_product")) + require.Equal(t, "0x8037", buildProperties.Get("build.pid")) } func TestLoadVIDPIDSpecificProperties(t *testing.T) { @@ -96,8 +96,8 @@ func TestLoadVIDPIDSpecificProperties(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "0x0037", buildProperties["pid.0"]) - require.Equal(t, "\"Genuino Micro\"", buildProperties["vid.4.build.usb_product"]) - require.Equal(t, "0x2341", buildProperties["build.vid"]) - require.Equal(t, "0x8237", buildProperties["build.pid"]) + require.Equal(t, "0x0037", buildProperties.Get("pid.0")) + require.Equal(t, "\"Genuino Micro\"", buildProperties.Get("vid.4.build.usb_product")) + require.Equal(t, "0x2341", buildProperties.Get("build.vid")) + require.Equal(t, "0x8237", buildProperties.Get("build.pid")) } diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go index 4a3c0898..2a280fc3 100644 --- a/test/merge_sketch_with_bootloader_test.go +++ b/test/merge_sketch_with_bootloader_test.go @@ -151,8 +151,8 @@ func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { } buildProperties := ctx.BuildProperties - delete(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) - delete(buildProperties, constants.BUILD_PROPERTIES_BOOTLOADER_FILE) + buildProperties.Remove(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) + buildProperties.Remove(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) command := &builder.MergeSketchWithBootloader{} err := command.Run(ctx) diff --git a/test/recipe_runner_test.go b/test/recipe_runner_test.go index 2ebb7a37..47896501 100644 --- a/test/recipe_runner_test.go +++ b/test/recipe_runner_test.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" "github.com/stretchr/testify/require" ) @@ -45,10 +45,10 @@ import ( // So this test is pretty useless func TestRecipeRunner(t *testing.T) { ctx := &types.Context{} - buildProperties := make(properties.Map) + buildProperties := properties.NewMap() ctx.BuildProperties = buildProperties - buildProperties["recipe.hooks.prebuild.1.pattern"] = "echo" + buildProperties.Set("recipe.hooks.prebuild.1.pattern", "echo") commands := []types.Command{ &builder.AddAdditionalEntriesToContext{}, diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go index f126c8d9..d5b65342 100644 --- a/test/rewrite_hardware_keys_test.go +++ b/test/rewrite_hardware_keys_test.go @@ -35,7 +35,7 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-cli/arduino/cores" - properties "github.com/arduino/go-properties-map" + properties "github.com/arduino/go-properties-orderedmap" "github.com/stretchr/testify/require" ) @@ -49,10 +49,10 @@ func TestRewriteHardwareKeys(t *testing.T) { aPackage.Platforms = map[string]*cores.Platform{} platform := &cores.PlatformRelease{ - Properties: properties.Map{ + Properties: properties.NewFromHashmap(map[string]string{ "name": "A test platform", "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", - }, + }), } aPackage.Platforms["dummy"] = &cores.Platform{ Architecture: "dummy", @@ -77,7 +77,7 @@ func TestRewriteHardwareKeys(t *testing.T) { NoError(t, err) } - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties["compiler.path"]) + require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties.Get("compiler.path")) } func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { @@ -90,11 +90,11 @@ func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { aPackage.Platforms = make(map[string]*cores.Platform) platform := &cores.PlatformRelease{ - Properties: properties.Map{ + Properties: properties.NewFromHashmap(map[string]string{ "name": "A test platform", "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", "rewriting": "disabled", - }, + }), } aPackage.Platforms["dummy"] = &cores.Platform{ Architecture: "dummy", @@ -120,5 +120,5 @@ func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { NoError(t, err) } - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties["compiler.path"]) + require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties.Get("compiler.path")) } diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go index 29a293e8..4cf9a069 100644 --- a/test/setup_build_properties_test.go +++ b/test/setup_build_properties_test.go @@ -35,7 +35,6 @@ import ( "github.com/arduino/arduino-builder" "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" paths "github.com/arduino/go-paths-helper" "github.com/stretchr/testify/require" ) @@ -70,40 +69,40 @@ func TestSetupBuildProperties(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties["software"]) + require.Equal(t, "ARDUINO", buildProperties.Get("software")) - require.Equal(t, "uno", buildProperties["_id"]) - require.Equal(t, "Arduino/Genuino Uno", buildProperties["name"]) - require.Equal(t, "0x2341", buildProperties["vid.0"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) + require.Equal(t, "uno", buildProperties.Get("_id")) + require.Equal(t, "Arduino/Genuino Uno", buildProperties.Get("name")) + require.Equal(t, "0x2341", buildProperties.Get("vid.0")) + require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) + require.Equal(t, "{path}/etc/avrdude.conf", buildProperties.Get("tools.avrdude.config.path")) - requireEquivalentPaths(t, buildProperties["runtime.platform.path"], "downloaded_hardware/arduino/avr") - requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], "downloaded_hardware/arduino") - require.Equal(t, "10600", buildProperties["runtime.ide.version"]) - require.NotEmpty(t, buildProperties["runtime.os"]) + requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), "downloaded_hardware/arduino/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), "downloaded_hardware/arduino") + require.Equal(t, "10600", buildProperties.Get("runtime.ide.version")) + require.NotEmpty(t, buildProperties.Get("runtime.os")) - requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"], "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") - requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude.path"], "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude-6.0.1-arduino5.path"), "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude.path"), "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") - bossacPath := buildProperties["runtime.tools.bossac.path"] - bossac161Path := buildProperties["runtime.tools.bossac-1.6.1-arduino.path"] - bossac15Path := buildProperties["runtime.tools.bossac-1.5-arduino.path"] + bossacPath := buildProperties.Get("runtime.tools.bossac.path") + bossac161Path := buildProperties.Get("runtime.tools.bossac-1.6.1-arduino.path") + bossac15Path := buildProperties.Get("runtime.tools.bossac-1.5-arduino.path") requireEquivalentPaths(t, bossac161Path, "downloaded_tools/bossac/1.6.1-arduino") requireEquivalentPaths(t, bossac15Path, "downloaded_tools/bossac/1.5-arduino") requireEquivalentPaths(t, bossacPath, bossac161Path, bossac15Path) - requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties["build.source.path"], "sketch1") + requireEquivalentPaths(t, buildProperties.Get("build.source.path"), "sketch1") - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.zone")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.dst")) + require.True(t, buildProperties.ContainsKey("extra.time.utc")) + require.True(t, buildProperties.ContainsKey("extra.time.local")) + require.True(t, buildProperties.ContainsKey("extra.time.zone")) + require.True(t, buildProperties.ContainsKey("extra.time.dst")) } func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { @@ -139,12 +138,12 @@ func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties["software"]) + require.Equal(t, "ARDUINO", buildProperties.Get("software")) - require.Equal(t, "uno", buildProperties["_id"]) - require.Equal(t, "fake name", buildProperties["name"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "non existent path with space and a =", buildProperties["tools.avrdude.config.path"]) + require.Equal(t, "uno", buildProperties.Get("_id")) + require.Equal(t, "fake name", buildProperties.Get("name")) + require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) + require.Equal(t, "non existent path with space and a =", buildProperties.Get("tools.avrdude.config.path")) } func TestSetupBuildPropertiesUserHardware(t *testing.T) { @@ -177,12 +176,12 @@ func TestSetupBuildPropertiesUserHardware(t *testing.T) { buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties["software"]) + require.Equal(t, "ARDUINO", buildProperties.Get("software")) - require.Equal(t, "custom_yun", buildProperties["_id"]) - require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties["bootloader.file"]) - requireEquivalentPaths(t, buildProperties["runtime.platform.path"], filepath.Join("user_hardware", "my_avr_platform", "avr")) - requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], filepath.Join("user_hardware", "my_avr_platform")) + require.Equal(t, "custom_yun", buildProperties.Get("_id")) + require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties.Get("bootloader.file")) + requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), filepath.Join("user_hardware", "my_avr_platform", "avr")) + requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), filepath.Join("user_hardware", "my_avr_platform")) } func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) { @@ -210,36 +209,36 @@ func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testi buildProperties := ctx.BuildProperties - require.Equal(t, "ARDUINO", buildProperties["software"]) + require.Equal(t, "ARDUINO", buildProperties.Get("software")) - require.Equal(t, "custom_yun", buildProperties["_id"]) - require.Equal(t, "Arduino Yún", buildProperties["name"]) - require.Equal(t, "0x2341", buildProperties["vid.0"]) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties["recipe.c.o.pattern"]) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties["tools.avrdude.config.path"]) + require.Equal(t, "custom_yun", buildProperties.Get("_id")) + require.Equal(t, "Arduino Yún", buildProperties.Get("name")) + require.Equal(t, "0x2341", buildProperties.Get("vid.0")) + require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) + require.Equal(t, "{path}/etc/avrdude.conf", buildProperties.Get("tools.avrdude.config.path")) - requireEquivalentPaths(t, buildProperties["runtime.platform.path"], "user_hardware/my_avr_platform/avr") - requireEquivalentPaths(t, buildProperties["runtime.hardware.path"], "user_hardware/my_avr_platform") - require.Equal(t, "10600", buildProperties["runtime.ide.version"]) - require.NotEmpty(t, buildProperties["runtime.os"]) + requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), "user_hardware/my_avr_platform/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), "user_hardware/my_avr_platform") + require.Equal(t, "10600", buildProperties.Get("runtime.ide.version")) + require.NotEmpty(t, buildProperties.Get("runtime.os")) - requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties["runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"], "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties["runtime.tools.bossac-1.6.1-arduino.path"], "downloaded_tools/bossac/1.6.1-arduino") - requireEquivalentPaths(t, buildProperties["runtime.tools.bossac-1.5-arduino.path"], "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac-1.6.1-arduino.path"), "downloaded_tools/bossac/1.6.1-arduino") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac-1.5-arduino.path"), "downloaded_tools/bossac/1.5-arduino") - requireEquivalentPaths(t, buildProperties["runtime.tools.bossac.path"], "downloaded_tools/bossac/1.6.1-arduino", "downloaded_tools/bossac/1.5-arduino") - requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude.path"], "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac.path"), "downloaded_tools/bossac/1.6.1-arduino", "downloaded_tools/bossac/1.5-arduino") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude.path"), "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties["runtime.tools.avrdude-6.0.1-arduino5.path"], "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude-6.0.1-arduino5.path"), "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties["runtime.tools.avr-gcc-4.8.1-arduino5.path"], "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") + requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc-4.8.1-arduino5.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties["build.source.path"], "sketch1") + requireEquivalentPaths(t, buildProperties.Get("build.source.path"), "sketch1") - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.utc")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.local")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.zone")) - require.True(t, utils.MapStringStringHas(buildProperties, "extra.time.dst")) + require.True(t, buildProperties.ContainsKey("extra.time.utc")) + require.True(t, buildProperties.ContainsKey("extra.time.local")) + require.True(t, buildProperties.ContainsKey("extra.time.zone")) + require.True(t, buildProperties.ContainsKey("extra.time.dst")) } diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go index ee2dd903..d3e2fdea 100644 --- a/test/target_board_resolver_test.go +++ b/test/target_board_resolver_test.go @@ -61,7 +61,7 @@ func TestTargetBoardResolverUno(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "uno", targetBoard.BoardID) - require.Equal(t, "atmega328p", targetBoard.Properties["build.mcu"]) + require.Equal(t, "atmega328p", targetBoard.Properties.Get("build.mcu")) } func TestTargetBoardResolverDue(t *testing.T) { @@ -86,7 +86,7 @@ func TestTargetBoardResolverDue(t *testing.T) { require.Equal(t, "sam", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "arduino_due_x", targetBoard.BoardID) - require.Equal(t, "cortex-m3", targetBoard.Properties["build.mcu"]) + require.Equal(t, "cortex-m3", targetBoard.Properties.Get("build.mcu")) } func TestTargetBoardResolverMega1280(t *testing.T) { @@ -111,8 +111,8 @@ func TestTargetBoardResolverMega1280(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardID) - require.Equal(t, "atmega1280", targetBoard.Properties["build.mcu"]) - require.Equal(t, "AVR_MEGA", targetBoard.Properties["build.board"]) + require.Equal(t, "atmega1280", targetBoard.Properties.Get("build.mcu")) + require.Equal(t, "AVR_MEGA", targetBoard.Properties.Get("build.board")) } func TestTargetBoardResolverMega2560(t *testing.T) { @@ -137,8 +137,8 @@ func TestTargetBoardResolverMega2560(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mega", targetBoard.BoardID) - require.Equal(t, "atmega2560", targetBoard.Properties["build.mcu"]) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties["build.board"]) + require.Equal(t, "atmega2560", targetBoard.Properties.Get("build.mcu")) + require.Equal(t, "AVR_MEGA2560", targetBoard.Properties.Get("build.board")) } func TestTargetBoardResolverCustomYun(t *testing.T) { @@ -163,8 +163,8 @@ func TestTargetBoardResolverCustomYun(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "custom_yun", targetBoard.BoardID) - require.Equal(t, "atmega32u4", targetBoard.Properties["build.mcu"]) - require.Equal(t, "AVR_YUN", targetBoard.Properties["build.board"]) + require.Equal(t, "atmega32u4", targetBoard.Properties.Get("build.mcu")) + require.Equal(t, "AVR_YUN", targetBoard.Properties.Get("build.board")) } func TestTargetBoardResolverCustomCore(t *testing.T) { @@ -190,5 +190,5 @@ func TestTargetBoardResolverCustomCore(t *testing.T) { targetBoard := ctx.TargetBoard require.Equal(t, "attiny841", targetBoard.BoardID) require.Equal(t, "tiny841", ctx.BuildCore) - require.Equal(t, "tiny14", targetBoard.Properties["build.variant"]) + require.Equal(t, "tiny14", targetBoard.Properties.Get("build.variant")) } diff --git a/types/context.go b/types/context.go index b84b9cf1..2dfeabab 100644 --- a/types/context.go +++ b/types/context.go @@ -10,7 +10,7 @@ import ( "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type ProgressStruct struct { @@ -50,7 +50,7 @@ type Context struct { PlatformKeyRewrites PlatforKeysRewrite HardwareRewriteResults map[*cores.PlatformRelease][]PlatforKeyRewrite - BuildProperties properties.Map + BuildProperties *properties.Map BuildCore string BuildPath *paths.Path BuildCachePath *paths.Path @@ -112,13 +112,13 @@ type Context struct { UseArduinoPreprocessor bool } -func (ctx *Context) ExtractBuildOptions() properties.Map { - opts := make(properties.Map) - opts["hardwareFolders"] = strings.Join(ctx.HardwareDirs.AsStrings(), ",") - opts["toolsFolders"] = strings.Join(ctx.ToolsDirs.AsStrings(), ",") - opts["builtInLibrariesFolders"] = strings.Join(ctx.BuiltInLibrariesDirs.AsStrings(), ",") - opts["otherLibrariesFolders"] = strings.Join(ctx.OtherLibrariesDirs.AsStrings(), ",") - opts["sketchLocation"] = ctx.SketchLocation.String() +func (ctx *Context) ExtractBuildOptions() *properties.Map { + opts := properties.NewMap() + opts.Set("hardwareFolders", strings.Join(ctx.HardwareDirs.AsStrings(), ",")) + opts.Set("toolsFolders", strings.Join(ctx.ToolsDirs.AsStrings(), ",")) + opts.Set("builtInLibrariesFolders", strings.Join(ctx.BuiltInLibrariesDirs.AsStrings(), ",")) + opts.Set("otherLibrariesFolders", strings.Join(ctx.OtherLibrariesDirs.AsStrings(), ",")) + opts.SetPath("sketchLocation", ctx.SketchLocation) var additionalFilesRelative []string if ctx.Sketch != nil { for _, sketch := range ctx.Sketch.AdditionalFiles { @@ -130,26 +130,26 @@ func (ctx *Context) ExtractBuildOptions() properties.Map { additionalFilesRelative = append(additionalFilesRelative, relPath.String()) } } - opts["fqbn"] = ctx.FQBN.String() - opts["runtime.ide.version"] = ctx.ArduinoAPIVersion - opts["customBuildProperties"] = strings.Join(ctx.CustomBuildProperties, ",") - opts["additionalFiles"] = strings.Join(additionalFilesRelative, ",") + opts.Set("fqbn", ctx.FQBN.String()) + opts.Set("runtime.ide.version", ctx.ArduinoAPIVersion) + opts.Set("customBuildProperties", strings.Join(ctx.CustomBuildProperties, ",")) + opts.Set("additionalFiles", strings.Join(additionalFilesRelative, ",")) return opts } -func (ctx *Context) InjectBuildOptions(opts properties.Map) { - ctx.HardwareDirs = paths.NewPathList(strings.Split(opts["hardwareFolders"], ",")...) - ctx.ToolsDirs = paths.NewPathList(strings.Split(opts["toolsFolders"], ",")...) - ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(opts["builtInLibrariesFolders"], ",")...) - ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(opts["otherLibrariesFolders"], ",")...) - ctx.SketchLocation = paths.New(opts["sketchLocation"]) - fqbn, err := cores.ParseFQBN(opts["fqbn"]) +func (ctx *Context) InjectBuildOptions(opts *properties.Map) { + ctx.HardwareDirs = paths.NewPathList(strings.Split(opts.Get("hardwareFolders"), ",")...) + ctx.ToolsDirs = paths.NewPathList(strings.Split(opts.Get("toolsFolders"), ",")...) + ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(opts.Get("builtInLibrariesFolders"), ",")...) + ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(opts.Get("otherLibrariesFolders"), ",")...) + ctx.SketchLocation = opts.GetPath("sketchLocation") + fqbn, err := cores.ParseFQBN(opts.Get("fqbn")) if err != nil { i18n.ErrorfWithLogger(ctx.GetLogger(), "Error in FQBN: %s", err) } ctx.FQBN = fqbn - ctx.ArduinoAPIVersion = opts["runtime.ide.version"] - ctx.CustomBuildProperties = strings.Split(opts["customBuildProperties"], ",") + ctx.ArduinoAPIVersion = opts.Get("runtime.ide.version") + ctx.CustomBuildProperties = strings.Split(opts.Get("customBuildProperties"), ",") } func (ctx *Context) GetLogger() i18n.Logger { diff --git a/utils/utils.go b/utils/utils.go index 25cac519..649807bb 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -324,11 +324,6 @@ func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int) return outbytes, errbytes, i18n.WrapError(err) } -func MapStringStringHas(aMap map[string]string, key string) bool { - _, ok := aMap[key] - return ok -} - func AbsolutizePaths(files []string) ([]string, error) { for idx, file := range files { if file == "" { diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go index c72e46f7..32b80fd1 100644 --- a/warn_about_arch_incompatible_libraries.go +++ b/warn_about_arch_incompatible_libraries.go @@ -49,7 +49,7 @@ func (s *WarnAboutArchIncompatibleLibraries) Run(ctx *types.Context) error { logger := ctx.GetLogger() archs := []string{targetPlatform.Platform.Architecture} - if overrides, ok := buildProperties[constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK]; ok { + if overrides, ok := buildProperties.GetOk(constants.BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK); ok { archs = append(archs, strings.Split(overrides, ",")...) } diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go index bdc930dc..f6e39810 100644 --- a/warn_about_platform_rewrites.go +++ b/warn_about_platform_rewrites.go @@ -57,7 +57,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, constants.MSG_WARNING_PLATFORM_OLD_VALUES, platform.Properties[constants.PLATFORM_NAME], rewrite.Key+"="+rewrite.OldValue, rewrite.Key+"="+rewrite.NewValue) + logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, + constants.MSG_WARNING_PLATFORM_OLD_VALUES, + platform.Properties.Get(constants.PLATFORM_NAME), + rewrite.Key+"="+rewrite.OldValue, + rewrite.Key+"="+rewrite.NewValue) } } } From 3c198fc7f0d8fe239ce5c4560617b689773ac460 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 2 Oct 2018 15:19:37 +0200 Subject: [PATCH 45/57] Adopting ordered properties map (part 2) --- .travis.yml | 2 +- README.md | 2 +- fail_if_imported_library_is_wrong.go | 2 +- platform_keys_rewrite_loader.go | 6 +++--- test/helper_tools_downloader.go | 2 +- wipeout_build_path_if_build_options_changed.go | 12 ++++++------ 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.travis.yml b/.travis.yml index 910c086e..5e65b5f4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,7 +10,7 @@ install: - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls - go get github.com/wadey/gocovmerge - - go get github.com/arduino/go-properties-map + - go get github.com/arduino/go-properties-orderedmap - go get github.com/arduino/go-timeutils script: diff --git a/README.md b/README.md index ddd8efc2..275ca796 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ To build, run the following commands: go get github.com/go-errors/errors go get github.com/stretchr/testify go get github.com/jstemmer/go-junit-report -go get -u github.com/arduino/go-properties-map +go get -u github.com/arduino/go-properties-orderedmap go get -u github.com/arduino/go-timeutils go get google.golang.org/grpc go get github.com/golang/protobuf/proto diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go index 60068145..760d0e09 100644 --- a/fail_if_imported_library_is_wrong.go +++ b/fail_if_imported_library_is_wrong.go @@ -51,7 +51,7 @@ func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { return i18n.ErrorfWithLogger(logger, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) } for _, propName := range libraries.MandatoryProperties { - if _, ok := library.Properties[propName]; !ok { + if !library.Properties.ContainsKey(propName) { return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.InstallDir) } } diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go index 9b0fd67d..c4f90a63 100644 --- a/platform_keys_rewrite_loader.go +++ b/platform_keys_rewrite_loader.go @@ -39,7 +39,7 @@ import ( "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type PlatformKeysRewriteLoader struct{} @@ -73,8 +73,8 @@ func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { return i18n.WrapError(err) } rewriteKey := strings.Join(keyParts[2:], ".") - oldValue := txt[key] - newValue := txt[constants.PLATFORM_REWRITE_NEW+"."+strings.Join(keyParts[1:], ".")] + oldValue := txt.Get(key) + newValue := txt.Get(constants.PLATFORM_REWRITE_NEW + "." + strings.Join(keyParts[1:], ".")) platformKeyRewrite := types.PlatforKeyRewrite{Key: rewriteKey, OldValue: oldValue, NewValue: newValue} platformKeysRewrite.Rewrites = growSliceOfRewrites(platformKeysRewrite.Rewrites, index) platformKeysRewrite.Rewrites[index] = platformKeyRewrite diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index c3b32ff0..e371b942 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -47,7 +47,7 @@ import ( "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/utils" "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" "github.com/go-errors/errors" ) diff --git a/wipeout_build_path_if_build_options_changed.go b/wipeout_build_path_if_build_options_changed.go index b7bc0946..4816d797 100644 --- a/wipeout_build_path_if_build_options_changed.go +++ b/wipeout_build_path_if_build_options_changed.go @@ -38,7 +38,7 @@ import ( "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-map" + "github.com/arduino/go-properties-orderedmap" ) type WipeoutBuildPathIfBuildOptionsChanged struct{} @@ -51,15 +51,15 @@ func (s *WipeoutBuildPathIfBuildOptionsChanged) Run(ctx *types.Context) error { previousBuildOptionsJson := ctx.BuildOptionsJsonPrevious logger := ctx.GetLogger() - var opts properties.Map - var prevOpts properties.Map + var opts *properties.Map + var prevOpts *properties.Map json.Unmarshal([]byte(buildOptionsJson), &opts) json.Unmarshal([]byte(previousBuildOptionsJson), &prevOpts) // If SketchLocation path is different but filename is the same, consider it equal - if filepath.Base(opts["sketchLocation"]) == filepath.Base(prevOpts["sketchLocation"]) { - delete(opts, "sketchLocation") - delete(prevOpts, "sketchLocation") + if filepath.Base(opts.Get("sketchLocation")) == filepath.Base(prevOpts.Get("sketchLocation")) { + opts.Remove("sketchLocation") + prevOpts.Remove("sketchLocation") } // If options are not changed check if core has From eb9e737c5c13f3dc7421e8a953f0414abbbb39a9 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 2 Oct 2018 16:38:32 +0200 Subject: [PATCH 46/57] Adopting ordered properties map (part 3) --- test/helper_tools_downloader.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go index e371b942..8e092a7e 100644 --- a/test/helper_tools_downloader.go +++ b/test/helper_tools_downloader.go @@ -393,7 +393,7 @@ func coreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) (bool, return false, i18n.WrapError(err) } - if core.Version != platform["version"] { + if core.Version != platform.Get("version") { err := corePath.RemoveAll() return false, i18n.WrapError(err) } @@ -446,7 +446,7 @@ func libraryAlreadyDownloadedAndUnpacked(targetPath *paths.Path, library Library if err != nil { return false } - return libProps["version"] == library.Version || libProps["version"] == library.VersionInLibProperties + return libProps.Get("version") == library.Version || libProps.Get("version") == library.VersionInLibProperties } func downloadAndUnpackCore(core Core, url string, targetPath *paths.Path) error { From f64c68b7bcdae69eeb1174f706d1fcef5e329519 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 16 Oct 2018 13:43:27 +0200 Subject: [PATCH 47/57] The board loader now detects default arguments in FQBN "config" This commit fixes the tests --- test/add_build_board_property_if_missing_test.go | 13 +++++++------ test/user_hardware/my_avr_platform/avr/boards.txt | 4 ++-- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go index 9293078b..4ef6c097 100644 --- a/test/add_build_board_property_if_missing_test.go +++ b/test/add_build_board_property_if_missing_test.go @@ -34,7 +34,6 @@ import ( "testing" "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/go-paths-helper" @@ -53,6 +52,7 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { ctx := &types.Context{ HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), FQBN: parseFQBN(t, "my_avr_platform:avr:mymega"), + Verbose: true, } commands := []types.Command{ @@ -74,8 +74,8 @@ func TestAddBuildBoardPropertyIfMissing(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, "", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_MCU)) - require.Equal(t, "AVR_MYMEGA", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) + require.Equal(t, "atmega2560", targetBoard.Properties.Get("build.mcu")) + require.Equal(t, "AVR_MYMEGA2560", targetBoard.Properties.Get("build.board")) } func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { @@ -83,7 +83,8 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { ctx := &types.Context{ HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), + FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega1280"), + Verbose: true, } commands := []types.Command{ @@ -103,6 +104,6 @@ func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { require.Equal(t, "avr", targetPlatform.Platform.Architecture) targetBoard := ctx.TargetBoard require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, "atmega2560", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_MCU)) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) + require.Equal(t, "atmega1280", targetBoard.Properties.Get("build.mcu")) + require.Equal(t, "AVR_MYMEGA", targetBoard.Properties.Get("build.board")) } diff --git a/test/user_hardware/my_avr_platform/avr/boards.txt b/test/user_hardware/my_avr_platform/avr/boards.txt index 6b98abf5..35bd3548 100644 --- a/test/user_hardware/my_avr_platform/avr/boards.txt +++ b/test/user_hardware/my_avr_platform/avr/boards.txt @@ -68,7 +68,7 @@ mymega.menu.cpu.atmega2560.bootloader.extended_fuses=0xFD mymega.menu.cpu.atmega2560.bootloader.file={bootloader._folder}/stk500boot_v2_mega2560.hex mymega.menu.cpu.atmega2560.build.mcu=atmega2560 -mymega.menu.cpu.atmega2560.build.board=AVR_MEGA2560 +mymega.menu.cpu.atmega2560.build.board=AVR_MYMEGA2560 mymega.menu.cpu.atmega1280=ATmega1280 @@ -82,4 +82,4 @@ mymega.menu.cpu.atmega1280.bootloader.extended_fuses=0xF5 mymega.menu.cpu.atmega1280.bootloader.file={bootloader._folder}/ATmegaBOOT_168_atmega1280.hex mymega.menu.cpu.atmega1280.build.mcu=atmega1280 -mymega.menu.cpu.atmega1280.build.board=AVR_MEGA +mymega.menu.cpu.atmega1280.build.board=AVR_MYMEGA From 75c65fde2a90ac33f2528ac38385fae02f6bad97 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 16 Oct 2018 14:44:10 +0200 Subject: [PATCH 48/57] Fix travis build --- .travis.yml | 20 ++++++++++++++++---- README.md | 1 + 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5e65b5f4..c1c46f58 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,20 +1,32 @@ language: go +os: + - linux + - osx + go: - - 1.9.2 + - 1.11.x install: - go get github.com/go-errors/errors - go get github.com/stretchr/testify - go get github.com/jstemmer/go-junit-report + - go get github.com/arduino/go-paths-helper + - go get github.com/arduino/go-properties-orderedmap + - go get github.com/arduino/go-timeutils + - go get google.golang.org/grpc + - go get github.com/golang/protobuf/proto + - go get golang.org/x/net/context + - go get github.com/fsnotify/fsnotify + - go get github.com/arduino/arduino-cli - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls - go get github.com/wadey/gocovmerge - - go get github.com/arduino/go-properties-orderedmap - - go get github.com/arduino/go-timeutils script: - - go get github.com/arduino/arduino-builder/arduino-builder + - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-paths-helper + - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-properties-orderedmap + - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-timeutils - go build -o $HOME/arduino-builder -v github.com/arduino/arduino-builder/arduino-builder - export TEST_PACKAGES=`go list github.com/arduino/arduino-builder/...` - RES=0; I=0; for PKG in $TEST_PACKAGES; do go test -v -timeout 30m -covermode=count -coverprofile=coverage.$I.out $PKG; ((RES=RES+$?)); ((I++)); done; ( exit $RES ) diff --git a/README.md b/README.md index 275ca796..c351797c 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ To build, run the following commands: go get github.com/go-errors/errors go get github.com/stretchr/testify go get github.com/jstemmer/go-junit-report +go get -u github.com/arduino/go-paths-helper go get -u github.com/arduino/go-properties-orderedmap go get -u github.com/arduino/go-timeutils go get google.golang.org/grpc From 8f0fb63d56c77aa3265ea387b777970df2442977 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 16 Oct 2018 15:34:55 +0200 Subject: [PATCH 49/57] Fix travis build --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index c1c46f58..61733890 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,8 +32,8 @@ script: - RES=0; I=0; for PKG in $TEST_PACKAGES; do go test -v -timeout 30m -covermode=count -coverprofile=coverage.$I.out $PKG; ((RES=RES+$?)); ((I++)); done; ( exit $RES ) after_success: - - bin/gocovmerge coverage.*.out > coverage.out - - bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN + - $GOPATH/bin/gocovmerge coverage.*.out > coverage.out + - $GOPATH/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN env: global: From b5ab3ed3d5b1aee337d99109098115acba82fb66 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 1 Apr 2019 12:20:00 +0200 Subject: [PATCH 50/57] Added LoggerToIoWriter --- i18n/i18n.go | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/i18n/i18n.go b/i18n/i18n.go index 202d51c7..f605f5e7 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -52,6 +52,34 @@ type Logger interface { Flush() string } +type LoggerToIoWriter struct { + Writer io.Writer +} + +func (s LoggerToIoWriter) Fprintln(w io.Writer, level string, format string, a ...interface{}) { + fmt.Fprintln(s.Writer, Format(format, a...)) +} + +func (s LoggerToIoWriter) UnformattedFprintln(w io.Writer, str string) { + fmt.Fprintln(s.Writer, str) +} + +func (s LoggerToIoWriter) UnformattedWrite(w io.Writer, data []byte) { + s.Writer.Write(data) +} + +func (s LoggerToIoWriter) Println(level string, format string, a ...interface{}) { + s.Fprintln(nil, level, format, a...) +} + +func (s LoggerToIoWriter) Flush() string { + return "" +} + +func (s LoggerToIoWriter) Name() string { + return "LoggerToIoWriter" +} + type NoopLogger struct{} func (s NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {} From 6be83c9bf1f1c7c895d6fbb658a90053266d6ad5 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Mon, 1 Apr 2019 12:20:22 +0200 Subject: [PATCH 51/57] Log library discovery process using logger --- resolve_library.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/resolve_library.go b/resolve_library.go index 2760b8ae..ef8b4fff 100644 --- a/resolve_library.go +++ b/resolve_library.go @@ -32,6 +32,7 @@ package builder import ( "fmt" + "github.com/arduino/arduino-builder/constants" "github.com/arduino/arduino-builder/types" "github.com/arduino/arduino-cli/arduino/libraries" ) @@ -39,10 +40,12 @@ import ( func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { resolver := ctx.LibrariesResolver importedLibraries := ctx.ImportedLibraries + logger := ctx.GetLogger() candidates := resolver.AlternativesFor(header) - fmt.Printf("ResolveLibrary(%s)\n", header) - fmt.Printf(" -> candidates: %s\n", candidates) + logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf("Alternatives for %s: %s", header, candidates)) + logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf("ResolveLibrary(%s)", header)) + logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf(" -> candidates: %s", candidates)) if candidates == nil || len(candidates) == 0 { return nil From 63f49042802e011ec7a1e3193dc320dc25158d77 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 12 Apr 2019 11:07:29 +0200 Subject: [PATCH 52/57] Added Context.ExecStdout/ExecStderr to easy redirect output of executed commands --- i18n/i18n.go | 37 +++++++++++++++++++++++++------------ types/context.go | 9 +++++++-- utils/utils.go | 13 ++++++++++--- 3 files changed, 42 insertions(+), 17 deletions(-) diff --git a/i18n/i18n.go b/i18n/i18n.go index f605f5e7..2597b377 100644 --- a/i18n/i18n.go +++ b/i18n/i18n.go @@ -52,32 +52,45 @@ type Logger interface { Flush() string } -type LoggerToIoWriter struct { - Writer io.Writer +type LoggerToCustomStreams struct { + Stdout io.Writer + Stderr io.Writer } -func (s LoggerToIoWriter) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - fmt.Fprintln(s.Writer, Format(format, a...)) +func (s LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string, a ...interface{}) { + target := s.Stdout + if w == os.Stderr { + target = s.Stderr + } + fmt.Fprintln(target, Format(format, a...)) } -func (s LoggerToIoWriter) UnformattedFprintln(w io.Writer, str string) { - fmt.Fprintln(s.Writer, str) +func (s LoggerToCustomStreams) UnformattedFprintln(w io.Writer, str string) { + target := s.Stdout + if w == os.Stderr { + target = s.Stderr + } + fmt.Fprintln(target, str) } -func (s LoggerToIoWriter) UnformattedWrite(w io.Writer, data []byte) { - s.Writer.Write(data) +func (s LoggerToCustomStreams) UnformattedWrite(w io.Writer, data []byte) { + target := s.Stdout + if w == os.Stderr { + target = s.Stderr + } + target.Write(data) } -func (s LoggerToIoWriter) Println(level string, format string, a ...interface{}) { +func (s LoggerToCustomStreams) Println(level string, format string, a ...interface{}) { s.Fprintln(nil, level, format, a...) } -func (s LoggerToIoWriter) Flush() string { +func (s LoggerToCustomStreams) Flush() string { return "" } -func (s LoggerToIoWriter) Name() string { - return "LoggerToIoWriter" +func (s LoggerToCustomStreams) Name() string { + return "LoggerToCustomStreams" } type NoopLogger struct{} diff --git a/types/context.go b/types/context.go index 2dfeabab..d263908e 100644 --- a/types/context.go +++ b/types/context.go @@ -1,6 +1,7 @@ package types import ( + "io" "strings" "github.com/arduino/arduino-builder/i18n" @@ -9,8 +10,8 @@ import ( "github.com/arduino/arduino-cli/arduino/libraries" "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" + paths "github.com/arduino/go-paths-helper" + properties "github.com/arduino/go-properties-orderedmap" ) type ProgressStruct struct { @@ -110,6 +111,10 @@ type Context struct { // Experimental: use arduino-preprocessor to create prototypes UseArduinoPreprocessor bool + + // Out and Err stream to redirect all Exec commands + ExecStdout io.Writer + ExecStderr io.Writer } func (ctx *Context) ExtractBuildOptions() *properties.Map { diff --git a/utils/utils.go b/utils/utils.go index c31cc295..55a61b21 100644 --- a/utils/utils.go +++ b/utils/utils.go @@ -48,7 +48,7 @@ import ( "github.com/arduino/arduino-builder/gohasissues" "github.com/arduino/arduino-builder/i18n" "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" + paths "github.com/arduino/go-paths-helper" "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" ) @@ -288,6 +288,13 @@ 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.ExecStderr == nil { + ctx.ExecStderr = os.Stderr + } + if ctx.Verbose { ctx.GetLogger().UnformattedFprintln(os.Stdout, PrintableCommand(command.Args)) } @@ -296,14 +303,14 @@ func ExecCommand(ctx *types.Context, command *exec.Cmd, stdout int, stderr int) buffer := &bytes.Buffer{} command.Stdout = buffer } else if stdout == Show || stdout == ShowIfVerbose && ctx.Verbose { - command.Stdout = os.Stdout + command.Stdout = ctx.ExecStdout } if stderr == Capture { buffer := &bytes.Buffer{} command.Stderr = buffer } else if stderr == Show || stderr == ShowIfVerbose && ctx.Verbose { - command.Stderr = os.Stderr + command.Stderr = ctx.ExecStderr } err := command.Start() From 14969d058d724f4ebb9202f7b41642cdfc4d0dd8 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 May 2019 10:19:56 +0200 Subject: [PATCH 53/57] Removed builder module (moved into arduino-cli) (WIP) --- .gitignore | 81 - add_additional_entries_to_context.go | 86 - add_build_board_property_if_missing.go | 67 - ...operties_from_parent_platform_txt_files.go | 48 - additional_sketch_files_copier.go | 85 - builder.go | 218 --- builder_utils/utils.go | 533 ------ client/client.go | 87 - constants/constants.go | 175 -- container_add_prototypes.go | 71 - container_build_options.go | 56 - container_find_includes.go | 409 ----- container_merge_copy_sketch_files.go | 56 - container_setup.go | 70 - create_build_options_map.go | 51 - create_cmake_rule.go | 266 --- ctags/ctags_has_issues.go | 310 ---- ctags/ctags_parser.go | 254 --- ctags/ctags_parser_test.go | 347 ---- ctags/ctags_properties.go | 47 - ctags/ctags_to_prototypes.go | 120 -- ctags/ctags_to_prototypes_test.go | 239 --- ...tCTagsParserClassMembersAreFilteredOut.txt | 6 - .../TestCTagsParserDefaultArguments.txt | 3 - .../TestCTagsParserFunctionPointer.txt | 4 - .../TestCTagsParserFunctionPointers.txt | 5 - ...tCTagsParserFunctionPointersNoIndirect.txt | 7 - ctags/test_data/TestCTagsParserNamespace.txt | 4 - ...uldDealFunctionWithDifferentSignatures.txt | 3 - .../TestCTagsParserShouldDealWithClasses.txt | 2 - .../TestCTagsParserShouldDealWithMacros.txt | 8 - .../TestCTagsParserShouldDealWithStructs.txt | 5 - .../TestCTagsParserShouldListPrototypes.txt | 8 - .../TestCTagsParserShouldListTemplates.txt | 3 - .../TestCTagsParserShouldListTemplates2.txt | 4 - ctags/test_data/TestCTagsParserStatic.txt | 3 - .../TestCTagsParserStructWithFunctions.txt | 8 - ...TestCTagsRunnerSketchWithClassFunction.txt | 4 - .../TestCTagsRunnerSketchWithMultifile.txt | 77 - ctags_runner.go | 81 - ctags_target_file_saver.go | 57 - dump_build_properties.go | 52 - ensure_buildpath_exists.go | 44 - fail_if_buildpath_equals_sketchpath.go | 61 - fail_if_imported_library_is_wrong.go | 67 - filter_sketch_source.go | 106 -- gcc_preproc_runner.go | 104 -- generate_buildpath_if_missing.go | 61 - gohasissues/go_has_issues.go | 145 -- grpc/proto/builder.pb.go | 396 ---- grpc/proto/builder.proto | 63 - grpc/rpc.go | 235 --- hardware/platform.keys.rewrite.txt | 42 - hardware_loader.go | 50 - i18n/errors.go | 31 - i18n/i18n.go | 274 --- includes_finder_with_regexp.go | 60 - libraries_loader.go | 99 - load_previous_build_options.go | 54 - load_vid_pid_specific_properties.go | 80 - arduino-builder/main.go => main.go | 0 merge_sketch_with_bootloader.go | 148 -- phases/core_builder.go | 139 -- phases/libraries_builder.go | 179 -- phases/linker.go | 99 - phases/sizer.go | 182 -- phases/sizer_test.go | 102 -- phases/sketch_builder.go | 69 - platform_keys_rewrite_loader.go | 109 -- preprocess_sketch.go | 162 -- print_preprocessed_source.go | 45 - print_used_and_not_used_libraries.go | 71 - print_used_libraries_if_verbose.go | 64 - prototypes_adder.go | 120 -- read_file_and_store_in_context.go | 52 - recipe_runner.go | 85 - resolve_library.go | 81 - rewrite_hardware_keys.go | 74 - set_custom_build_properties.go | 50 - setup_build_properties.go | 133 -- sketch_loader.go | 137 -- sketch_saver.go | 49 - sketch_source_merger.go | 82 - store_build_options_map.go | 42 - target_board_resolver.go | 70 - test/.gitignore | 1 - .../add_additional_entries_to_context_test.go | 77 - ...dd_build_board_property_if_missing_test.go | 109 -- test/additional_sketch_files_copier_test.go | 134 -- test/builder_test.go | 422 ----- test/builder_utils_test.go | 191 -- test/create_build_options_map_test.go | 69 - test/ctags_runner_test.go | 279 --- test/dependent_libraries/library1/library1.h | 1 - test/dependent_libraries/library2/library2.h | 1 - .../dependent_libraries/library3/library3.cpp | 2 - test/dependent_libraries/library3/library3.h | 1 - test/dependent_libraries/library4/library4.h | 0 test/eol_processing/sketch.ino | 1 - ...ail_if_buildpath_equals_sketchpath_test.go | 59 - test/generate_buildpath_if_missing_test.go | 102 -- test/hardware/arduino/avr/boards.local.txt | 11 - test/hardware/arduino/avr/boards.txt | 18 - test/hardware/arduino/avr/platform.local.txt | 1 - test/hardware/platform.txt | 1 - test/hardware/watterott/avr/boards.txt | 130 -- test/hardware/watterott/avr/platform.txt | 146 -- test/hardware/watterott/avr/programmers.txt | 0 test/hardware_loader_test.go | 243 --- test/helper.go | 106 -- test/helper_tools_downloader.go | 853 --------- test/i18n_test.go | 72 - test/includes_finder_with_regexp_test.go | 103 -- test/includes_to_include_folders_test.go | 339 ---- .../ANewLibrary-master/anewlibrary.h | 0 test/libraries/Balanduino/Balanduino.h | 0 test/libraries/Balanduino/Kalman.h | 0 test/libraries/Balanduino/PS3BT.h | 0 test/libraries/Balanduino/SPP.h | 0 test/libraries/Balanduino/Wii.h | 0 test/libraries/Balanduino/XBOXRECV.h | 0 test/libraries/Balanduino/adk.h | 0 test/libraries/Balanduino/usbhub.h | 0 test/libraries/FakeAudio/Audio.h | 0 test/libraries/FakeAudio/FakeAudio.h | 0 test/libraries/IRremote/IRremote.h | 1 - test/libraries/IRremote/IRremoteInt.h | 0 test/libraries/SPI/SPI.cpp | 201 --- test/libraries/SPI/SPI.h | 324 ---- test/libraries/SPI/keywords.txt | 36 - test/libraries/SPI/library.properties | 11 - .../ShouldNotRecurseWithOldLibs.cpp | 0 .../ShouldNotRecurseWithOldLibs.h | 0 .../ShouldNotRecurseWithOldLibs/doc/error.cpp | 1 - .../utility/utils.cpp | 0 .../utility/utils.h | 0 test/libraries/USBHost/keywords.txt | 35 - test/libraries/USBHost/library.properties | 9 - .../USBHost/src/KeyboardController.cpp | 40 - .../USBHost/src/KeyboardController.h | 54 - .../libraries/USBHost/src/MouseController.cpp | 83 - test/libraries/USBHost/src/MouseController.h | 57 - test/libraries/USBHost/src/Usb.cpp | 857 --------- test/libraries/USBHost/src/Usb.h | 48 - test/libraries/USBHost/src/UsbCore.h | 291 --- test/libraries/USBHost/src/address.h | 280 --- test/libraries/USBHost/src/adk.cpp | 410 ----- test/libraries/USBHost/src/adk.h | 148 -- test/libraries/USBHost/src/confdescparser.h | 223 --- test/libraries/USBHost/src/hexdump.h | 61 - test/libraries/USBHost/src/hid.cpp | 112 -- test/libraries/USBHost/src/hid.h | 183 -- test/libraries/USBHost/src/hidboot.cpp | 223 --- test/libraries/USBHost/src/hidboot.h | 609 ------- .../USBHost/src/hidescriptorparser.cpp | 1599 ----------------- .../USBHost/src/hidescriptorparser.h | 173 -- test/libraries/USBHost/src/hiduniversal.cpp | 421 ----- test/libraries/USBHost/src/hiduniversal.h | 105 -- test/libraries/USBHost/src/hidusagestr.h | 977 ---------- test/libraries/USBHost/src/macros.h | 82 - test/libraries/USBHost/src/message.cpp | 116 -- test/libraries/USBHost/src/message.h | 78 - test/libraries/USBHost/src/parsetools.cpp | 67 - test/libraries/USBHost/src/parsetools.h | 143 -- test/libraries/USBHost/src/printhex.h | 84 - test/libraries/USBHost/src/sink_parser.h | 41 - test/libraries/USBHost/src/usb_ch9.h | 174 -- test/libraries/USBHost/src/usbhub.cpp | 426 ----- test/libraries/USBHost/src/usbhub.h | 252 --- test/libraries/testlib1/testlib1.h | 0 test/libraries/testlib2/testlib2.h | 0 test/libraries/testlib3/testlib3.h | 0 test/libraries/testlib4/testlib4.h | 0 test/libraries/wronglib/library.properties | 9 - test/libraries/wronglib/src/.gitkeep | 0 test/libraries/wronglib/utility/.gitkeep | 0 test/libraries_loader_test.go | 304 ---- test/load_previous_build_options_map_test.go | 68 - test/load_vid_pid_specific_properties_test.go | 103 -- test/merge_sketch_with_bootloader_test.go | 206 --- test/platform_keys_rewrite_loader_test.go | 74 - test/prototypes_adder_test.go | 950 ---------- test/read_file_and_store_in_context_test.go | 58 - test/recipe_runner_test.go | 69 - test/rewrite_hardware_keys_test.go | 124 -- test/setup_build_properties_test.go | 244 --- test/sketch1/doc.txt | 0 test/sketch1/header.h | 1 - test/sketch1/merged_sketch.txt | 16 - test/sketch1/old.pde | 0 test/sketch1/other.ino | 3 - test/sketch1/s_file.S | 0 test/sketch1/sketch.ino | 7 - test/sketch1/src/helper.h | 0 test/sketch10/sketch.ino | 5 - test/sketch11/sketch_fastleds.ino | 27 - test/sketch12/sketch12.ino | 16 - test/sketch2/SketchWithIfDef.ino | 50 - test/sketch2/SketchWithIfDef.preprocessed.txt | 65 - .../SketchWithIfDef.resolved.directives.txt | 55 - test/sketch2/empty_1.h | 4 - test/sketch2/empty_2.h | 4 - test/sketch3/Baladuino.ino | 303 ---- test/sketch3/Baladuino.preprocessed.txt | 311 ---- test/sketch4/CharWithEscapedDoubleQuote.ino | 338 ---- ...harWithEscapedDoubleQuote.preprocessed.txt | 385 ---- .../IncludeBetweenMultilineComment.ino | 15 - ...deBetweenMultilineComment.preprocessed.txt | 24 - test/sketch6/LineContinuations.ino | 34 - .../LineContinuations.preprocessed.txt | 43 - test/sketch7/StringWithComment.ino | 13 - .../StringWithComment.preprocessed.txt | 21 - test/sketch8/SketchWithStruct.ino | 22 - .../sketch8/SketchWithStruct.preprocessed.txt | 32 - test/sketch9/sketch.ino | 6 - .../sketch_class_function.ino | 8 - test/sketch_loader_test.go | 178 -- test/sketch_no_functions/main.ino | 8 - test/sketch_no_functions_two_files/main.ino | 8 - test/sketch_no_functions_two_files/partb.ino | 4 - test/sketch_source_merger_test.go | 63 - .../sketch.ino | 8 - .../sketch.ino | 9 - .../sketch_that_includes_arduino_h.ino | 14 - test/sketch_usbhost/sketch_usbhost.ino | 11 - .../backup/sketch.ino | 7 - test/sketch_with_backup_files/sketch.ino | 7 - test/sketch_with_class/sketch.ino | 19 - ...sketch_with_class_and_method_substring.ino | 13 - test/sketch_with_config/config.h | 1 - .../sketch_with_config/sketch_with_config.ino | 19 - .../sketch_with_config.preprocessed.txt | 28 - .../src/includes/de bug.cpp | 5 - test/sketch_with_config/src/includes/de bug.h | 0 test/sketch_with_const/sketch.ino | 10 - test/sketch_with_default_args/sketch.ino | 8 - .../sketch.ino | 1 - .../sketch_with_enum_class.ino | 19 - .../sketch_with_externC.ino | 11 - .../sketch_with_externC_multiline.ino | 34 - .../sketch_with_fake_function_pointer.ino | 19 - .../CallbackBug.h | 5 - test/sketch_with_function_pointer/sketch.ino | 5 - .../sketch.ino | 20 - test/sketch_with_ifdef/sketch.ino | 15 - .../sketch.preprocessed.SAM.txt | 29 - .../sketch_with_ifdef/sketch.preprocessed.txt | 29 - test/sketch_with_inline_function/sketch.ino | 14 - test/sketch_with_macosx_garbage/.#sketch.ino | 2 - test/sketch_with_macosx_garbage/sketch.ino | 2 - .../sketch_with_multiline_prototypes.ino | 53 - .../sketch_with_multiline_template.ino | 10 - test/sketch_with_namespace/sketch.ino | 8 - test/sketch_with_old_lib/sketch.ino | 9 - .../sketch_with_static_asserts.ino | 16 - .../sketch_with_subfolders.ino | 12 - .../src/subfolder/dont_load_me.ino | 1 - .../src/subfolder/other.cpp | 11 - .../src/subfolder/other.h | 13 - .../subfolder/dont_load_me.cpp | 2 - .../subfolder/dont_load_me.ino | 2 - test/sketch_with_subfolders/subfolder/other.h | 2 - .../template_and_shift.cpp | 19 - test/sketch_with_typename/sketch.ino | 14 - test/sketch_with_usbcon/sketch.ino | 18 - test/store_build_options_map_test.go | 87 - test/target_board_resolver_test.go | 194 -- .../avr/builtin_tools_versions.txt | 2 - test/tools_loader_test.go | 198 -- test/try_build_of_problematic_sketch_test.go | 264 --- test/unique_string_queue_test.go | 48 - test/unquote_test.go | 54 - .../unused_compiled_libraries_remover_test.go | 106 -- test/user_hardware/arduino/avr/.gitkeep | 0 .../my_avr_platform/avr/boards.txt | 85 - .../stk500v2/stk500boot_v2_mega2560.hex | 469 ----- .../my_avr_platform/avr/libraries/SPI/SPI.cpp | 201 --- .../my_avr_platform/avr/libraries/SPI/SPI.h | 324 ---- .../BarometricPressureSensor.ino | 143 -- .../DigitalPotControl/DigitalPotControl.ino | 71 - .../avr/libraries/SPI/keywords.txt | 36 - .../avr/libraries/SPI/library.properties | 10 - .../my_avr_platform/avr/platform.txt | 9 - .../my_avr_platform/platform.txt | 1 - test/user_hardware/my_symlinked_avr_platform | 1 - test/utils_test.go | 159 -- ...uild_path_if_build_options_changed_test.go | 104 -- tools_loader.go | 87 - types/accessories.go | 110 -- types/context.go | 169 -- types/types.go | 176 -- types/utils.go | 49 - unused_compiled_libraries_remover.go | 73 - utils/utils.go | 624 ------- warn_about_arch_incompatible_libraries.go | 66 - warn_about_platform_rewrites.go | 70 - ...out_build_path_if_build_options_changed.go | 94 - 297 files changed, 29759 deletions(-) delete mode 100644 .gitignore delete mode 100644 add_additional_entries_to_context.go delete mode 100644 add_build_board_property_if_missing.go delete mode 100644 add_missing_build_properties_from_parent_platform_txt_files.go delete mode 100644 additional_sketch_files_copier.go delete mode 100644 builder.go delete mode 100644 builder_utils/utils.go delete mode 100644 client/client.go delete mode 100644 constants/constants.go delete mode 100644 container_add_prototypes.go delete mode 100644 container_build_options.go delete mode 100644 container_find_includes.go delete mode 100644 container_merge_copy_sketch_files.go delete mode 100644 container_setup.go delete mode 100644 create_build_options_map.go delete mode 100644 create_cmake_rule.go delete mode 100644 ctags/ctags_has_issues.go delete mode 100644 ctags/ctags_parser.go delete mode 100644 ctags/ctags_parser_test.go delete mode 100644 ctags/ctags_properties.go delete mode 100644 ctags/ctags_to_prototypes.go delete mode 100644 ctags/ctags_to_prototypes_test.go delete mode 100644 ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt delete mode 100644 ctags/test_data/TestCTagsParserDefaultArguments.txt delete mode 100644 ctags/test_data/TestCTagsParserFunctionPointer.txt delete mode 100644 ctags/test_data/TestCTagsParserFunctionPointers.txt delete mode 100644 ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt delete mode 100644 ctags/test_data/TestCTagsParserNamespace.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldDealWithClasses.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldDealWithMacros.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldDealWithStructs.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldListPrototypes.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldListTemplates.txt delete mode 100644 ctags/test_data/TestCTagsParserShouldListTemplates2.txt delete mode 100644 ctags/test_data/TestCTagsParserStatic.txt delete mode 100644 ctags/test_data/TestCTagsParserStructWithFunctions.txt delete mode 100644 ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt delete mode 100644 ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt delete mode 100644 ctags_runner.go delete mode 100644 ctags_target_file_saver.go delete mode 100644 dump_build_properties.go delete mode 100644 ensure_buildpath_exists.go delete mode 100644 fail_if_buildpath_equals_sketchpath.go delete mode 100644 fail_if_imported_library_is_wrong.go delete mode 100644 filter_sketch_source.go delete mode 100644 gcc_preproc_runner.go delete mode 100644 generate_buildpath_if_missing.go delete mode 100644 gohasissues/go_has_issues.go delete mode 100644 grpc/proto/builder.pb.go delete mode 100644 grpc/proto/builder.proto delete mode 100644 grpc/rpc.go delete mode 100644 hardware/platform.keys.rewrite.txt delete mode 100644 hardware_loader.go delete mode 100644 i18n/errors.go delete mode 100644 i18n/i18n.go delete mode 100644 includes_finder_with_regexp.go delete mode 100644 libraries_loader.go delete mode 100644 load_previous_build_options.go delete mode 100644 load_vid_pid_specific_properties.go rename arduino-builder/main.go => main.go (100%) delete mode 100644 merge_sketch_with_bootloader.go delete mode 100644 phases/core_builder.go delete mode 100644 phases/libraries_builder.go delete mode 100644 phases/linker.go delete mode 100644 phases/sizer.go delete mode 100644 phases/sizer_test.go delete mode 100644 phases/sketch_builder.go delete mode 100644 platform_keys_rewrite_loader.go delete mode 100644 preprocess_sketch.go delete mode 100644 print_preprocessed_source.go delete mode 100644 print_used_and_not_used_libraries.go delete mode 100644 print_used_libraries_if_verbose.go delete mode 100644 prototypes_adder.go delete mode 100644 read_file_and_store_in_context.go delete mode 100644 recipe_runner.go delete mode 100644 resolve_library.go delete mode 100644 rewrite_hardware_keys.go delete mode 100644 set_custom_build_properties.go delete mode 100644 setup_build_properties.go delete mode 100644 sketch_loader.go delete mode 100644 sketch_saver.go delete mode 100644 sketch_source_merger.go delete mode 100644 store_build_options_map.go delete mode 100644 target_board_resolver.go delete mode 100644 test/.gitignore delete mode 100644 test/add_additional_entries_to_context_test.go delete mode 100644 test/add_build_board_property_if_missing_test.go delete mode 100644 test/additional_sketch_files_copier_test.go delete mode 100644 test/builder_test.go delete mode 100644 test/builder_utils_test.go delete mode 100644 test/create_build_options_map_test.go delete mode 100644 test/ctags_runner_test.go delete mode 100644 test/dependent_libraries/library1/library1.h delete mode 100644 test/dependent_libraries/library2/library2.h delete mode 100644 test/dependent_libraries/library3/library3.cpp delete mode 100644 test/dependent_libraries/library3/library3.h delete mode 100644 test/dependent_libraries/library4/library4.h delete mode 100644 test/eol_processing/sketch.ino delete mode 100644 test/fail_if_buildpath_equals_sketchpath_test.go delete mode 100644 test/generate_buildpath_if_missing_test.go delete mode 100644 test/hardware/arduino/avr/boards.local.txt delete mode 100644 test/hardware/arduino/avr/boards.txt delete mode 100644 test/hardware/arduino/avr/platform.local.txt delete mode 100644 test/hardware/platform.txt delete mode 100644 test/hardware/watterott/avr/boards.txt delete mode 100644 test/hardware/watterott/avr/platform.txt delete mode 100644 test/hardware/watterott/avr/programmers.txt delete mode 100644 test/hardware_loader_test.go delete mode 100644 test/helper.go delete mode 100644 test/helper_tools_downloader.go delete mode 100644 test/i18n_test.go delete mode 100644 test/includes_finder_with_regexp_test.go delete mode 100644 test/includes_to_include_folders_test.go delete mode 100644 test/libraries/ANewLibrary-master/anewlibrary.h delete mode 100644 test/libraries/Balanduino/Balanduino.h delete mode 100644 test/libraries/Balanduino/Kalman.h delete mode 100644 test/libraries/Balanduino/PS3BT.h delete mode 100644 test/libraries/Balanduino/SPP.h delete mode 100644 test/libraries/Balanduino/Wii.h delete mode 100644 test/libraries/Balanduino/XBOXRECV.h delete mode 100644 test/libraries/Balanduino/adk.h delete mode 100644 test/libraries/Balanduino/usbhub.h delete mode 100644 test/libraries/FakeAudio/Audio.h delete mode 100644 test/libraries/FakeAudio/FakeAudio.h delete mode 100644 test/libraries/IRremote/IRremote.h delete mode 100644 test/libraries/IRremote/IRremoteInt.h delete mode 100644 test/libraries/SPI/SPI.cpp delete mode 100644 test/libraries/SPI/SPI.h delete mode 100644 test/libraries/SPI/keywords.txt delete mode 100644 test/libraries/SPI/library.properties delete mode 100644 test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.cpp delete mode 100644 test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.h delete mode 100644 test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp delete mode 100644 test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.cpp delete mode 100644 test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.h delete mode 100644 test/libraries/USBHost/keywords.txt delete mode 100644 test/libraries/USBHost/library.properties delete mode 100644 test/libraries/USBHost/src/KeyboardController.cpp delete mode 100644 test/libraries/USBHost/src/KeyboardController.h delete mode 100644 test/libraries/USBHost/src/MouseController.cpp delete mode 100644 test/libraries/USBHost/src/MouseController.h delete mode 100644 test/libraries/USBHost/src/Usb.cpp delete mode 100644 test/libraries/USBHost/src/Usb.h delete mode 100644 test/libraries/USBHost/src/UsbCore.h delete mode 100644 test/libraries/USBHost/src/address.h delete mode 100644 test/libraries/USBHost/src/adk.cpp delete mode 100644 test/libraries/USBHost/src/adk.h delete mode 100644 test/libraries/USBHost/src/confdescparser.h delete mode 100644 test/libraries/USBHost/src/hexdump.h delete mode 100644 test/libraries/USBHost/src/hid.cpp delete mode 100644 test/libraries/USBHost/src/hid.h delete mode 100644 test/libraries/USBHost/src/hidboot.cpp delete mode 100644 test/libraries/USBHost/src/hidboot.h delete mode 100644 test/libraries/USBHost/src/hidescriptorparser.cpp delete mode 100644 test/libraries/USBHost/src/hidescriptorparser.h delete mode 100644 test/libraries/USBHost/src/hiduniversal.cpp delete mode 100644 test/libraries/USBHost/src/hiduniversal.h delete mode 100644 test/libraries/USBHost/src/hidusagestr.h delete mode 100644 test/libraries/USBHost/src/macros.h delete mode 100644 test/libraries/USBHost/src/message.cpp delete mode 100644 test/libraries/USBHost/src/message.h delete mode 100644 test/libraries/USBHost/src/parsetools.cpp delete mode 100644 test/libraries/USBHost/src/parsetools.h delete mode 100644 test/libraries/USBHost/src/printhex.h delete mode 100644 test/libraries/USBHost/src/sink_parser.h delete mode 100644 test/libraries/USBHost/src/usb_ch9.h delete mode 100644 test/libraries/USBHost/src/usbhub.cpp delete mode 100644 test/libraries/USBHost/src/usbhub.h delete mode 100644 test/libraries/testlib1/testlib1.h delete mode 100644 test/libraries/testlib2/testlib2.h delete mode 100644 test/libraries/testlib3/testlib3.h delete mode 100644 test/libraries/testlib4/testlib4.h delete mode 100644 test/libraries/wronglib/library.properties delete mode 100644 test/libraries/wronglib/src/.gitkeep delete mode 100644 test/libraries/wronglib/utility/.gitkeep delete mode 100644 test/libraries_loader_test.go delete mode 100644 test/load_previous_build_options_map_test.go delete mode 100644 test/load_vid_pid_specific_properties_test.go delete mode 100644 test/merge_sketch_with_bootloader_test.go delete mode 100644 test/platform_keys_rewrite_loader_test.go delete mode 100644 test/prototypes_adder_test.go delete mode 100644 test/read_file_and_store_in_context_test.go delete mode 100644 test/recipe_runner_test.go delete mode 100644 test/rewrite_hardware_keys_test.go delete mode 100644 test/setup_build_properties_test.go delete mode 100644 test/sketch1/doc.txt delete mode 100644 test/sketch1/header.h delete mode 100644 test/sketch1/merged_sketch.txt delete mode 100644 test/sketch1/old.pde delete mode 100644 test/sketch1/other.ino delete mode 100644 test/sketch1/s_file.S delete mode 100644 test/sketch1/sketch.ino delete mode 100644 test/sketch1/src/helper.h delete mode 100644 test/sketch10/sketch.ino delete mode 100644 test/sketch11/sketch_fastleds.ino delete mode 100644 test/sketch12/sketch12.ino delete mode 100644 test/sketch2/SketchWithIfDef.ino delete mode 100644 test/sketch2/SketchWithIfDef.preprocessed.txt delete mode 100644 test/sketch2/SketchWithIfDef.resolved.directives.txt delete mode 100644 test/sketch2/empty_1.h delete mode 100644 test/sketch2/empty_2.h delete mode 100644 test/sketch3/Baladuino.ino delete mode 100644 test/sketch3/Baladuino.preprocessed.txt delete mode 100644 test/sketch4/CharWithEscapedDoubleQuote.ino delete mode 100644 test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt delete mode 100644 test/sketch5/IncludeBetweenMultilineComment.ino delete mode 100644 test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt delete mode 100644 test/sketch6/LineContinuations.ino delete mode 100644 test/sketch6/LineContinuations.preprocessed.txt delete mode 100644 test/sketch7/StringWithComment.ino delete mode 100644 test/sketch7/StringWithComment.preprocessed.txt delete mode 100644 test/sketch8/SketchWithStruct.ino delete mode 100644 test/sketch8/SketchWithStruct.preprocessed.txt delete mode 100644 test/sketch9/sketch.ino delete mode 100644 test/sketch_class_function/sketch_class_function.ino delete mode 100644 test/sketch_loader_test.go delete mode 100644 test/sketch_no_functions/main.ino delete mode 100644 test/sketch_no_functions_two_files/main.ino delete mode 100644 test/sketch_no_functions_two_files/partb.ino delete mode 100644 test/sketch_source_merger_test.go delete mode 100644 test/sketch_that_checks_if_SPI_has_transactions/sketch.ino delete mode 100644 test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino delete mode 100644 test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino delete mode 100644 test/sketch_usbhost/sketch_usbhost.ino delete mode 100644 test/sketch_with_backup_files/backup/sketch.ino delete mode 100644 test/sketch_with_backup_files/sketch.ino delete mode 100644 test/sketch_with_class/sketch.ino delete mode 100644 test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino delete mode 100644 test/sketch_with_config/config.h delete mode 100644 test/sketch_with_config/sketch_with_config.ino delete mode 100644 test/sketch_with_config/sketch_with_config.preprocessed.txt delete mode 100644 test/sketch_with_config/src/includes/de bug.cpp delete mode 100644 test/sketch_with_config/src/includes/de bug.h delete mode 100644 test/sketch_with_const/sketch.ino delete mode 100644 test/sketch_with_default_args/sketch.ino delete mode 100644 test/sketch_with_dependend_libraries/sketch.ino delete mode 100644 test/sketch_with_enum_class/sketch_with_enum_class.ino delete mode 100644 test/sketch_with_externC/sketch_with_externC.ino delete mode 100644 test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino delete mode 100644 test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino delete mode 100644 test/sketch_with_function_pointer/CallbackBug.h delete mode 100644 test/sketch_with_function_pointer/sketch.ino delete mode 100644 test/sketch_with_function_signature_inside_ifdef/sketch.ino delete mode 100644 test/sketch_with_ifdef/sketch.ino delete mode 100644 test/sketch_with_ifdef/sketch.preprocessed.SAM.txt delete mode 100644 test/sketch_with_ifdef/sketch.preprocessed.txt delete mode 100644 test/sketch_with_inline_function/sketch.ino delete mode 100644 test/sketch_with_macosx_garbage/.#sketch.ino delete mode 100644 test/sketch_with_macosx_garbage/sketch.ino delete mode 100644 test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino delete mode 100644 test/sketch_with_multiline_template/sketch_with_multiline_template.ino delete mode 100644 test/sketch_with_namespace/sketch.ino delete mode 100644 test/sketch_with_old_lib/sketch.ino delete mode 100644 test/sketch_with_static_asserts/sketch_with_static_asserts.ino delete mode 100644 test/sketch_with_subfolders/sketch_with_subfolders.ino delete mode 100644 test/sketch_with_subfolders/src/subfolder/dont_load_me.ino delete mode 100644 test/sketch_with_subfolders/src/subfolder/other.cpp delete mode 100644 test/sketch_with_subfolders/src/subfolder/other.h delete mode 100644 test/sketch_with_subfolders/subfolder/dont_load_me.cpp delete mode 100644 test/sketch_with_subfolders/subfolder/dont_load_me.ino delete mode 100644 test/sketch_with_subfolders/subfolder/other.h delete mode 100644 test/sketch_with_templates_and_shift/template_and_shift.cpp delete mode 100644 test/sketch_with_typename/sketch.ino delete mode 100644 test/sketch_with_usbcon/sketch.ino delete mode 100644 test/store_build_options_map_test.go delete mode 100644 test/target_board_resolver_test.go delete mode 100644 test/tools_builtin/avr/builtin_tools_versions.txt delete mode 100644 test/tools_loader_test.go delete mode 100644 test/try_build_of_problematic_sketch_test.go delete mode 100644 test/unique_string_queue_test.go delete mode 100644 test/unquote_test.go delete mode 100644 test/unused_compiled_libraries_remover_test.go delete mode 100644 test/user_hardware/arduino/avr/.gitkeep delete mode 100644 test/user_hardware/my_avr_platform/avr/boards.txt delete mode 100644 test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.h delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt delete mode 100644 test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties delete mode 100644 test/user_hardware/my_avr_platform/avr/platform.txt delete mode 100644 test/user_hardware/my_avr_platform/platform.txt delete mode 120000 test/user_hardware/my_symlinked_avr_platform delete mode 100644 test/utils_test.go delete mode 100644 test/wipeout_build_path_if_build_options_changed_test.go delete mode 100644 tools_loader.go delete mode 100644 types/accessories.go delete mode 100644 types/context.go delete mode 100644 types/types.go delete mode 100644 types/utils.go delete mode 100644 unused_compiled_libraries_remover.go delete mode 100644 utils/utils.go delete mode 100644 warn_about_arch_incompatible_libraries.go delete mode 100644 warn_about_platform_rewrites.go delete mode 100644 wipeout_build_path_if_build_options_changed.go diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 0df12e54..00000000 --- a/.gitignore +++ /dev/null @@ -1,81 +0,0 @@ -bin -src/github.com -src/golang.org -./arduino-builder - -# Created by .ignore support plugin (hsz.mobi) -### Go template -# Compiled Object files, Static and Dynamic libs (Shared Objects) -*.o -*.a -*.so - -# Folders -_obj -_test - -# Architecture specific extensions/prefixes -*.[568vq] -[568vq].out - -*.cgo1.go -*.cgo2.c -_cgo_defun.c -_cgo_gotypes.go -_cgo_export.* - -_testmain.go - -*.exe -*.test -*.prof - - - -### JetBrains template -# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm - -*.iml - -## Directory-based project format: -.idea/ -# if you remove the above rule, at least ignore the following: - -# User-specific stuff: -# .idea/workspace.xml -# .idea/tasks.xml -# .idea/dictionaries - -# Sensitive or high-churn files: -# .idea/dataSources.ids -# .idea/dataSources.xml -# .idea/sqlDataSources.xml -# .idea/dynamic.xml -# .idea/uiDesigner.xml - -# Gradle: -# .idea/gradle.xml -# .idea/libraries - -# Mongo Explorer plugin: -# .idea/mongoSettings.xml - -## File-based project format: -*.ipr -*.iws - -## Plugin-specific files: - -# IntelliJ -out/ - -# mpeltonen/sbt-idea plugin -.idea_modules/ - -# JIRA plugin -atlassian-ide-plugin.xml - -# Crashlytics plugin (for Android Studio and IntelliJ) -com_crashlytics_export_strings.xml -crashlytics.properties -crashlytics-build.properties diff --git a/add_additional_entries_to_context.go b/add_additional_entries_to_context.go deleted file mode 100644 index eaf32700..00000000 --- a/add_additional_entries_to_context.go +++ /dev/null @@ -1,86 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" -) - -type AddAdditionalEntriesToContext struct{} - -func (*AddAdditionalEntriesToContext) Run(ctx *types.Context) error { - if ctx.BuildPath != nil { - buildPath := ctx.BuildPath - preprocPath, err := buildPath.Join(constants.FOLDER_PREPROC).Abs() - if err != nil { - return i18n.WrapError(err) - } - sketchBuildPath, err := buildPath.Join(constants.FOLDER_SKETCH).Abs() - if err != nil { - return i18n.WrapError(err) - } - librariesBuildPath, err := buildPath.Join("libraries").Abs() - if err != nil { - return i18n.WrapError(err) - } - coreBuildPath, err := buildPath.Join(constants.FOLDER_CORE).Abs() - if err != nil { - return i18n.WrapError(err) - } - - ctx.PreprocPath = preprocPath - ctx.SketchBuildPath = sketchBuildPath - ctx.LibrariesBuildPath = librariesBuildPath - ctx.CoreBuildPath = coreBuildPath - } - - if ctx.BuildCachePath != nil { - coreBuildCachePath, err := ctx.BuildCachePath.Join(constants.FOLDER_CORE).Abs() - if err != nil { - return i18n.WrapError(err) - } - - ctx.CoreBuildCachePath = coreBuildCachePath - } - - if ctx.WarningsLevel == "" { - ctx.WarningsLevel = DEFAULT_WARNINGS_LEVEL - } - - ctx.CollectedSourceFiles = &types.UniqueSourceFileQueue{} - - ctx.LibrariesResolutionResults = map[string]types.LibraryResolutionResult{} - ctx.HardwareRewriteResults = map[*cores.PlatformRelease][]types.PlatforKeyRewrite{} - - return nil -} diff --git a/add_build_board_property_if_missing.go b/add_build_board_property_if_missing.go deleted file mode 100644 index c94b7a14..00000000 --- a/add_build_board_property_if_missing.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" -) - -type AddBuildBoardPropertyIfMissing struct{} - -func (*AddBuildBoardPropertyIfMissing) Run(ctx *types.Context) error { - packages := ctx.Hardware - logger := ctx.GetLogger() - - for _, aPackage := range packages.Packages { - for _, platform := range aPackage.Platforms { - for _, platformRelease := range platform.Releases { - 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, - constants.MSG_MISSING_BUILD_BOARD, - aPackage.Name, - platform.Architecture, - board.BoardID, - board.Properties.Get(constants.BUILD_PROPERTIES_BUILD_BOARD)) - } - } - } - } - } - - return nil -} diff --git a/add_missing_build_properties_from_parent_platform_txt_files.go b/add_missing_build_properties_from_parent_platform_txt_files.go deleted file mode 100644 index 1016cc6b..00000000 --- a/add_missing_build_properties_from_parent_platform_txt_files.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/ctags" - "github.com/arduino/arduino-builder/types" -) - -type AddMissingBuildPropertiesFromParentPlatformTxtFiles struct{} - -func (s *AddMissingBuildPropertiesFromParentPlatformTxtFiles) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - - newBuildProperties := ctags.CtagsProperties.Clone() - newBuildProperties.Merge(ArduinoPreprocessorProperties) - newBuildProperties.Merge(buildProperties) - ctx.BuildProperties = newBuildProperties - - return nil -} diff --git a/additional_sketch_files_copier.go b/additional_sketch_files_copier.go deleted file mode 100644 index 0d9043e1..00000000 --- a/additional_sketch_files_copier.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "bytes" - - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" -) - -type AdditionalSketchFilesCopier struct{} - -func (s *AdditionalSketchFilesCopier) Run(ctx *types.Context) error { - sketch := ctx.Sketch - sketchBuildPath := ctx.SketchBuildPath - - if err := sketchBuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - sketchBasePath := sketch.MainFile.Name.Parent() - - for _, file := range sketch.AdditionalFiles { - relativePath, err := sketchBasePath.RelTo(file.Name) - if err != nil { - return i18n.WrapError(err) - } - - targetFilePath := sketchBuildPath.JoinPath(relativePath) - if err = targetFilePath.Parent().MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - bytes, err := file.Name.ReadFile() - if err != nil { - return i18n.WrapError(err) - } - - if targetFileChanged(bytes, targetFilePath) { - if err := targetFilePath.WriteFile(bytes); err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func targetFileChanged(currentBytes []byte, targetFilePath *paths.Path) bool { - oldBytes, err := targetFilePath.ReadFile() - if err != nil { - return true - } - - return bytes.Compare(currentBytes, oldBytes) != 0 -} diff --git a/builder.go b/builder.go deleted file mode 100644 index c231c4fe..00000000 --- a/builder.go +++ /dev/null @@ -1,218 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "reflect" - "strconv" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/phases" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -var MAIN_FILE_VALID_EXTENSIONS = map[string]bool{".ino": true, ".pde": true} -var ADDITIONAL_FILE_VALID_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true} -var ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS = map[string]bool{".c": true, ".cpp": true, ".s": true} - -const DEFAULT_DEBUG_LEVEL = 5 -const DEFAULT_WARNINGS_LEVEL = "none" -const DEFAULT_SOFTWARE = "ARDUINO" - -type Builder struct{} - -func (s *Builder) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - &EnsureBuildPathExists{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &ContainerBuildOptions{}, - - &WarnAboutPlatformRewrites{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &ContainerMergeCopySketchFiles{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Detecting libraries used..."), - &ContainerFindIncludes{}, - - &WarnAboutArchIncompatibleLibraries{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Generating function prototypes..."), - &PreprocessSketch{}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling sketch..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_SKETCH_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.SketchBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_SKETCH_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling libraries..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LIBRARIES_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &UnusedCompiledLibrariesRemover{}, - &phases.LibrariesBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LIBRARIES_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Compiling core..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_CORE_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.CoreBuilder{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_CORE_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - utils.LogIfVerbose(constants.LOG_LEVEL_INFO, "Linking everything together..."), - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LINKING_PRELINK, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &phases.Linker{}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_LINKING_POSTLINK, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_OBJCOPY_PREOBJCOPY, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &RecipeByPrefixSuffixRunner{Prefix: "recipe.objcopy.", Suffix: constants.HOOKS_PATTERN_SUFFIX}, - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_OBJCOPY_POSTOBJCOPY, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &MergeSketchWithBootloader{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_POSTBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - } - - mainErr := runCommands(ctx, commands, true) - - commands = []types.Command{ - &PrintUsedAndNotUsedLibraries{SketchError: mainErr != nil}, - - &PrintUsedLibrariesIfVerbose{}, - - &ExportProjectCMake{SketchError: mainErr != nil}, - - &phases.Sizer{SketchError: mainErr != nil}, - } - otherErr := runCommands(ctx, commands, false) - - if mainErr != nil { - return mainErr - } - - return otherErr -} - -type PreprocessSketch struct{} - -func (s *PreprocessSketch) Run(ctx *types.Context) error { - var commands []types.Command - if ctx.UseArduinoPreprocessor { - commands = append(commands, &PreprocessSketchArduino{}) - } else { - commands = append(commands, &ContainerAddPrototypes{}) - } - return runCommands(ctx, commands, true) -} - -type Preprocess struct{} - -func (s *Preprocess) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - &EnsureBuildPathExists{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &ContainerBuildOptions{}, - - &RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - - &ContainerMergeCopySketchFiles{}, - - &ContainerFindIncludes{}, - - &WarnAboutArchIncompatibleLibraries{}, - - &PreprocessSketch{}, - - &PrintPreprocessedSource{}, - } - - return runCommands(ctx, commands, true) -} - -type ParseHardwareAndDumpBuildProperties struct{} - -func (s *ParseHardwareAndDumpBuildProperties) Run(ctx *types.Context) error { - commands := []types.Command{ - &GenerateBuildPathIfMissing{}, - - &ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &DumpBuildProperties{}, - } - - return runCommands(ctx, commands, true) -} - -func runCommands(ctx *types.Context, commands []types.Command, progressEnabled bool) error { - - ctx.Progress.PrintEnabled = progressEnabled - ctx.Progress.Progress = 0 - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - ctx.Progress.Steps = 100.0 / float64(len(commands)) - builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func PrintRingNameIfDebug(ctx *types.Context, command types.Command) { - if ctx.DebugLevel >= 10 { - ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_RUNNING_COMMAND, strconv.FormatInt(time.Now().Unix(), 10), reflect.Indirect(reflect.ValueOf(command)).Type().Name()) - } -} - -func RunBuilder(ctx *types.Context) error { - command := Builder{} - return command.Run(ctx) -} - -func RunParseHardwareAndDumpBuildProperties(ctx *types.Context) error { - command := ParseHardwareAndDumpBuildProperties{} - return command.Run(ctx) -} - -func RunPreprocess(ctx *types.Context) error { - command := Preprocess{} - return command.Run(ctx) -} diff --git a/builder_utils/utils.go b/builder_utils/utils.go deleted file mode 100644 index 194dceea..00000000 --- a/builder_utils/utils.go +++ /dev/null @@ -1,533 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder_utils - -import ( - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "sync" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" -) - -func PrintProgressIfProgressEnabledAndMachineLogger(ctx *types.Context) { - - if !ctx.Progress.PrintEnabled { - return - } - - log := ctx.GetLogger() - if log.Name() == "machine" { - log.Println(constants.LOG_LEVEL_INFO, constants.MSG_PROGRESS, strconv.FormatFloat(ctx.Progress.Progress, 'f', 2, 32)) - ctx.Progress.Progress += ctx.Progress.Steps - } -} - -func CompileFilesRecursive(ctx *types.Context, sourcePath *paths.Path, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { - objectFiles, err := CompileFiles(ctx, sourcePath, false, buildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - - folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - subFolderObjectFiles, err := CompileFilesRecursive(ctx, sourcePath.Join(folder.Name()), buildPath.Join(folder.Name()), buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles.AddAll(subFolderObjectFiles) - } - - return objectFiles, nil -} - -func CompileFiles(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { - sObjectFiles, err := compileFilesWithExtensionWithRecipe(ctx, sourcePath, recurse, buildPath, buildProperties, includes, ".S", constants.RECIPE_S_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - cObjectFiles, err := compileFilesWithExtensionWithRecipe(ctx, sourcePath, recurse, buildPath, buildProperties, includes, ".c", constants.RECIPE_C_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - cppObjectFiles, err := compileFilesWithExtensionWithRecipe(ctx, sourcePath, recurse, buildPath, buildProperties, includes, ".cpp", constants.RECIPE_CPP_PATTERN) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles := paths.NewPathList() - objectFiles.AddAll(sObjectFiles) - objectFiles.AddAll(cObjectFiles) - objectFiles.AddAll(cppObjectFiles) - return objectFiles, nil -} - -func compileFilesWithExtensionWithRecipe(ctx *types.Context, sourcePath *paths.Path, recurse bool, buildPath *paths.Path, buildProperties *properties.Map, includes []string, extension string, recipe string) (paths.PathList, error) { - sources, err := findFilesInFolder(sourcePath, extension, recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - return compileFilesWithRecipe(ctx, sourcePath, sources, buildPath, buildProperties, includes, recipe) -} - -func findFilesInFolder(sourcePath *paths.Path, extension string, recurse bool) (paths.PathList, error) { - files, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterFilesWithExtensions(extension)) - if err != nil { - return nil, i18n.WrapError(err) - } - var sources paths.PathList - for _, file := range files { - sources = append(sources, sourcePath.Join(file.Name())) - } - - if recurse { - folders, err := utils.ReadDirFiltered(sourcePath.String(), utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - otherSources, err := findFilesInFolder(sourcePath.Join(folder.Name()), extension, recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - sources = append(sources, otherSources...) - } - } - - return sources, nil -} - -func findAllFilesInFolder(sourcePath string, recurse bool) ([]string, error) { - files, err := utils.ReadDirFiltered(sourcePath, utils.FilterFiles()) - if err != nil { - return nil, i18n.WrapError(err) - } - var sources []string - for _, file := range files { - sources = append(sources, filepath.Join(sourcePath, file.Name())) - } - - if recurse { - folders, err := utils.ReadDirFiltered(sourcePath, utils.FilterDirs) - if err != nil { - return nil, i18n.WrapError(err) - } - - for _, folder := range folders { - otherSources, err := findAllFilesInFolder(filepath.Join(sourcePath, folder.Name()), recurse) - if err != nil { - return nil, i18n.WrapError(err) - } - sources = append(sources, otherSources...) - } - } - - return sources, nil -} - -func compileFilesWithRecipe(ctx *types.Context, sourcePath *paths.Path, sources paths.PathList, buildPath *paths.Path, buildProperties *properties.Map, includes []string, recipe string) (paths.PathList, error) { - objectFiles := paths.NewPathList() - if len(sources) == 0 { - return objectFiles, nil - } - objectFilesChan := make(chan *paths.Path) - errorsChan := make(chan error) - doneChan := make(chan struct{}) - - ctx.Progress.Steps = ctx.Progress.Steps / float64(len(sources)) - var wg sync.WaitGroup - wg.Add(len(sources)) - - for _, source := range sources { - go func(source *paths.Path) { - defer wg.Done() - PrintProgressIfProgressEnabledAndMachineLogger(ctx) - objectFile, err := compileFileWithRecipe(ctx, sourcePath, source, buildPath, buildProperties, includes, recipe) - if err != nil { - errorsChan <- err - } else { - objectFilesChan <- objectFile - } - }(source) - } - - go func() { - wg.Wait() - doneChan <- struct{}{} - }() - - for { - select { - case objectFile := <-objectFilesChan: - objectFiles.Add(objectFile) - case err := <-errorsChan: - return nil, i18n.WrapError(err) - case <-doneChan: - close(objectFilesChan) - for objectFile := range objectFilesChan { - objectFiles.Add(objectFile) - } - objectFiles.Sort() - return objectFiles, nil - } - } -} - -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)) - properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, source) - relativeSource, err := sourcePath.RelTo(source) - if err != nil { - return nil, i18n.WrapError(err) - } - properties.Set(constants.BUILD_PROPERTIES_OBJECT_FILE, buildPath.JoinPath(relativeSource).String()+".o") - - err = properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE).Parent().MkdirAll() - if err != nil { - return nil, i18n.WrapError(err) - } - - objIsUpToDate, err := ObjFileIsUpToDate(ctx, properties.GetPath(constants.BUILD_PROPERTIES_SOURCE_FILE), properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE), buildPath.Join(relativeSource.String()+".d")) - if err != nil { - return nil, i18n.WrapError(err) - } - - if !objIsUpToDate { - _, _, err = ExecRecipe(ctx, properties, recipe, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return nil, i18n.WrapError(err) - } - } else if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, properties.Get(constants.BUILD_PROPERTIES_OBJECT_FILE)) - } - - return properties.GetPath(constants.BUILD_PROPERTIES_OBJECT_FILE), nil -} - -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, "Checking previous results for {0} (result = {1}, dep = {2})", sourceFile, objectFile, dependencyFile) - } - if objectFile == nil || dependencyFile == nil { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: nil") - } - return false, nil - } - - sourceFile = sourceFile.Clean() - sourceFileStat, err := sourceFile.Stat() - if err != nil { - return false, i18n.WrapError(err) - } - - objectFile = objectFile.Clean() - objectFileStat, err := objectFile.Stat() - if err != nil { - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", objectFile) - } - return false, nil - } else { - return false, i18n.WrapError(err) - } - } - - dependencyFile = dependencyFile.Clean() - dependencyFileStat, err := dependencyFile.Stat() - if err != nil { - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", dependencyFile) - } - return false, nil - } else { - return false, i18n.WrapError(err) - } - } - - if sourceFileStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", sourceFile, objectFile) - } - return false, nil - } - if sourceFileStat.ModTime().After(dependencyFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", sourceFile, dependencyFile) - } - return false, nil - } - - rows, err := dependencyFile.ReadFileAsLines() - if err != nil { - return false, i18n.WrapError(err) - } - - rows = utils.Map(rows, removeEndingBackSlash) - rows = utils.Map(rows, strings.TrimSpace) - rows = utils.Map(rows, unescapeDep) - rows = utils.Filter(rows, nonEmptyString) - - if len(rows) == 0 { - return true, nil - } - - firstRow := rows[0] - if !strings.HasSuffix(firstRow, ":") { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "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, "Depfile is about different file: {0}", objFileInDepFile) - } - return false, nil - } - - rows = rows[1:] - for _, row := range rows { - depStat, err := os.Stat(row) - 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, "Failed to read: {0}", row) - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, i18n.WrapError(err).Error()) - } - return false, nil - } - if os.IsNotExist(err) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "Not found: {0}", row) - } - return false, nil - } - if depStat.ModTime().After(objectFileStat.ModTime()) { - if debugLevel >= 20 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, "{0} newer than {1}", row, objectFile) - } - return false, nil - } - } - - return true, nil -} - -func unescapeDep(s string) string { - s = strings.Replace(s, "\\ ", " ", -1) - s = strings.Replace(s, "\\\t", "\t", -1) - s = strings.Replace(s, "\\#", "#", -1) - s = strings.Replace(s, "$$", "$", -1) - s = strings.Replace(s, "\\\\", "\\", -1) - return s -} - -func removeEndingBackSlash(s string) string { - if strings.HasSuffix(s, "\\") { - s = s[:len(s)-1] - } - return s -} - -func nonEmptyString(s string) bool { - return s != constants.EMPTY_STRING -} - -func CoreOrReferencedCoreHasChanged(corePath, targetCorePath, targetFile *paths.Path) bool { - - targetFileStat, err := targetFile.Stat() - if err == nil { - files, err := findAllFilesInFolder(corePath.String(), true) - if err != nil { - return true - } - for _, file := range files { - fileStat, err := os.Stat(file) - if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) { - return true - } - } - if targetCorePath != nil && !strings.EqualFold(corePath.String(), targetCorePath.String()) { - return CoreOrReferencedCoreHasChanged(targetCorePath, nil, targetFile) - } - return false - } - return true -} - -func TXTBuildRulesHaveChanged(corePath, targetCorePath, targetFile *paths.Path) bool { - - targetFileStat, err := targetFile.Stat() - if err == nil { - files, err := findAllFilesInFolder(corePath.String(), true) - if err != nil { - return true - } - for _, file := range files { - // report changes only for .txt files - if filepath.Ext(file) != ".txt" { - continue - } - fileStat, err := os.Stat(file) - if err != nil || fileStat.ModTime().After(targetFileStat.ModTime()) { - return true - } - } - if targetCorePath != nil && !corePath.EqualsTo(targetCorePath) { - return TXTBuildRulesHaveChanged(targetCorePath, nil, targetFile) - } - return false - } - return true -} - -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) - - rebuildArchive := false - - if archiveFileStat, err := archiveFilePath.Stat(); err == nil { - - for _, objectFile := range objectFilesToArchive { - objectFileStat, err := objectFile.Stat() - if err != nil || objectFileStat.ModTime().After(archiveFileStat.ModTime()) { - // need to rebuild the archive - rebuildArchive = true - break - } - } - - // something changed, rebuild the core archive - if rebuildArchive { - err = archiveFilePath.Remove() - if err != nil { - return nil, i18n.WrapError(err) - } - } else { - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_PREVIOUS_COMPILED_FILE, archiveFilePath) - } - return archiveFilePath, nil - } - } - - for _, objectFile := range objectFilesToArchive { - properties := buildProperties.Clone() - properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE, archiveFilePath.Base()) - properties.SetPath(constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH, archiveFilePath) - properties.SetPath(constants.BUILD_PROPERTIES_OBJECT_FILE, objectFile) - - _, _, err := ExecRecipe(ctx, properties, constants.RECIPE_AR_PATTERN, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return nil, i18n.WrapError(err) - } - } - - return archiveFilePath, nil -} - -func ExecRecipe(ctx *types.Context, buildProperties *properties.Map, recipe string, removeUnsetProperties bool, stdout int, stderr int) ([]byte, []byte, error) { - // See util.ExecCommand for stdout/stderr arguments - command, err := PrepareCommandForRecipe(ctx, buildProperties, recipe, removeUnsetProperties) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - return utils.ExecCommand(ctx, command, stdout, stderr) -} - -const COMMANDLINE_LIMIT = 30000 - -func PrepareCommandForRecipe(ctx *types.Context, buildProperties *properties.Map, recipe string, removeUnsetProperties bool) (*exec.Cmd, error) { - logger := ctx.GetLogger() - pattern := buildProperties.Get(recipe) - if pattern == "" { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, recipe) - } - - var err error - commandLine := buildProperties.ExpandPropsInString(pattern) - if removeUnsetProperties { - commandLine = properties.DeleteUnexpandedPropsFromString(commandLine) - } - - relativePath := "" - - if len(commandLine) > COMMANDLINE_LIMIT { - relativePath = buildProperties.Get("build.path") - } - - command, err := utils.PrepareCommand(commandLine, logger, relativePath) - if err != nil { - return nil, i18n.WrapError(err) - } - - return command, nil -} - -// GetCachedCoreArchiveFileName returns the filename to be used to store -// the global cached core.a. -func GetCachedCoreArchiveFileName(fqbn string, coreFolder *paths.Path) string { - fqbnToUnderscore := strings.Replace(fqbn, ":", "_", -1) - fqbnToUnderscore = strings.Replace(fqbnToUnderscore, "=", "_", -1) - if absCoreFolder, err := coreFolder.Abs(); err == nil { - coreFolder = absCoreFolder - } // silently continue if absolute path can't be detected - hash := utils.MD5Sum([]byte(coreFolder.String())) - realName := "core_" + fqbnToUnderscore + "_" + hash + ".a" - if len(realName) > 100 { - // avoid really long names, simply hash the final part - realName = "core_" + utils.MD5Sum([]byte(fqbnToUnderscore+"_"+hash)) + ".a" - } - return realName -} diff --git a/client/client.go b/client/client.go deleted file mode 100644 index 29e2ce7c..00000000 --- a/client/client.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * - * Copyright 2015 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -// Package main implements a simple gRPC client that demonstrates how to use gRPC-Go libraries -// to perform unary, client streaming, server streaming and full duplex RPCs. -// -// It interacts with the route guide service whose definition can be found in routeguide/route_guide.proto. -package main - -import ( - "io" - "log" - - pb "github.com/arduino/arduino-builder/grpc/proto" - "golang.org/x/net/context" - "google.golang.org/grpc" -) - -// printFeature gets the feature for the given point. -func autocomplete(client pb.BuilderClient, in *pb.BuildParams) { - resp, err := client.Autocomplete(context.Background(), in) - if err != nil { - log.Fatalf("%v.GetFeatures(_) = _, %v: ", client, err) - } - log.Println(resp) -} - -// printFeatures lists all the features within the given bounding Rectangle. -func build(client pb.BuilderClient, in *pb.BuildParams) { - stream, err := client.Build(context.Background(), in) - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - for { - line, err := stream.Recv() - if err == io.EOF { - break - } - if err != nil { - log.Fatalf("%v.ListFeatures(_) = _, %v", client, err) - } - log.Println(line) - } -} - -func main() { - conn, err := grpc.Dial("localhost:12345", grpc.WithInsecure()) - if err != nil { - log.Fatalf("fail to dial: %v", err) - } - defer conn.Close() - - client := pb.NewBuilderClient(conn) - - exampleParames := pb.BuildParams{ - BuiltInLibrariesFolders: "/ssd/Arduino-master/build/linux/work/libraries", - CustomBuildProperties: "build.warn_data_percentage=75", - FQBN: "arduino:avr:mega:cpu=atmega2560", - HardwareFolders: "/ssd/Arduino-master/build/linux/work/hardware,/home/martino/.arduino15/packages,/home/martino/eslov-sk/hardware", - OtherLibrariesFolders: "/home/martino/eslov-sk/libraries", - ArduinoAPIVersion: "10805", - SketchLocation: "/home/martino/eslov-sk/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino", - ToolsFolders: "/ssd/Arduino-master/build/linux/work/tools-builder,/ssd/Arduino-master/build/linux/work/hardware/tools/avr,/home/martino/.arduino15/packages", - Verbose: true, - WarningsLevel: "all", - BuildCachePath: "/tmp/arduino_cache_761418/", - CodeCompleteAt: "/home/martino/eslov-sk/libraries/WiFi101/examples/ScanNetworks/ScanNetworks.ino:56:9", - } - - //build(client, &exampleParames) - autocomplete(client, &exampleParames) -} diff --git a/constants/constants.go b/constants/constants.go deleted file mode 100644 index 111ac299..00000000 --- a/constants/constants.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package constants - -const BUILD_OPTIONS_FILE = "build.options.json" -const BUILD_PROPERTIES_ARCHIVE_FILE = "archive_file" -const BUILD_PROPERTIES_ARCHIVE_FILE_PATH = "archive_file_path" -const BUILD_PROPERTIES_ARCH_OVERRIDE_CHECK = "architecture.override_check" -const BUILD_PROPERTIES_BOOTLOADER_FILE = "bootloader.file" -const BUILD_PROPERTIES_BOOTLOADER_NOBLINK = "bootloader.noblink" -const BUILD_PROPERTIES_BUILD_BOARD = "build.board" -const BUILD_PROPERTIES_BUILD_CORE_PATH = "build.core.path" -const BUILD_PROPERTIES_BUILD_MCU = "build.mcu" -const BUILD_PROPERTIES_BUILD_VARIANT_PATH = "build.variant.path" -const BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS = "compiler.c.elf.flags" -const BUILD_PROPERTIES_COMPILER_LDFLAGS = "compiler.ldflags" -const BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS = "compiler.libraries.ldflags" -const BUILD_PROPERTIES_COMPILER_CPP_FLAGS = "compiler.cpp.flags" -const BUILD_PROPERTIES_COMPILER_WARNING_FLAGS = "compiler.warning_flags" -const BUILD_PROPERTIES_FQBN = "build.fqbn" -const BUILD_PROPERTIES_INCLUDES = "includes" -const BUILD_PROPERTIES_OBJECT_FILE = "object_file" -const BUILD_PROPERTIES_OBJECT_FILES = "object_files" -const BUILD_PROPERTIES_PATTERN = "pattern" -const BUILD_PROPERTIES_PID = "pid" -const BUILD_PROPERTIES_PREPROCESSED_FILE_PATH = "preprocessed_file_path" -const BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH = "runtime.platform.path" -const BUILD_PROPERTIES_SOURCE_FILE = "source_file" -const BUILD_PROPERTIES_TOOLS_KEY = "tools" -const BUILD_PROPERTIES_VID = "vid" -const CTAGS = "ctags" -const EMPTY_STRING = "" -const FILE_CTAGS_TARGET_FOR_GCC_MINUS_E = "ctags_target_for_gcc_minus_e.cpp" -const FILE_PLATFORM_KEYS_REWRITE_TXT = "platform.keys.rewrite.txt" -const FILE_INCLUDES_CACHE = "includes.cache" -const FOLDER_BOOTLOADERS = "bootloaders" -const FOLDER_CORE = "core" -const FOLDER_PREPROC = "preproc" -const FOLDER_SKETCH = "sketch" -const FOLDER_TOOLS = "tools" -const hooks_core = hooks + ".core" -const HOOKS_CORE_POSTBUILD = hooks_core + hooks_postbuild_suffix -const HOOKS_CORE_PREBUILD = hooks_core + hooks_prebuild_suffix -const hooks_libraries = hooks + ".libraries" -const HOOKS_LIBRARIES_POSTBUILD = hooks_libraries + hooks_postbuild_suffix -const HOOKS_LIBRARIES_PREBUILD = hooks_libraries + hooks_prebuild_suffix -const hooks_linking = hooks + ".linking" -const HOOKS_LINKING_POSTLINK = hooks_linking + hooks_postlink_suffix -const HOOKS_LINKING_PRELINK = hooks_linking + hooks_prelink_suffix -const hooks_objcopy = hooks + ".objcopy" -const HOOKS_OBJCOPY_POSTOBJCOPY = hooks_objcopy + hooks_postobjcopy_suffix -const HOOKS_OBJCOPY_PREOBJCOPY = hooks_objcopy + hooks_preobjcopy_suffix -const HOOKS_PATTERN_SUFFIX = ".pattern" -const HOOKS_POSTBUILD = hooks + hooks_postbuild_suffix -const hooks_postbuild_suffix = ".postbuild" -const hooks_postlink_suffix = ".postlink" -const hooks_postobjcopy_suffix = ".postobjcopy" -const HOOKS_PREBUILD = hooks + hooks_prebuild_suffix -const hooks_prebuild_suffix = ".prebuild" -const hooks_prelink_suffix = ".prelink" -const hooks_preobjcopy_suffix = ".preobjcopy" -const hooks = "recipe.hooks" -const hooks_sketch = hooks + ".sketch" -const HOOKS_SKETCH_POSTBUILD = hooks_sketch + hooks_postbuild_suffix -const HOOKS_SKETCH_PREBUILD = hooks_sketch + hooks_prebuild_suffix -const LIBRARY_ALL_ARCHS = "*" -const LIBRARY_EMAIL = "email" -const LIBRARY_FOLDER_ARCH = "arch" -const LIBRARY_FOLDER_SRC = "src" -const LOG_LEVEL_DEBUG = "debug" -const LOG_LEVEL_ERROR = "error" -const LOG_LEVEL_INFO = "info" -const LOG_LEVEL_WARN = "warn" -const MSG_ARCH_FOLDER_NOT_SUPPORTED = "'arch' folder is no longer supported! See http://goo.gl/gfFJzU for more information" -const MSG_ARCHIVING_CORE_CACHE = "Archiving built core (caching) in: {0}" -const MSG_ERROR_ARCHIVING_CORE_CACHE = "Error archiving built core (caching) in {0}: {1}" -const MSG_CORE_CACHE_UNAVAILABLE = "Unable to cache built core, please tell {0} maintainers to follow http://goo.gl/QdCUjo" -const MSG_BOARD_UNKNOWN = "Board {0} (platform {1}, package {2}) is unknown" -const MSG_BOOTLOADER_FILE_MISSING = "Bootloader file specified but missing: {0}" -const MSG_BUILD_OPTIONS_CHANGED = "Build options changed, rebuilding all" -const MSG_CANT_FIND_SKETCH_IN_PATH = "Unable to find {0} in {1}" -const MSG_FQBN_INVALID = "{0} is not a valid fully qualified board name. Required format is targetPackageName:targetPlatformName:targetBoardName." -const MSG_FIND_INCLUDES_FAILED = "Error while detecting libraries included by {0}" -const MSG_INVALID_QUOTING = "Invalid quoting: no closing [{0}] char found." -const MSG_LIB_LEGACY = "(legacy)" -const MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR = "Multiple libraries were found for \"{0}\"" -const MSG_LIBRARIES_NOT_USED = " Not used: {0}" -const MSG_LIBRARIES_USED = " Used: {0}" -const MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS = "Library can't use both 'src' and 'utility' folders. Double check {0}" -const MSG_LIBRARY_INCOMPATIBLE_ARCH = "WARNING: library {0} claims to run on {1} architecture(s) and may be incompatible with your current board which runs on {2} architecture(s)." -const MSG_LOOKING_FOR_RECIPES = "Looking for recipes like {0}*{1}" -const MSG_MISSING_BUILD_BOARD = "Warning: Board {0}:{1}:{2} doesn''t define a ''build.board'' preference. Auto-set to: {3}" -const MSG_MISSING_CORE_FOR_BOARD = "Selected board depends on '{0}' core (not installed)." -const MSG_PACKAGE_UNKNOWN = "{0}: Unknown package" -const MSG_PATTERN_MISSING = "{0} pattern is missing" -const MSG_PLATFORM_UNKNOWN = "Platform {0} (package {1}) is unknown" -const MSG_PROGRESS = "Progress {0}" -const MSG_PROP_IN_LIBRARY = "Missing '{0}' from library in {1}" -const MSG_RUNNING_COMMAND = "Ts: {0} - Running: {1}" -const MSG_RUNNING_RECIPE = "Running recipe: {0}" -const MSG_SETTING_BUILD_PATH = "Setting build path to {0}" -const MSG_SIZER_TEXT_FULL = "Sketch uses {0} bytes ({2}%%) of program storage space. Maximum is {1} bytes." -const MSG_SIZER_DATA_FULL = "Global variables use {0} bytes ({2}%%) of dynamic memory, leaving {3} bytes for local variables. Maximum is {1} bytes." -const MSG_SIZER_DATA = "Global variables use {0} bytes of dynamic memory." -const MSG_SIZER_TEXT_TOO_BIG = "Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it." -const MSG_SIZER_DATA_TOO_BIG = "Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint." -const MSG_SIZER_LOW_MEMORY = "Low memory available, stability problems may occur." -const MSG_SIZER_ERROR_NO_RULE = "Couldn't determine program size" -const MSG_SKETCH_CANT_BE_IN_BUILDPATH = "Sketch cannot be located in build path. Please specify a different build path" -const MSG_UNKNOWN_SKETCH_EXT = "Unknown sketch file extension: {0}" -const MSG_USING_LIBRARY_AT_VERSION = "Using library {0} at version {1} in folder: {2} {3}" -const MSG_USING_LIBRARY = "Using library {0} in folder: {1} {2}" -const MSG_USING_BOARD = "Using board '{0}' from platform in folder: {1}" -const MSG_USING_CORE = "Using core '{0}' from platform in folder: {1}" -const MSG_USING_PREVIOUS_COMPILED_FILE = "Using previously compiled file: {0}" -const MSG_USING_CACHED_INCLUDES = "Using cached library dependencies for file: {0}" -const MSG_WARNING_LIB_INVALID_CATEGORY = "WARNING: Category '{0}' in library {1} is not valid. Setting to '{2}'" -const MSG_WARNING_PLATFORM_OLD_VALUES = "Warning: platform.txt from core '{0}' contains deprecated {1}, automatically converted to {2}. Consider upgrading this core." -const MSG_WARNING_SPURIOUS_FILE_IN_LIB = "WARNING: Spurious {0} folder in '{1}' library" -const PACKAGE_NAME = "name" -const PACKAGE_TOOLS = "tools" -const PLATFORM_ARCHITECTURE = "architecture" -const PLATFORM_NAME = "name" -const PLATFORM_REWRITE_NEW = "new" -const PLATFORM_REWRITE_OLD = "old" -const PLATFORM_URL = "url" -const PLATFORM_VERSION = "version" -const PROPERTY_WARN_DATA_PERCENT = "build.warn_data_percentage" -const PROPERTY_UPLOAD_MAX_SIZE = "upload.maximum_size" -const PROPERTY_UPLOAD_MAX_DATA_SIZE = "upload.maximum_data_size" -const RECIPE_AR_PATTERN = "recipe.ar.pattern" -const RECIPE_C_COMBINE_PATTERN = "recipe.c.combine.pattern" -const RECIPE_C_PATTERN = "recipe.c.o.pattern" -const RECIPE_CPP_PATTERN = "recipe.cpp.o.pattern" -const RECIPE_SIZE_PATTERN = "recipe.size.pattern" -const RECIPE_PREPROC_MACROS = "recipe.preproc.macros" -const RECIPE_S_PATTERN = "recipe.S.o.pattern" -const RECIPE_SIZE_REGEXP = "recipe.size.regex" -const RECIPE_SIZE_REGEXP_DATA = "recipe.size.regex.data" -const RECIPE_SIZE_REGEXP_EEPROM = "recipe.size.regex.eeprom" -const REWRITING_DISABLED = "disabled" -const REWRITING = "rewriting" -const SPACE = " " -const SKETCH_FOLDER_SRC = "src" -const TOOL_NAME = "name" -const TOOL_URL = "url" -const TOOL_VERSION = "version" diff --git a/container_add_prototypes.go b/container_add_prototypes.go deleted file mode 100644 index 8309288f..00000000 --- a/container_add_prototypes.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerAddPrototypes struct{} - -func (s *ContainerAddPrototypes) Run(ctx *types.Context) error { - // Generate the full pathname for the preproc output file - if err := ctx.PreprocPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - targetFilePath := ctx.PreprocPath.Join(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E) - - // Run preprocessor - sourceFile := ctx.SketchBuildPath.Join(ctx.Sketch.MainFile.Name.Base() + ".cpp") - if err := GCCPreprocRunner(ctx, sourceFile, targetFilePath, ctx.IncludeFolders); err != nil { - return i18n.WrapError(err) - } - - commands := []types.Command{ - &ReadFileAndStoreInContext{FileToRead: targetFilePath, Target: &ctx.SourceGccMinusE}, - &FilterSketchSource{Source: &ctx.SourceGccMinusE}, - &CTagsTargetFileSaver{Source: &ctx.SourceGccMinusE, TargetFileName: constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E}, - &CTagsRunner{}, - &PrototypesAdder{}, - &SketchSaver{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} diff --git a/container_build_options.go b/container_build_options.go deleted file mode 100644 index 67bd8917..00000000 --- a/container_build_options.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerBuildOptions struct{} - -func (s *ContainerBuildOptions) Run(ctx *types.Context) error { - commands := []types.Command{ - &CreateBuildOptionsMap{}, - &LoadPreviousBuildOptionsMap{}, - &WipeoutBuildPathIfBuildOptionsChanged{}, - &StoreBuildOptionsMap{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} diff --git a/container_find_includes.go b/container_find_includes.go deleted file mode 100644 index e84aaabb..00000000 --- a/container_find_includes.go +++ /dev/null @@ -1,409 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -/* - -Include detection - -This code is responsible for figuring out what libraries the current -sketch needs an populates both Context.ImportedLibraries with a list of -Library objects, and Context.IncludeFolders with a list of folders to -put on the include path. - -Simply put, every #include in a source file pulls in the library that -provides that source file. This includes source files in the selected -libraries, so libraries can recursively include other libraries as well. - -To implement this, the gcc preprocessor is used. A queue is created -containing, at first, the source files in the sketch. Each of the files -in the queue is processed in turn by running the preprocessor on it. If -the preprocessor provides an error, the output is examined to see if the -error is a missing header file originating from a #include directive. - -The filename is extracted from that #include directive, and a library is -found that provides it. If multiple libraries provide the same file, one -is slected (how this selection works is not described here, see the -ResolveLibrary function for that). The library selected in this way is -added to the include path through Context.IncludeFolders and the list of -libraries to include in the link through Context.ImportedLibraries. - -Furthermore, all of the library source files are added to the queue, to -be processed as well. When the preprocessor completes without showing an -#include error, processing of the file is complete and it advances to -the next. When no library can be found for a included filename, an error -is shown and the process is aborted. - -Caching - -Since this process is fairly slow (requiring at least one invocation of -the preprocessor per source file), its results are cached. - -Just caching the complete result (i.e. the resulting list of imported -libraries) seems obvious, but such a cache is hard to invalidate. Making -a list of all the source and header files used to create the list and -check if any of them changed is probably feasible, but this would also -require caching the full list of libraries to invalidate the cache when -the include to library resolution might have a different result. Another -downside of a complete cache is that any changes requires re-running -everything, even if no includes were actually changed. - -Instead, caching happens by keeping a sort of "journal" of the steps in -the include detection, essentially tracing each file processed and each -include path entry added. The cache is used by retracing these steps: -The include detection process is executed normally, except that instead -of running the preprocessor, the include filenames are (when possible) -read from the cache. Then, the include file to library resolution is -again executed normally. The results are checked against the cache and -as long as the results match, the cache is considered valid. - -When a source file (or any of the files it includes, as indicated by the -.d file) is changed, the preprocessor is executed as normal for the -file, ignoring any includes from the cache. This does not, however, -invalidate the cache: If the results from the preprocessor match the -entries in the cache, the cache remains valid and can again be used for -the next (unchanged) file. - -The cache file uses the JSON format and contains a list of entries. Each -entry represents a discovered library and contains: - - Sourcefile: The source file that the include was found in - - Include: The included filename found - - Includepath: The addition to the include path - -There are also some special entries: - - When adding the initial include path entries, such as for the core - and variant paths. These are not discovered, so the Sourcefile and - Include fields will be empty. - - When a file contains no (more) missing includes, an entry with an - empty Include and IncludePath is generated. - -*/ - -package builder - -import ( - "encoding/json" - "os" - "os/exec" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/arduino-cli/arduino/libraries" - "github.com/arduino/go-paths-helper" - - "github.com/go-errors/errors" -) - -type ContainerFindIncludes struct{} - -func (s *ContainerFindIncludes) Run(ctx *types.Context) error { - cachePath := ctx.BuildPath.Join(constants.FILE_INCLUDES_CACHE) - cache := readCache(cachePath) - - appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_CORE_PATH)) - if ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH) != "" { - appendIncludeFolder(ctx, cache, nil, "", ctx.BuildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH)) - } - - sketch := ctx.Sketch - mergedfile, err := types.MakeSourceFile(ctx, sketch, paths.New(sketch.MainFile.Name.Base()+".cpp")) - if err != nil { - return i18n.WrapError(err) - } - ctx.CollectedSourceFiles.Push(mergedfile) - - sourceFilePaths := ctx.CollectedSourceFiles - queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, ctx.SketchBuildPath, false /* recurse */) - srcSubfolderPath := ctx.SketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) - if srcSubfolderPath.IsDir() { - queueSourceFilesFromFolder(ctx, sourceFilePaths, sketch, srcSubfolderPath, true /* recurse */) - } - - for !sourceFilePaths.Empty() { - err := findIncludesUntilDone(ctx, cache, sourceFilePaths.Pop()) - if err != nil { - cachePath.Remove() - return i18n.WrapError(err) - } - } - - // Finalize the cache - cache.ExpectEnd() - err = writeCache(cache, cachePath) - if err != nil { - return i18n.WrapError(err) - } - - err = runCommand(ctx, &FailIfImportedLibraryIsWrong{}) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -// Append the given folder to the include path and match or append it to -// the cache. sourceFilePath and include indicate the source of this -// include (e.g. what #include line in what file it was resolved from) -// and should be the empty string for the default include folders, like -// the core or variant. -func appendIncludeFolder(ctx *types.Context, cache *includeCache, sourceFilePath *paths.Path, include string, folder *paths.Path) { - ctx.IncludeFolders = append(ctx.IncludeFolders, folder) - cache.ExpectEntry(sourceFilePath, include, folder) -} - -func runCommand(ctx *types.Context, command types.Command) error { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - return nil -} - -type includeCacheEntry struct { - Sourcefile *paths.Path - Include string - Includepath *paths.Path -} - -type includeCache struct { - // Are the cache contents valid so far? - valid bool - // Index into entries of the next entry to be processed. Unused - // when the cache is invalid. - next int - entries []includeCacheEntry -} - -// Return the next cache entry. Should only be called when the cache is -// valid and a next entry is available (the latter can be checked with -// ExpectFile). Does not advance the cache. -func (cache *includeCache) Next() includeCacheEntry { - return cache.entries[cache.next] -} - -// Check that the next cache entry is about the given file. If it is -// not, or no entry is available, the cache is invalidated. Does not -// advance the cache. -func (cache *includeCache) ExpectFile(sourcefile *paths.Path) { - if cache.valid && (cache.next >= len(cache.entries) || !cache.Next().Sourcefile.EqualsTo(sourcefile)) { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } -} - -// Check that the next entry matches the given values. If so, advance -// the cache. If not, the cache is invalidated. If the cache is -// invalidated, or was already invalid, an entry with the given values -// is appended. -func (cache *includeCache) ExpectEntry(sourcefile *paths.Path, include string, librarypath *paths.Path) { - entry := includeCacheEntry{Sourcefile: sourcefile, Include: include, Includepath: librarypath} - if cache.valid { - if cache.next < len(cache.entries) && cache.Next() == entry { - cache.next++ - } else { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } - } - - if !cache.valid { - cache.entries = append(cache.entries, entry) - } -} - -// Check that the cache is completely consumed. If not, the cache is -// invalidated. -func (cache *includeCache) ExpectEnd() { - if cache.valid && cache.next < len(cache.entries) { - cache.valid = false - cache.entries = cache.entries[:cache.next] - } -} - -// Read the cache from the given file -func readCache(path *paths.Path) *includeCache { - bytes, err := path.ReadFile() - if err != nil { - // Return an empty, invalid cache - return &includeCache{} - } - result := &includeCache{} - err = json.Unmarshal(bytes, &result.entries) - if err != nil { - // Return an empty, invalid cache - return &includeCache{} - } - result.valid = true - return result -} - -// Write the given cache to the given file if it is invalidated. If the -// cache is still valid, just update the timestamps of the file. -func writeCache(cache *includeCache, path *paths.Path) error { - // If the cache was still valid all the way, just touch its file - // (in case any source file changed without influencing the - // includes). If it was invalidated, overwrite the cache with - // the new contents. - if cache.valid { - path.Chtimes(time.Now(), time.Now()) - } else { - bytes, err := json.MarshalIndent(cache.entries, "", " ") - if err != nil { - return i18n.WrapError(err) - } - err = path.WriteFile(bytes) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func findIncludesUntilDone(ctx *types.Context, cache *includeCache, sourceFile types.SourceFile) error { - sourcePath := sourceFile.SourcePath(ctx) - targetFilePath := paths.NullPath() - depPath := sourceFile.DepfilePath(ctx) - objPath := sourceFile.ObjectPath(ctx) - - // TODO: This should perhaps also compare against the - // include.cache file timestamp. Now, it only checks if the file - // changed after the object file was generated, but if it - // changed between generating the cache and the object file, - // this could show the file as unchanged when it really is - // changed. Changing files during a build isn't really - // supported, but any problems from it should at least be - // resolved when doing another build, which is not currently the - // case. - // TODO: This reads the dependency file, but the actual building - // does it again. Should the result be somehow cached? Perhaps - // remove the object file if it is found to be stale? - unchanged, err := builder_utils.ObjFileIsUpToDate(ctx, sourcePath, objPath, depPath) - if err != nil { - return i18n.WrapError(err) - } - - first := true - for { - var include string - cache.ExpectFile(sourcePath) - - includes := ctx.IncludeFolders - if library, ok := sourceFile.Origin.(*libraries.Library); ok && library.UtilityDir != nil { - includes = append(includes, library.UtilityDir) - } - var preproc_err error - var preproc_stderr []byte - if unchanged && cache.valid { - include = cache.Next().Include - if first && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CACHED_INCLUDES, sourcePath) - } - } else { - preproc_stderr, preproc_err = GCCPreprocRunnerForDiscoveringIncludes(ctx, sourcePath, targetFilePath, includes) - // Unwrap error and see if it is an ExitError. - _, is_exit_error := i18n.UnwrapError(preproc_err).(*exec.ExitError) - if preproc_err == nil { - // Preprocessor successful, done - include = "" - } else if !is_exit_error || preproc_stderr == nil { - // Ignore ExitErrors (e.g. gcc returning - // non-zero status), but bail out on - // other errors - return i18n.WrapError(preproc_err) - } else { - include = IncludesFinderWithRegExp(ctx, string(preproc_stderr)) - if include == "" && ctx.Verbose { - ctx.GetLogger().Println(constants.LOG_LEVEL_DEBUG, constants.MSG_FIND_INCLUDES_FAILED, sourcePath) - } - } - } - - if include == "" { - // No missing includes found, we're done - cache.ExpectEntry(sourcePath, "", nil) - return nil - } - - library := ResolveLibrary(ctx, include) - if library == nil { - // Library could not be resolved, show error - // err := runCommand(ctx, &GCCPreprocRunner{SourceFilePath: sourcePath, TargetFileName: paths.New(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E), Includes: includes}) - // return i18n.WrapError(err) - if preproc_err == nil || preproc_stderr == nil { - // Filename came from cache, so run preprocessor to obtain error to show - preproc_stderr, preproc_err = GCCPreprocRunnerForDiscoveringIncludes(ctx, sourcePath, targetFilePath, includes) - if preproc_err == nil { - // If there is a missing #include in the cache, but running - // gcc does not reproduce that, there is something wrong. - // Returning an error here will cause the cache to be - // deleted, so hopefully the next compilation will succeed. - return errors.New("Internal error in cache") - } - } - os.Stderr.Write(preproc_stderr) - return i18n.WrapError(preproc_err) - } - - // Add this library to the list of libraries, the - // include path and queue its source files for further - // include scanning - ctx.ImportedLibraries = append(ctx.ImportedLibraries, library) - appendIncludeFolder(ctx, cache, sourcePath, include, library.SourceDir) - sourceDirs := library.SourceDirs() - for _, sourceDir := range sourceDirs { - queueSourceFilesFromFolder(ctx, ctx.CollectedSourceFiles, library, sourceDir.Dir, sourceDir.Recurse) - } - first = false - } -} - -func queueSourceFilesFromFolder(ctx *types.Context, queue *types.UniqueSourceFileQueue, origin interface{}, folder *paths.Path, recurse bool) error { - extensions := func(ext string) bool { return ADDITIONAL_FILE_VALID_EXTENSIONS_NO_HEADERS[ext] } - - filePaths := []string{} - err := utils.FindFilesInFolder(&filePaths, folder.String(), extensions, recurse) - if err != nil { - return i18n.WrapError(err) - } - - for _, filePath := range filePaths { - sourceFile, err := types.MakeSourceFile(ctx, origin, paths.New(filePath)) - if err != nil { - return i18n.WrapError(err) - } - queue.Push(sourceFile) - } - - return nil -} diff --git a/container_merge_copy_sketch_files.go b/container_merge_copy_sketch_files.go deleted file mode 100644 index e84f29ba..00000000 --- a/container_merge_copy_sketch_files.go +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerMergeCopySketchFiles struct{} - -func (s *ContainerMergeCopySketchFiles) Run(ctx *types.Context) error { - commands := []types.Command{ - &SketchSourceMerger{}, - &SketchSaver{}, - &AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil - -} diff --git a/container_setup.go b/container_setup.go deleted file mode 100644 index d6108fdd..00000000 --- a/container_setup.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type ContainerSetupHardwareToolsLibsSketchAndProps struct{} - -func (s *ContainerSetupHardwareToolsLibsSketchAndProps) Run(ctx *types.Context) error { - commands := []types.Command{ - &AddAdditionalEntriesToContext{}, - &FailIfBuildPathEqualsSketchPath{}, - &HardwareLoader{}, - &PlatformKeysRewriteLoader{}, - &RewriteHardwareKeys{}, - &TargetBoardResolver{}, - &ToolsLoader{}, - &AddBuildBoardPropertyIfMissing{}, - &LibrariesLoader{}, - &SketchLoader{}, - &SetupBuildProperties{}, - &LoadVIDPIDSpecificProperties{}, - &SetCustomBuildProperties{}, - &AddMissingBuildPropertiesFromParentPlatformTxtFiles{}, - } - - ctx.Progress.Steps = ctx.Progress.Steps / float64(len(commands)) - - for _, command := range commands { - builder_utils.PrintProgressIfProgressEnabledAndMachineLogger(ctx) - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} diff --git a/create_build_options_map.go b/create_build_options_map.go deleted file mode 100644 index f32019c3..00000000 --- a/create_build_options_map.go +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "encoding/json" - - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type CreateBuildOptionsMap struct{} - -func (s *CreateBuildOptionsMap) Run(ctx *types.Context) error { - buildOptions := ctx.ExtractBuildOptions() - bytes, err := json.MarshalIndent(buildOptions, "", " ") - if err != nil { - return i18n.WrapError(err) - } - - ctx.BuildOptionsJson = string(bytes) - - return nil -} diff --git a/create_cmake_rule.go b/create_cmake_rule.go deleted file mode 100644 index e3dc3e49..00000000 --- a/create_cmake_rule.go +++ /dev/null @@ -1,266 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "os" - "path/filepath" - "strings" - - properties "github.com/arduino/go-properties-orderedmap" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -var VALID_EXPORT_EXTENSIONS = map[string]bool{".h": true, ".c": true, ".hpp": true, ".hh": true, ".cpp": true, ".s": true, ".a": true, ".properties": true} -var DOTHEXTENSION = map[string]bool{".h": true, ".hh": true, ".hpp": true} -var DOTAEXTENSION = map[string]bool{".a": true} - -type ExportProjectCMake struct { - // Was there an error while compiling the sketch? - SketchError bool -} - -func (s *ExportProjectCMake) Run(ctx *types.Context) error { - //verbose := ctx.Verbose - logger := ctx.GetLogger() - - if s.SketchError || !canExportCmakeProject(ctx) { - return nil - } - - // Create new cmake subFolder - clean if the folder is already there - cmakeFolder := ctx.BuildPath.Join("_cmake") - if _, err := cmakeFolder.Stat(); err == nil { - cmakeFolder.RemoveAll() - } - cmakeFolder.MkdirAll() - - // Create lib and build subfolders - libBaseFolder := cmakeFolder.Join("lib") - libBaseFolder.MkdirAll() - buildBaseFolder := cmakeFolder.Join("build") - buildBaseFolder.MkdirAll() - - // Create core subfolder path (don't create it yet) - coreFolder := cmakeFolder.Join("core") - cmakeFile := cmakeFolder.Join("CMakeLists.txt") - - dynamicLibsFromPkgConfig := map[string]bool{} - extensions := func(ext string) bool { return VALID_EXPORT_EXTENSIONS[ext] } - staticLibsExtensions := func(ext string) bool { return DOTAEXTENSION[ext] } - for _, library := range ctx.ImportedLibraries { - // Copy used libraries in the correct folder - libDir := libBaseFolder.Join(library.Name) - mcu := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) - utils.CopyDir(library.InstallDir.String(), libDir.String(), extensions) - - // Read cmake options if available - isStaticLib := true - if cmakeOptions, err := properties.LoadFromPath(libDir.Join("src", mcu, "arduino_builder.properties")); err == nil { - // If the library can be linked dynamically do not copy the library folder - if pkgs, ok := cmakeOptions.GetOk("cmake.pkg_config"); ok { - isStaticLib = false - for _, pkg := range strings.Split(pkgs, " ") { - dynamicLibsFromPkgConfig[pkg] = true - } - } - } - - // Remove examples folder - if _, err := libBaseFolder.Join("examples").Stat(); err == nil { - libDir.Join("examples").RemoveAll() - } - - // Remove stray folders contining incompatible or not needed libraries archives - var files []string - utils.FindFilesInFolder(&files, libDir.Join("src").String(), staticLibsExtensions, true) - for _, file := range files { - staticLibDir := filepath.Dir(file) - if !isStaticLib || !strings.Contains(staticLibDir, mcu) { - os.RemoveAll(staticLibDir) - } - } - } - - // Copy core + variant in use + preprocessed sketch in the correct folders - err := utils.CopyDir(ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_CORE_PATH), coreFolder.String(), extensions) - if err != nil { - fmt.Println(err) - } - err = utils.CopyDir(ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH), coreFolder.Join("variant").String(), extensions) - if err != nil { - fmt.Println(err) - } - - // Use old ctags method to generate export file - commands := []types.Command{ - //&ContainerMergeCopySketchFiles{}, - &ContainerAddPrototypes{}, - //&FilterSketchSource{Source: &ctx.Source, RemoveLineMarkers: true}, - //&SketchSaver{}, - } - - for _, command := range commands { - command.Run(ctx) - } - - err = utils.CopyDir(ctx.SketchBuildPath.String(), cmakeFolder.Join("sketch").String(), extensions) - if err != nil { - fmt.Println(err) - } - - // Extract CFLAGS, CPPFLAGS and LDFLAGS - var defines []string - var linkerflags []string - 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) - - // Extract folders with .h in them for adding in include list - var headerFiles []string - isHeader := func(ext string) bool { return DOTHEXTENSION[ext] } - utils.FindFilesInFolder(&headerFiles, cmakeFolder.String(), isHeader, true) - foldersContainingDotH := findUniqueFoldersRelative(headerFiles, cmakeFolder.String()) - - // Extract folders with .a in them for adding in static libs paths list - var staticLibs []string - utils.FindFilesInFolder(&staticLibs, cmakeFolder.String(), staticLibsExtensions, true) - - // Generate the CMakeLists global file - - projectName := strings.TrimSuffix(ctx.Sketch.MainFile.Name.Base(), ctx.Sketch.MainFile.Name.Ext()) - - cmakelist := "cmake_minimum_required(VERSION 3.5.0)\n" - cmakelist += "INCLUDE(FindPkgConfig)\n" - cmakelist += "project (" + projectName + " C CXX)\n" - cmakelist += "add_definitions (" + strings.Join(defines, " ") + " " + strings.Join(linkerflags, " ") + ")\n" - cmakelist += "include_directories (" + foldersContainingDotH + ")\n" - - // Make link directories relative - // We can totally discard them since they mostly are outside the core folder - // If they are inside the core they are not getting copied :) - var relLinkDirectories []string - for _, dir := range linkDirectories { - if strings.Contains(dir, cmakeFolder.String()) { - relLinkDirectories = append(relLinkDirectories, strings.TrimPrefix(dir, cmakeFolder.String())) - } - } - - // Add SO_PATHS option for libraries not getting found by pkg_config - cmakelist += "set(EXTRA_LIBS_DIRS \"\" CACHE STRING \"Additional paths for dynamic libraries\")\n" - - linkGroup := "" - for _, lib := range dynamicLibsFromGccMinusL { - // Dynamic libraries should be discovered by pkg_config - cmakelist += "pkg_search_module (" + strings.ToUpper(lib) + " " + lib + ")\n" - relLinkDirectories = append(relLinkDirectories, "${"+strings.ToUpper(lib)+"_LIBRARY_DIRS}") - linkGroup += " " + lib - } - for lib := range dynamicLibsFromPkgConfig { - cmakelist += "pkg_search_module (" + strings.ToUpper(lib) + " " + lib + ")\n" - relLinkDirectories = append(relLinkDirectories, "${"+strings.ToUpper(lib)+"_LIBRARY_DIRS}") - linkGroup += " ${" + strings.ToUpper(lib) + "_LIBRARIES}" - } - cmakelist += "link_directories (" + strings.Join(relLinkDirectories, " ") + " ${EXTRA_LIBS_DIRS})\n" - for _, staticLib := range staticLibs { - // Static libraries are fully configured - lib := filepath.Base(staticLib) - lib = strings.TrimPrefix(lib, "lib") - lib = strings.TrimSuffix(lib, ".a") - if !utils.SliceContains(dynamicLibsFromGccMinusL, lib) { - linkGroup += " " + lib - cmakelist += "add_library (" + lib + " STATIC IMPORTED)\n" - location := strings.TrimPrefix(staticLib, cmakeFolder.String()) - cmakelist += "set_property(TARGET " + lib + " PROPERTY IMPORTED_LOCATION " + "${PROJECT_SOURCE_DIR}" + location + " )\n" - } - } - - // Include source files - // TODO: remove .cpp and .h from libraries example folders - cmakelist += "file (GLOB_RECURSE SOURCES core/*.c* lib/*.c* sketch/*.c*)\n" - - // Compile and link project - cmakelist += "add_executable (" + projectName + " ${SOURCES} ${SOURCES_LIBS})\n" - cmakelist += "target_link_libraries( " + projectName + " -Wl,--as-needed -Wl,--start-group " + linkGroup + " -Wl,--end-group)\n" - - cmakeFile.WriteFile([]byte(cmakelist)) - - return nil -} - -func canExportCmakeProject(ctx *types.Context) bool { - return ctx.BuildProperties.Get("compiler.export_cmake") != "" -} - -func extractCompileFlags(ctx *types.Context, receipe string, defines, dynamicLibs, linkerflags, linkDirectories *[]string, logger i18n.Logger) { - command, _ := builder_utils.PrepareCommandForRecipe(ctx, ctx.BuildProperties, receipe, true) - - for _, arg := range command.Args { - if strings.HasPrefix(arg, "-D") { - *defines = utils.AppendIfNotPresent(*defines, arg) - continue - } - if strings.HasPrefix(arg, "-l") { - *dynamicLibs = utils.AppendIfNotPresent(*dynamicLibs, arg[2:]) - continue - } - if strings.HasPrefix(arg, "-L") { - *linkDirectories = utils.AppendIfNotPresent(*linkDirectories, arg[2:]) - continue - } - if strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "-I") && !strings.HasPrefix(arg, "-o") { - // HACK : from linkerflags remove MMD (no cache is produced) - if !strings.HasPrefix(arg, "-MMD") { - *linkerflags = utils.AppendIfNotPresent(*linkerflags, arg) - } - } - } -} - -func findUniqueFoldersRelative(slice []string, base string) string { - var out []string - for _, element := range slice { - path := filepath.Dir(element) - path = strings.TrimPrefix(path, base+"/") - if !utils.SliceContains(out, path) { - out = append(out, path) - } - } - return strings.Join(out, " ") -} diff --git a/ctags/ctags_has_issues.go b/ctags/ctags_has_issues.go deleted file mode 100644 index f61ab70a..00000000 --- a/ctags/ctags_has_issues.go +++ /dev/null @@ -1,310 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "bufio" - "os" - "strings" - - "github.com/arduino/arduino-builder/types" -) - -func (p *CTagsParser) FixCLinkageTagsDeclarations(tags []*types.CTag) { - - linesMap := p.FindCLinkageLines(tags) - for i, _ := range tags { - - if sliceContainsInt(linesMap[tags[i].Filename], tags[i].Line) && - !strings.Contains(tags[i].PrototypeModifiers, EXTERN) { - tags[i].PrototypeModifiers = tags[i].PrototypeModifiers + " " + EXTERN - } - } -} - -func sliceContainsInt(s []int, e int) bool { - for _, a := range s { - if a == e { - return true - } - } - return false -} - -func (p *CTagsParser) prototypeAndCodeDontMatch(tag *types.CTag) bool { - if tag.SkipMe { - return true - } - - code := removeSpacesAndTabs(tag.Code) - - if strings.Index(code, ")") == -1 { - // Add to code non-whitespace non-comments tokens until we find a closing round bracket - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - line := 1 - - // skip lines until we get to the start of this tag - for scanner.Scan() && line < tag.Line { - line++ - } - - // read up to 10 lines in search of a closing paren - multilinecomment := false - temp := "" - - code, multilinecomment = removeComments(scanner.Text(), multilinecomment) - for scanner.Scan() && line < (tag.Line+10) && strings.Index(temp, ")") == -1 { - temp, multilinecomment = removeComments(scanner.Text(), multilinecomment) - code += temp - } - } - } - - code = removeSpacesAndTabs(code) - - prototype := removeSpacesAndTabs(tag.Prototype) - prototype = removeTralingSemicolon(prototype) - - // Prototype matches exactly with the code? - ret := strings.Index(code, prototype) - - if ret == -1 { - // If the definition is multiline ctags uses the function name as line number - // Try to match functions in the form - // void - // foo() {} - - // Add to code n non-whitespace non-comments tokens before the code line - - code = removeEverythingAfterClosingRoundBracket(code) - // Get how many characters are "missing" - n := strings.Index(prototype, code) - line := 0 - // Add these characters to "code" string - code, line = getFunctionProtoWithNPreviousCharacters(tag, code, n) - // Check again for perfect matching - ret = strings.Index(code, prototype) - if ret != -1 { - tag.Line = line - } - } - - return ret == -1 -} - -func findTemplateMultiline(tag *types.CTag) string { - code, _ := getFunctionProtoUntilTemplateToken(tag, tag.Code) - return removeEverythingAfterClosingRoundBracket(code) -} - -func removeEverythingAfterClosingRoundBracket(s string) string { - n := strings.Index(s, ")") - return s[0 : n+1] -} - -func getFunctionProtoUntilTemplateToken(tag *types.CTag, code string) (string, int) { - - /* FIXME I'm ugly */ - line := 0 - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - multilinecomment := false - var textBuffer []string - - // buffer lines until we get to the start of this tag - for scanner.Scan() && line < (tag.Line-1) { - line++ - text := scanner.Text() - textBuffer = append(textBuffer, text) - } - - for line > 0 && !strings.Contains(code, TEMPLATE) { - - line = line - 1 - text := textBuffer[line] - - text, multilinecomment = removeComments(text, multilinecomment) - - code = text + code - } - } - return code, line -} - -func getFunctionProtoWithNPreviousCharacters(tag *types.CTag, code string, n int) (string, int) { - - /* FIXME I'm ugly */ - expectedPrototypeLen := len(code) + n - line := 0 - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - scanner := bufio.NewScanner(file) - multilinecomment := false - var textBuffer []string - - // buffer lines until we get to the start of this tag - for scanner.Scan() && line < (tag.Line-1) { - line++ - text := scanner.Text() - textBuffer = append(textBuffer, text) - } - - for line > 0 && len(code) < expectedPrototypeLen { - - line = line - 1 - text := textBuffer[line] - - text, multilinecomment = removeComments(text, multilinecomment) - - code = text + code - code = removeSpacesAndTabs(code) - } - } - return code, line -} - -func removeComments(text string, multilinecomment bool) (string, bool) { - // Remove C++ style comments - if strings.Index(text, "//") != -1 { - text = text[0:strings.Index(text, "//")] - } - - // Remove C style comments - if strings.Index(text, "*/") != -1 { - if strings.Index(text, "/*") != -1 { - // C style comments on the same line - text = text[0:strings.Index(text, "/*")] + text[strings.Index(text, "*/")+1:len(text)-1] - } else { - text = text[strings.Index(text, "*/")+1 : len(text)-1] - multilinecomment = true - } - } - - if multilinecomment { - if strings.Index(text, "/*") != -1 { - text = text[0:strings.Index(text, "/*")] - multilinecomment = false - } else { - text = "" - } - } - return text, multilinecomment -} - -/* This function scans the source files searching for "extern C" context - * It save the line numbers in a map filename -> {lines...} - */ -func (p *CTagsParser) FindCLinkageLines(tags []*types.CTag) map[string][]int { - - lines := make(map[string][]int) - - for _, tag := range tags { - - if lines[tag.Filename] != nil { - break - } - - file, err := os.Open(tag.Filename) - if err == nil { - defer file.Close() - - lines[tag.Filename] = append(lines[tag.Filename], -1) - - scanner := bufio.NewScanner(file) - - // we can't remove the comments otherwise the line number will be wrong - // there are three cases: - // 1 - extern "C" void foo() - // 2 - extern "C" { - // void foo(); - // void bar(); - // } - // 3 - extern "C" - // { - // void foo(); - // void bar(); - // } - // case 1 and 2 can be simply recognized with string matching and indent level count - // case 3 needs specia attention: if the line ONLY contains `extern "C"` string, don't bail out on indent level = 0 - - inScope := false - enteringScope := false - indentLevels := 0 - line := 0 - - externCDecl := removeSpacesAndTabs(EXTERN) - - for scanner.Scan() { - line++ - str := removeSpacesAndTabs(scanner.Text()) - - if len(str) == 0 { - continue - } - - // check if we are on the first non empty line after externCDecl in case 3 - if enteringScope == true { - enteringScope = false - } - - // check if the line contains externCDecl - if strings.Contains(str, externCDecl) { - inScope = true - if len(str) == len(externCDecl) { - // case 3 - enteringScope = true - } - } - if inScope == true { - lines[tag.Filename] = append(lines[tag.Filename], line) - } - indentLevels += strings.Count(str, "{") - strings.Count(str, "}") - - // Bail out if indentLevel is zero and we are not in case 3 - if indentLevels == 0 && enteringScope == false { - inScope = false - } - } - } - - } - return lines -} diff --git a/ctags/ctags_parser.go b/ctags/ctags_parser.go deleted file mode 100644 index 7bcc4c6c..00000000 --- a/ctags/ctags_parser.go +++ /dev/null @@ -1,254 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "strconv" - "strings" - - "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder/types" -) - -const KIND_PROTOTYPE = "prototype" -const KIND_FUNCTION = "function" - -//const KIND_PROTOTYPE_MODIFIERS = "prototype_modifiers" - -const TEMPLATE = "template" -const STATIC = "static" -const EXTERN = "extern \"C\"" - -var KNOWN_TAG_KINDS = map[string]bool{ - "prototype": true, - "function": true, -} - -type CTagsParser struct { - tags []*types.CTag - mainFile *paths.Path -} - -func (p *CTagsParser) Parse(ctagsOutput string, mainFile *paths.Path) []*types.CTag { - rows := strings.Split(ctagsOutput, "\n") - rows = removeEmpty(rows) - - p.mainFile = mainFile - - for _, row := range rows { - p.tags = append(p.tags, parseTag(row)) - } - - p.skipTagsWhere(tagIsUnknown) - p.skipTagsWhere(tagIsUnhandled) - p.addPrototypes() - p.removeDefinedProtypes() - p.skipDuplicates() - p.skipTagsWhere(p.prototypeAndCodeDontMatch) - - return p.tags -} - -func (p *CTagsParser) addPrototypes() { - for _, tag := range p.tags { - if !tag.SkipMe { - addPrototype(tag) - } - } -} - -func addPrototype(tag *types.CTag) { - if strings.Index(tag.Prototype, TEMPLATE) == 0 { - if strings.Index(tag.Code, TEMPLATE) == 0 { - code := tag.Code - if strings.Contains(code, "{") { - code = code[:strings.Index(code, "{")] - } else { - code = code[:strings.LastIndex(code, ")")+1] - } - tag.Prototype = code + ";" - } else { - //tag.Code is 99% multiline, recreate it - code := findTemplateMultiline(tag) - tag.Prototype = code + ";" - } - return - } - - tag.PrototypeModifiers = "" - if strings.Index(tag.Code, STATIC+" ") != -1 { - tag.PrototypeModifiers = tag.PrototypeModifiers + " " + STATIC - } - - // Extern "C" modifier is now added in FixCLinkageTagsDeclarations - - tag.PrototypeModifiers = strings.TrimSpace(tag.PrototypeModifiers) -} - -func (p *CTagsParser) removeDefinedProtypes() { - definedPrototypes := make(map[string]bool) - for _, tag := range p.tags { - if tag.Kind == KIND_PROTOTYPE { - definedPrototypes[tag.Prototype] = true - } - } - - for _, tag := range p.tags { - if definedPrototypes[tag.Prototype] { - //if ctx.DebugLevel >= 10 { - // ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_SKIPPING_TAG_ALREADY_DEFINED, tag.FunctionName) - //} - tag.SkipMe = true - } - } -} - -func (p *CTagsParser) skipDuplicates() { - definedPrototypes := make(map[string]bool) - - for _, tag := range p.tags { - if !definedPrototypes[tag.Prototype] && tag.SkipMe == false { - definedPrototypes[tag.Prototype] = true - } else { - tag.SkipMe = true - } - } -} - -type skipFuncType func(tag *types.CTag) bool - -func (p *CTagsParser) skipTagsWhere(skipFunc skipFuncType) { - for _, tag := range p.tags { - if !tag.SkipMe { - skip := skipFunc(tag) - //if skip && p.debugLevel >= 10 { - // ctx.GetLogger().Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_SKIPPING_TAG_WITH_REASON, tag.FunctionName, runtime.FuncForPC(reflect.ValueOf(skipFunc).Pointer()).Name()) - //} - tag.SkipMe = skip - } - } -} - -func removeTralingSemicolon(s string) string { - return s[0 : len(s)-1] -} - -func removeSpacesAndTabs(s string) string { - s = strings.Replace(s, " ", "", -1) - s = strings.Replace(s, "\t", "", -1) - return s -} - -func tagIsUnhandled(tag *types.CTag) bool { - return !isHandled(tag) -} - -func isHandled(tag *types.CTag) bool { - if tag.Class != "" { - return false - } - if tag.Struct != "" { - return false - } - if tag.Namespace != "" { - return false - } - return true -} - -func tagIsUnknown(tag *types.CTag) bool { - return !KNOWN_TAG_KINDS[tag.Kind] -} - -func parseTag(row string) *types.CTag { - tag := &types.CTag{} - parts := strings.Split(row, "\t") - - tag.FunctionName = parts[0] - // This unescapes any backslashes in the filename. These - // filenames that ctags outputs originate from the line markers - // in the source, as generated by gcc. gcc escapes both - // backslashes and double quotes, but ctags ignores any escaping - // and just cuts off the filename at the first double quote it - // sees. This means any backslashes are still escaped, and need - // to be unescape, and any quotes will just break the build. - tag.Filename = strings.Replace(parts[1], "\\\\", "\\", -1) - - parts = parts[2:] - - returntype := "" - for _, part := range parts { - if strings.Contains(part, ":") { - colon := strings.Index(part, ":") - field := part[:colon] - value := strings.TrimSpace(part[colon+1:]) - switch field { - case "kind": - tag.Kind = value - case "line": - val, _ := strconv.Atoi(value) - // TODO: Check err from strconv.Atoi - tag.Line = val - case "typeref": - tag.Typeref = value - case "signature": - tag.Signature = value - case "returntype": - returntype = value - case "class": - tag.Class = value - case "struct": - tag.Struct = value - case "namespace": - tag.Namespace = value - } - } - } - tag.Prototype = returntype + " " + tag.FunctionName + tag.Signature + ";" - - if strings.Contains(row, "/^") && strings.Contains(row, "$/;") { - tag.Code = row[strings.Index(row, "/^")+2 : strings.Index(row, "$/;")] - } - - return tag -} - -func removeEmpty(rows []string) []string { - var newRows []string - for _, row := range rows { - row = strings.TrimSpace(row) - if len(row) > 0 { - newRows = append(newRows, row) - } - } - - return newRows -} diff --git a/ctags/ctags_parser_test.go b/ctags/ctags_parser_test.go deleted file mode 100644 index 41f7ccd0..00000000 --- a/ctags/ctags_parser_test.go +++ /dev/null @@ -1,347 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "io/ioutil" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder/types" - - "github.com/stretchr/testify/require" -) - -func produceTags(t *testing.T, filename string) []*types.CTag { - bytes, err := ioutil.ReadFile(filepath.Join("test_data", filename)) - require.NoError(t, err) - - parser := CTagsParser{} - return parser.Parse(string(bytes), nil) -} - -func TestCTagsParserShouldListPrototypes(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListPrototypes.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "server", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "process", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "process", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "digitalCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "analogCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) - idx++ - require.Equal(t, "modeCommand", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", tags[idx].Filename) -} - -func TestCTagsParserShouldListTemplates(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListTemplates.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "minimum", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template T minimum (T a, T b);", tags[idx].Prototype) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void setup();", tags[idx].Prototype) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void loop();", tags[idx].Prototype) -} - -func TestCTagsParserShouldListTemplates2(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldListTemplates2.txt") - - require.Equal(t, 4, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "SRAM_writeAnything", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template int SRAM_writeAnything(int ee, const T& value);", tags[idx].Prototype) - idx++ - require.Equal(t, "SRAM_readAnything", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "template int SRAM_readAnything(int ee, T& value);", tags[idx].Prototype) -} - -func TestCTagsParserShouldDealWithClasses(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithClasses.txt") - - require.Equal(t, 2, len(tags)) - idx := 0 - require.Equal(t, "SleepCycle", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - idx++ - require.Equal(t, "SleepCycle", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealWithStructs(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithStructs.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "A_NEW_TYPE", tags[idx].FunctionName) - require.Equal(t, "struct", tags[idx].Kind) - idx++ - require.Equal(t, "foo", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - require.Equal(t, "struct:A_NEW_TYPE", tags[idx].Typeref) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "dostuff", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealWithMacros(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealWithMacros.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "DEBUG", tags[idx].FunctionName) - require.Equal(t, "macro", tags[idx].Kind) - idx++ - require.Equal(t, "DISABLED", tags[idx].FunctionName) - require.Equal(t, "macro", tags[idx].Kind) - idx++ - require.Equal(t, "hello", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "debug", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "disabledIsDefined", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "useMyType", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserShouldDealFunctionWithDifferentSignatures(t *testing.T) { - tags := produceTags(t, "TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - idx++ - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "getBytes", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserClassMembersAreFilteredOut(t *testing.T) { - tags := produceTags(t, "TestCTagsParserClassMembersAreFilteredOut.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "set_values", tags[idx].FunctionName) - require.Equal(t, "prototype", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "area", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "set_values", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Rectangle", tags[idx].Class) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserStructWithFunctions(t *testing.T) { - tags := produceTags(t, "TestCTagsParserStructWithFunctions.txt") - - require.Equal(t, 8, len(tags)) - idx := 0 - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "struct", tags[idx].Kind) - idx++ - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "sensorData", tags[idx].Struct) - idx++ - require.Equal(t, "sensorData", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "sensorData", tags[idx].Struct) - idx++ - require.Equal(t, "sensors", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "sensor1", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "sensor2", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserDefaultArguments(t *testing.T) { - tags := produceTags(t, "TestCTagsParserDefaultArguments.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "test", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void test(int x = 1);", tags[idx].Prototype) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserNamespace(t *testing.T) { - tags := produceTags(t, "TestCTagsParserNamespace.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "value", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "Test", tags[idx].Namespace) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserStatic(t *testing.T) { - tags := produceTags(t, "TestCTagsParserStatic.txt") - - require.Equal(t, 3, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "doStuff", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserFunctionPointer(t *testing.T) { - tags := produceTags(t, "TestCTagsParserFunctionPointer.txt") - - require.Equal(t, 4, len(tags)) - idx := 0 - require.Equal(t, "t1Callback", tags[idx].FunctionName) - require.Equal(t, "variable", tags[idx].Kind) - idx++ - require.Equal(t, "t1Callback", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) -} - -func TestCTagsParserFunctionPointers(t *testing.T) { - tags := produceTags(t, "TestCTagsParserFunctionPointers.txt") - - require.Equal(t, 5, len(tags)) - idx := 0 - require.Equal(t, "setup", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "loop", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "func", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - idx++ - require.Equal(t, "funcArr", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "int funcArr();", tags[idx].Prototype) - idx++ - require.Equal(t, "funcCombo", tags[idx].FunctionName) - require.Equal(t, "function", tags[idx].Kind) - require.Equal(t, "void funcCombo(void (*(&in)[5])(int));", tags[idx].Prototype) -} diff --git a/ctags/ctags_properties.go b/ctags/ctags_properties.go deleted file mode 100644 index 38f15ecf..00000000 --- a/ctags/ctags_properties.go +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015-2018 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import properties "github.com/arduino/go-properties-orderedmap" - -// CtagsProperties are the platform properties needed to run ctags -var CtagsProperties = properties.NewFromHashmap(map[string]string{ - // Ctags - "tools.ctags.path": "{runtime.tools.ctags.path}", - "tools.ctags.cmd.path": "{path}/ctags", - "tools.ctags.pattern": `"{cmd.path}" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "{source_file}"`, - - // additional entries - "tools.avrdude.path": "{runtime.tools.avrdude.path}", - - "preproc.macros.flags": "-w -x c++ -E -CC", - //"preproc.macros.compatibility_flags": `{build.mbed_api_include} {build.nRF51822_api_include} {build.ble_api_include} {compiler.libsam.c.flags} {compiler.arm.cmsis.path} {build.variant_system_include}`, - //"recipe.preproc.macros": `"{compiler.path}{compiler.cpp.cmd}" {compiler.cpreprocessor.flags} {compiler.cpp.flags} {preproc.macros.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {preproc.macros.compatibility_flags} {includes} "{source_file}" -o "{preprocessed_file_path}"`, -}) diff --git a/ctags/ctags_to_prototypes.go b/ctags/ctags_to_prototypes.go deleted file mode 100644 index 9e811ac1..00000000 --- a/ctags/ctags_to_prototypes.go +++ /dev/null @@ -1,120 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "strings" - - "github.com/arduino/arduino-builder/types" -) - -func (p *CTagsParser) GeneratePrototypes() ([]*types.Prototype, int) { - return p.toPrototypes(), p.findLineWhereToInsertPrototypes() -} - -func (p *CTagsParser) findLineWhereToInsertPrototypes() int { - firstFunctionLine := p.firstFunctionAtLine() - firstFunctionPointerAsArgument := p.firstFunctionPointerUsedAsArgument() - if firstFunctionLine != -1 && firstFunctionPointerAsArgument != -1 { - if firstFunctionLine < firstFunctionPointerAsArgument { - return firstFunctionLine - } else { - return firstFunctionPointerAsArgument - } - } else if firstFunctionLine != -1 { - return firstFunctionLine - } else if firstFunctionPointerAsArgument != -1 { - return firstFunctionPointerAsArgument - } else { - return 0 - } -} - -func (p *CTagsParser) firstFunctionPointerUsedAsArgument() int { - functionTags := p.collectFunctions() - for _, tag := range p.tags { - if functionNameUsedAsFunctionPointerIn(tag, functionTags) { - return tag.Line - } - } - return -1 -} - -func functionNameUsedAsFunctionPointerIn(tag *types.CTag, functionTags []*types.CTag) bool { - for _, functionTag := range functionTags { - if tag.Line != functionTag.Line && strings.Index(tag.Code, "&"+functionTag.FunctionName) != -1 { - return true - } - if tag.Line != functionTag.Line && strings.Index(strings.TrimSpace(tag.Code), "("+functionTag.FunctionName+")") != -1 { - return true - } - } - return false -} - -func (p *CTagsParser) collectFunctions() []*types.CTag { - functionTags := []*types.CTag{} - for _, tag := range p.tags { - if tag.Kind == KIND_FUNCTION && !tag.SkipMe { - functionTags = append(functionTags, tag) - } - } - return functionTags -} - -func (p *CTagsParser) firstFunctionAtLine() int { - for _, tag := range p.tags { - if !tagIsUnknown(tag) && isHandled(tag) && tag.Kind == KIND_FUNCTION && tag.Filename == p.mainFile.String() { - return tag.Line - } - } - return -1 -} - -func (p *CTagsParser) toPrototypes() []*types.Prototype { - prototypes := []*types.Prototype{} - for _, tag := range p.tags { - if strings.TrimSpace(tag.Prototype) == "" { - continue - } - if !tag.SkipMe { - prototype := &types.Prototype{ - FunctionName: tag.FunctionName, - File: tag.Filename, - Prototype: tag.Prototype, - Modifiers: tag.PrototypeModifiers, - Line: tag.Line, - //Fields: tag, - } - prototypes = append(prototypes, prototype) - } - } - return prototypes -} diff --git a/ctags/ctags_to_prototypes_test.go b/ctags/ctags_to_prototypes_test.go deleted file mode 100644 index 429f72ed..00000000 --- a/ctags/ctags_to_prototypes_test.go +++ /dev/null @@ -1,239 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package ctags - -import ( - "io/ioutil" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func producePrototypes(t *testing.T, filename string, mainFile string) ([]*types.Prototype, int) { - bytes, err := ioutil.ReadFile(filepath.Join("test_data", filename)) - require.NoError(t, err) - - parser := &CTagsParser{} - parser.Parse(string(bytes), paths.New(mainFile)) - return parser.GeneratePrototypes() -} - -func TestCTagsToPrototypesShouldListPrototypes(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListPrototypes.txt", "/tmp/sketch7210316334309249705.cpp") - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch7210316334309249705.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void digitalCommand(YunClient client);", prototypes[2].Prototype) - require.Equal(t, "void analogCommand(YunClient client);", prototypes[3].Prototype) - require.Equal(t, "void modeCommand(YunClient client);", prototypes[4].Prototype) - - require.Equal(t, 33, line) -} - -func TestCTagsToPrototypesShouldListTemplates(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListTemplates.txt", "/tmp/sketch8398023134925534708.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "template T minimum (T a, T b);", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch8398023134925534708.cpp", prototypes[0].File) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesShouldListTemplates2(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldListTemplates2.txt", "/tmp/sketch463160524247569568.cpp") - - require.Equal(t, 4, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch463160524247569568.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "template int SRAM_writeAnything(int ee, const T& value);", prototypes[2].Prototype) - require.Equal(t, "template int SRAM_readAnything(int ee, T& value);", prototypes[3].Prototype) - - require.Equal(t, 1, line) -} - -func TestCTagsToPrototypesShouldDealWithClasses(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithClasses.txt", "/tmp/sketch9043227824785312266.cpp") - - require.Equal(t, 0, len(prototypes)) - - require.Equal(t, 8, line) -} - -func TestCTagsToPrototypesShouldDealWithStructs(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithStructs.txt", "/tmp/sketch8930345717354294915.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch8930345717354294915.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void dostuff(A_NEW_TYPE * bar);", prototypes[2].Prototype) - - require.Equal(t, 9, line) -} - -func TestCTagsToPrototypesShouldDealWithMacros(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealWithMacros.txt", "/tmp/sketch5976699731718729500.cpp") - - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/sketch5976699731718729500.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void debug();", prototypes[2].Prototype) - require.Equal(t, "void disabledIsDefined();", prototypes[3].Prototype) - require.Equal(t, "int useMyType(MyType type);", prototypes[4].Prototype) - - require.Equal(t, 18, line) -} - -func TestCTagsToPrototypesShouldDealFunctionWithDifferentSignatures(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt", "/tmp/test260613593/preproc/ctags_target.cpp") - - require.Equal(t, 1, len(prototypes)) - require.Equal(t, "boolean getBytes( byte addr, int amount );", prototypes[0].Prototype) - require.Equal(t, "/tmp/test260613593/preproc/ctags_target.cpp", prototypes[0].File) - - require.Equal(t, 5031, line) -} - -func TestCTagsToPrototypesClassMembersAreFilteredOut(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserClassMembersAreFilteredOut.txt", "/tmp/test834438754/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test834438754/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 14, line) -} - -func TestCTagsToPrototypesStructWithFunctions(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserStructWithFunctions.txt", "/tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 16, line) -} - -func TestCTagsToPrototypesDefaultArguments(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserDefaultArguments.txt", "/tmp/test179252494/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void test(int x = 1);", prototypes[0].Prototype) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "/tmp/test179252494/preproc/ctags_target.cpp", prototypes[1].File) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesNamespace(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserNamespace.txt", "/tmp/test030883150/preproc/ctags_target.cpp") - - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test030883150/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 8, line) -} - -func TestCTagsToPrototypesStatic(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserStatic.txt", "/tmp/test542833488/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test542833488/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void doStuff();", prototypes[2].Prototype) - require.Equal(t, "static", prototypes[2].Modifiers) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointer(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointer.txt", "/tmp/test547238273/preproc/ctags_target.cpp") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void t1Callback();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test547238273/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void setup();", prototypes[1].Prototype) - require.Equal(t, "void loop();", prototypes[2].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointers(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointers.txt", "/tmp/test907446433/preproc/ctags_target.cpp") - require.Equal(t, 2, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test907446433/preproc/ctags_target.cpp", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 2, line) -} - -func TestCTagsToPrototypesFunctionPointersNoIndirect(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsParserFunctionPointersNoIndirect.txt", "/tmp/test547238273/preproc/bug_callback.ino") - require.Equal(t, 5, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "/tmp/test547238273/preproc/bug_callback.ino", prototypes[0].File) - require.Equal(t, "void loop();", prototypes[1].Prototype) - - require.Equal(t, 10, line) -} - -func TestCTagsRunnerSketchWithClassFunction(t *testing.T) { - prototypes, _ := producePrototypes(t, "TestCTagsRunnerSketchWithClassFunction.txt", "/home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino") - - require.Equal(t, 3, len(prototypes)) - require.Equal(t, "void setup();", prototypes[0].Prototype) - require.Equal(t, "void loop();", prototypes[1].Prototype) - require.Equal(t, "void asdf();", prototypes[2].Prototype) -} - -func TestCTagsRunnerSketchWithMultiFile(t *testing.T) { - prototypes, line := producePrototypes(t, "TestCTagsRunnerSketchWithMultifile.txt", "/tmp/apUNI8a/main.ino") - - require.Equal(t, 0, line) - require.Equal(t, "void A7105_Setup();", prototypes[0].Prototype) - require.Equal(t, "void A7105_Reset();", prototypes[1].Prototype) - require.Equal(t, "int A7105_calibrate_VCB(uint8_t channel);", prototypes[2].Prototype) -} diff --git a/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt b/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt deleted file mode 100644 index 12313597..00000000 --- a/ctags/test_data/TestCTagsParserClassMembersAreFilteredOut.txt +++ /dev/null @@ -1,6 +0,0 @@ -set_values /tmp/test834438754/preproc/ctags_target.cpp /^ void set_values (int,int);$/;" kind:prototype line:5 class:Rectangle signature:(int,int) returntype:void -area /tmp/test834438754/preproc/ctags_target.cpp /^ int area() {return width*height;}$/;" kind:function line:6 class:Rectangle signature:() returntype:int -set_values /tmp/test834438754/preproc/ctags_target.cpp /^void Rectangle::set_values (int x, int y) {$/;" kind:function line:9 class:Rectangle signature:(int x, int y) returntype:void -setup /tmp/test834438754/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:14 signature:() returntype:void -loop /tmp/test834438754/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:18 signature:() returntype:void - diff --git a/ctags/test_data/TestCTagsParserDefaultArguments.txt b/ctags/test_data/TestCTagsParserDefaultArguments.txt deleted file mode 100644 index 7735d974..00000000 --- a/ctags/test_data/TestCTagsParserDefaultArguments.txt +++ /dev/null @@ -1,3 +0,0 @@ -test /tmp/test179252494/preproc/ctags_target.cpp /^void test(int x = 1) {$/;" kind:function line:2 signature:(int x = 1) returntype:void -setup /tmp/test179252494/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:5 signature:() returntype:void -loop /tmp/test179252494/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:8 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointer.txt b/ctags/test_data/TestCTagsParserFunctionPointer.txt deleted file mode 100644 index b36c5928..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointer.txt +++ /dev/null @@ -1,4 +0,0 @@ -t1Callback /tmp/test547238273/preproc/ctags_target.cpp /^Task t1(&t1Callback);$/;" kind:variable line:2 -t1Callback /tmp/test547238273/preproc/ctags_target.cpp /^void t1Callback() {}$/;" kind:function line:3 signature:() returntype:void -setup /tmp/test547238273/preproc/ctags_target.cpp /^void setup() {}$/;" kind:function line:4 signature:() returntype:void -loop /tmp/test547238273/preproc/ctags_target.cpp /^void loop() {}$/;" kind:function line:5 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointers.txt b/ctags/test_data/TestCTagsParserFunctionPointers.txt deleted file mode 100644 index 0aa1e06a..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointers.txt +++ /dev/null @@ -1,5 +0,0 @@ -setup /tmp/test907446433/preproc/ctags_target.cpp /^void setup(){$/;" kind:function line:2 signature:() returntype:void -loop /tmp/test907446433/preproc/ctags_target.cpp /^void loop(){}$/;" kind:function line:5 signature:() returntype:void -func /tmp/test907446433/preproc/ctags_target.cpp /^void (*func())(){$/;" kind:function line:7 signature:() returntype:void -funcArr /tmp/test907446433/preproc/ctags_target.cpp /^int (&funcArr())[5]{$/;" kind:function line:11 signature:() returntype:int -funcCombo /tmp/test907446433/preproc/ctags_target.cpp /^void (*(&funcCombo(void (*(&in)[5])(int)))[5])(int){$/;" kind:function line:15 signature:(void (*(&in)[5])(int)) returntype:void diff --git a/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt b/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt deleted file mode 100644 index d32e2099..00000000 --- a/ctags/test_data/TestCTagsParserFunctionPointersNoIndirect.txt +++ /dev/null @@ -1,7 +0,0 @@ -BUG /tmp/test547238273/preproc/bug_callback.ino /^ public: BUG(void (*fn)(void)) {}$/;" kind:function line:6 class:BUG signature:(void (*fn)(void)) -b /tmp/test547238273/preproc/bug_callback.ino /^BUG b(makeItBreak); \/\/this will break$/;" kind:prototype line:10 signature:(makeItBreak)returntype:BUG -setup /tmp/test547238273/preproc/bug_callback.ino /^void setup() {$/;" kind:function line:12 signature:() returntype:void -loop /tmp/test547238273/preproc/bug_callback.ino /^void loop() {}$/;" kind:function line:16 signature:() returntype:void -makeItBreak /tmp/test547238273/preproc/bug_callback.ino /^void makeItBreak() {}$/;" kind:function line:18 signature:() returntype:void -caller /tmp/test547238273/preproc/bug_callback.ino /^void caller(int (*cc)(int ),int a) {$/;" kind:function line:20 signature:(int (*cc)(int ),int a) returntype:void -blub /tmp/test547238273/preproc/bug_callback.ino /^int blub(int a) {$/;" kind:function line:24 signature:(int a) returntype:int diff --git a/ctags/test_data/TestCTagsParserNamespace.txt b/ctags/test_data/TestCTagsParserNamespace.txt deleted file mode 100644 index 8a12c235..00000000 --- a/ctags/test_data/TestCTagsParserNamespace.txt +++ /dev/null @@ -1,4 +0,0 @@ -value /tmp/test030883150/preproc/ctags_target.cpp /^ int value() {$/;" kind:function line:3 namespace:Test signature:() returntype:int -setup /tmp/test030883150/preproc/ctags_target.cpp /^void setup() {}$/;" kind:function line:8 signature:() returntype:void -loop /tmp/test030883150/preproc/ctags_target.cpp /^void loop() {}$/;" kind:function line:9 signature:() returntype:void - diff --git a/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt b/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt deleted file mode 100644 index f052e995..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealFunctionWithDifferentSignatures.txt +++ /dev/null @@ -1,3 +0,0 @@ -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^ void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;$/;" kind:prototype line:4330 signature:(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const returntype:void -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address$/;" kind:function line:5031 signature:( byte addr, int amount ) returntype:boolean -getBytes /tmp/test260613593/preproc/ctags_target.cpp /^boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address$/;" kind:function line:214 signature:( byte addr, int amount ) returntype:boolean diff --git a/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt b/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt deleted file mode 100644 index 12317759..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithClasses.txt +++ /dev/null @@ -1,2 +0,0 @@ -SleepCycle /tmp/sketch9043227824785312266.cpp /^ SleepCycle( const char* name );$/;" kind:prototype line:4 signature:( const char* name ) -SleepCycle /tmp/sketch9043227824785312266.cpp /^ SleepCycle::SleepCycle( const char* name )$/;" kind:function line:8 signature:( const char* name ) diff --git a/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt b/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt deleted file mode 100644 index f972e00c..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithMacros.txt +++ /dev/null @@ -1,8 +0,0 @@ -DEBUG /tmp/sketch5976699731718729500.cpp 1;" kind:macro line:1 -DISABLED /tmp/sketch5976699731718729500.cpp 2;" kind:macro line:2 -hello /tmp/sketch5976699731718729500.cpp /^String hello = "world!";$/;" kind:variable line:16 -setup /tmp/sketch5976699731718729500.cpp /^void setup() {$/;" kind:function line:18 signature:() returntype:void -loop /tmp/sketch5976699731718729500.cpp /^void loop() {$/;" kind:function line:23 signature:() returntype:void -debug /tmp/sketch5976699731718729500.cpp /^void debug() {$/;" kind:function line:35 signature:() returntype:void -disabledIsDefined /tmp/sketch5976699731718729500.cpp /^void disabledIsDefined() {$/;" kind:function line:46 signature:() returntype:void -useMyType /tmp/sketch5976699731718729500.cpp /^int useMyType(MyType type) {$/;" kind:function line:50 signature:(MyType type) returntype:int diff --git a/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt b/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt deleted file mode 100644 index 240ed27b..00000000 --- a/ctags/test_data/TestCTagsParserShouldDealWithStructs.txt +++ /dev/null @@ -1,5 +0,0 @@ -A_NEW_TYPE /tmp/sketch8930345717354294915.cpp /^struct A_NEW_TYPE {$/;" kind:struct line:3 -foo /tmp/sketch8930345717354294915.cpp /^} foo;$/;" kind:variable line:7 typeref:struct:A_NEW_TYPE -setup /tmp/sketch8930345717354294915.cpp /^void setup() {$/;" kind:function line:9 signature:() returntype:void -loop /tmp/sketch8930345717354294915.cpp /^void loop() {$/;" kind:function line:13 signature:() returntype:void -dostuff /tmp/sketch8930345717354294915.cpp /^void dostuff (A_NEW_TYPE * bar)$/;" kind:function line:17 signature:(A_NEW_TYPE * bar) returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListPrototypes.txt b/ctags/test_data/TestCTagsParserShouldListPrototypes.txt deleted file mode 100644 index 4e678f51..00000000 --- a/ctags/test_data/TestCTagsParserShouldListPrototypes.txt +++ /dev/null @@ -1,8 +0,0 @@ -server /tmp/sketch7210316334309249705.cpp /^YunServer server;$/;" kind:variable line:31 -setup /tmp/sketch7210316334309249705.cpp /^void setup() {$/;" kind:function line:33 signature:() returntype:void -loop /tmp/sketch7210316334309249705.cpp /^void loop() {$/;" kind:function line:46 signature:() returntype:void -process /tmp/sketch7210316334309249705.cpp /^void process(YunClient client);$/;" kind:prototype line:61 signature:(YunClient client) returntype:void -process /tmp/sketch7210316334309249705.cpp /^void process(YunClient client) {$/;" kind:function line:62 signature:(YunClient client) returntype:void -digitalCommand /tmp/sketch7210316334309249705.cpp /^void digitalCommand(YunClient client) {$/;" kind:function line:82 signature:(YunClient client) returntype:void -analogCommand /tmp/sketch7210316334309249705.cpp /^void analogCommand(YunClient client) {$/;" kind:function line:110 signature:(YunClient client) returntype:void -modeCommand /tmp/sketch7210316334309249705.cpp /^void modeCommand(YunClient client) {$/;" kind:function line:151 signature:(YunClient client) returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListTemplates.txt b/ctags/test_data/TestCTagsParserShouldListTemplates.txt deleted file mode 100644 index 3281e49c..00000000 --- a/ctags/test_data/TestCTagsParserShouldListTemplates.txt +++ /dev/null @@ -1,3 +0,0 @@ -minimum /tmp/sketch8398023134925534708.cpp /^template T minimum (T a, T b) $/;" kind:function line:2 signature:(T a, T b) returntype:templateT -setup /tmp/sketch8398023134925534708.cpp /^void setup () $/;" kind:function line:9 signature:() returntype:void -loop /tmp/sketch8398023134925534708.cpp /^void loop () { }$/;" kind:function line:13 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserShouldListTemplates2.txt b/ctags/test_data/TestCTagsParserShouldListTemplates2.txt deleted file mode 100644 index c08ddba0..00000000 --- a/ctags/test_data/TestCTagsParserShouldListTemplates2.txt +++ /dev/null @@ -1,4 +0,0 @@ -setup /tmp/sketch463160524247569568.cpp /^void setup() {$/;" kind:function line:1 signature:() returntype:void -loop /tmp/sketch463160524247569568.cpp /^void loop() {$/;" kind:function line:6 signature:() returntype:void -SRAM_writeAnything /tmp/sketch463160524247569568.cpp /^template int SRAM_writeAnything(int ee, const T& value)$/;" kind:function line:11 signature:(int ee, const T& value) returntype:template int -SRAM_readAnything /tmp/sketch463160524247569568.cpp /^template int SRAM_readAnything(int ee, T& value)$/;" kind:function line:21 signature:(int ee, T& value) returntype:template int diff --git a/ctags/test_data/TestCTagsParserStatic.txt b/ctags/test_data/TestCTagsParserStatic.txt deleted file mode 100644 index ec1bdb14..00000000 --- a/ctags/test_data/TestCTagsParserStatic.txt +++ /dev/null @@ -1,3 +0,0 @@ -setup /tmp/test542833488/preproc/ctags_target.cpp /^void setup(){}$/;" kind:function line:2 signature:() returntype:void -loop /tmp/test542833488/preproc/ctags_target.cpp /^void loop(){}$/;" kind:function line:3 signature:() returntype:void -doStuff /tmp/test542833488/preproc/ctags_target.cpp /^static void doStuff() {}$/;" kind:function line:4 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsParserStructWithFunctions.txt b/ctags/test_data/TestCTagsParserStructWithFunctions.txt deleted file mode 100644 index 5519aec5..00000000 --- a/ctags/test_data/TestCTagsParserStructWithFunctions.txt +++ /dev/null @@ -1,8 +0,0 @@ -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^struct sensorData {$/;" kind:struct line:2 -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^ sensorData(int iStatus, float iTemp, float iMinTemp) : status(iStatus), temp(iTemp), minTemp(iMinTemp) {}$/;" kind:function line:3 struct:sensorData signature:(int iStatus, float iTemp, float iMinTemp) -sensorData /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^ sensorData() : status(-1), temp(1023.0), minTemp(1023.0) {}$/;" kind:function line:4 struct:sensorData signature:() -sensors /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensors[2];$/;" kind:variable line:10 -sensor1 /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensor1; \/\/(-1,1023.0,1023.0);$/;" kind:variable line:12 -sensor2 /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^sensorData sensor2; \/\/(-1,1023.0,1023.0);$/;" kind:variable line:13 -setup /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^void setup() {$/;" kind:function line:16 signature:() returntype:void -loop /tmp/build7315640391316178285.tmp/preproc/ctags_target.cpp /^void loop() {$/;" kind:function line:22 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt b/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt deleted file mode 100644 index 42f3b5ca..00000000 --- a/ctags/test_data/TestCTagsRunnerSketchWithClassFunction.txt +++ /dev/null @@ -1,4 +0,0 @@ -asdf /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^ void asdf() {}$/;" kind:function line:2 class:test signature:() returntype:void -setup /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void setup() {$/;" kind:function line:4 signature:() returntype:void -loop /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void loop() {}$/;" kind:function line:7 signature:() returntype:void -asdf /home/megabug/Workspace/arduino-builder/src/github.com/arduino/arduino-builder/test/sketch_class_function/sketch_class_function.ino /^void asdf() {}$/;" kind:function line:8 signature:() returntype:void diff --git a/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt b/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt deleted file mode 100644 index 626b8ef0..00000000 --- a/ctags/test_data/TestCTagsRunnerSketchWithMultifile.txt +++ /dev/null @@ -1,77 +0,0 @@ -allowed_ch /tmp/apUNI8a/a7105.ino /^const uint8_t allowed_ch[] = {0x14, 0x1e, 0x28, 0x32, 0x3c, 0x46, 0x50, 0x5a, 0x64, 0x6e, 0x78, 0x82};$/;" kind:variable line:21 -no_allowed_channels /tmp/apUNI8a/a7105.ino /^int no_allowed_channels = 12;$/;" kind:variable line:22 -A7105_Setup /tmp/apUNI8a/a7105.ino /^void A7105_Setup() {$/;" kind:function line:26 signature:() returntype:void -A7105_Reset /tmp/apUNI8a/a7105.ino /^void A7105_Reset()$/;" kind:function line:43 signature:() returntype:void -A7105_calibrate_IF /tmp/apUNI8a/a7105.ino /^int A7105_calibrate_IF() {$/;"kind:function line:52 signature:() returntype:int -A7105_calibrate_VCB /tmp/apUNI8a/a7105.ino /^int A7105_calibrate_VCB(uint8_t channel) {$/;" kind:function line:87 signature:(uint8_t channel) returntype:int -A7105_SetPower /tmp/apUNI8a/a7105.ino /^void A7105_SetPower(int power)$/;" kind:function line:120 signature:(int power) returntype:void -A7105_Strobe /tmp/apUNI8a/a7105.ino /^void A7105_Strobe(enum A7105_State state);$/;" kind:prototype line:176 signature:(enum A7105_State state) returntype:void -A7105_Strobe /tmp/apUNI8a/a7105.ino /^void A7105_Strobe(enum A7105_State state)$/;" kind:function line:179 signature:(enum A7105_State state) returntype:void -A7105_WriteReg /tmp/apUNI8a/a7105.ino /^void A7105_WriteReg(uint8_t address, uint8_t data)$/;" kind:function line:190 signature:(uint8_t address, uint8_t data) returntype:void -A7105_ReadReg /tmp/apUNI8a/a7105.ino /^uint8_t A7105_ReadReg(uint8_t address)$/;" kind:function line:197 signature:(uint8_t address) returntype:uint8_t -A7105_WriteData /tmp/apUNI8a/a7105.ino /^void A7105_WriteData(uint8_t *dpbuffer, uint8_t len, uint8_t channel)$/;" kind:function line:211 signature:(uint8_t *dpbuffer, uint8_t len, uint8_t channel) returntype:void -A7105_ReadData /tmp/apUNI8a/a7105.ino /^void A7105_ReadData(uint8_t *dpbuffer, uint8_t len)$/;" kind:function line:229 signature:(uint8_t *dpbuffer, uint8_t len) returntype:void -A7105_WriteID /tmp/apUNI8a/a7105.ino /^void A7105_WriteID(unsigned long id)$/;" kind:function line:247 signature:(unsigned long id) returntype:void -A7105_ReadID /tmp/apUNI8a/a7105.ino /^void A7105_ReadID()$/;" kind:function line:258 signature:() returntype:void -k13 /tmp/apUNI8a/a7105.ino /^unsigned char k13;$/;" kind:variable line:272 -make_test_packet /tmp/apUNI8a/a7105.ino /^void make_test_packet(uint8_t testpacket[]) {$/;" kind:function line:275 signature:(uint8_t testpacket[]) returntype:void -printpacket /tmp/apUNI8a/a7105.ino /^void printpacket(uint8_t packet[]) {$/;" kind:function line:295 signature:(uint8_t packet[]) returntype:void -A7105_shoutchannel /tmp/apUNI8a/a7105.ino /^void A7105_shoutchannel() {$/;" kind:function line:308 signature:() returntype:void -A7105_oneShout /tmp/apUNI8a/a7105.ino /^int A7105_oneShout() {$/;" kind:function line:337 signature:() returntype:int -A7105_oneShoutRAM /tmp/apUNI8a/a7105.ino /^int A7105_oneShoutRAM(unsigned char xState, unsigned char xType) {$/;" kind:function line:361 signature:(unsigned char xState, unsigned char xType) returntype:int -eavesdrop /tmp/apUNI8a/a7105.ino /^void eavesdrop() {$/;" kind:function line:391 signature:() returntype:void -A7105_findchannel /tmp/apUNI8a/a7105.ino /^uint8_t A7105_findchannel() {$/;" kind:function line:442 signature:() returntype:uint8_t -A7105_sniffchannel /tmp/apUNI8a/a7105.ino /^int A7105_sniffchannel() {$/;"kind:function line:464 signature:() returntype:int -A7105_sniffchannel /tmp/apUNI8a/a7105.ino /^void A7105_sniffchannel(uint8_t _channel) {$/;" kind:function line:484 signature:(uint8_t _channel) returntype:void -A7105_scanchannels /tmp/apUNI8a/a7105.ino /^void A7105_scanchannels(const uint8_t channels[]) {$/;" kind:function line:498 signature:(const uint8_t channels[]) returntype:void -Channels /tmp/apUNI8a/hubsan.ino /^volatile int16_t Channels[12];$/;" kind:variable line:6 -initialize /tmp/apUNI8a/hubsan.ino /^static void initialize() {$/;" kind:function line:8 signature:() returntype:void -hubsan_init /tmp/apUNI8a/hubsan.ino /^int hubsan_init()$/;" kind:function line:22 signature:() returntype:int -update_crc /tmp/apUNI8a/hubsan.ino /^static void update_crc()$/;" kind:function line:80 signature:() returntype:void -recdState /tmp/apUNI8a/main.ino /^unsigned char recdState, recdType;$/;"kind:variable line:5 -recdType /tmp/apUNI8a/main.ino /^unsigned char recdState, recdType;$/;"kind:variable line:5 -retries /tmp/apUNI8a/main.ino /^unsigned char retries;$/;" kind:variable line:6 -bwMap /tmp/apUNI8a/main.ino /^const unsigned char bwMap[4 \/* new cycle green yellow red blue (green) *\/] = {2, 6, 4, 1};$/;" kind:variable line:27 -bwButton /tmp/apUNI8a/main.ino /^unsigned char bwButton, bwCycle;$/;" kind:variable line:28 -bwCycle /tmp/apUNI8a/main.ino /^unsigned char bwButton, bwCycle;$/;" kind:variable line:28 -checkBW /tmp/apUNI8a/main.ino /^void checkBW(void); \/* watch button increment bwCycle *\/$/;" kind:prototype line:29 signature:(void) returntype:void -ledState /tmp/apUNI8a/main.ino /^unsigned char ledState;$/;" kind:variable line:31 -mySwitches /tmp/apUNI8a/main.ino /^unsigned char mySwitches;$/;" kind:variable line:32 -BWMODE /tmp/apUNI8a/main.ino /^unsigned char BWMODE, BLINKMODE;$/;" kind:variable line:34 -BLINKMODE /tmp/apUNI8a/main.ino /^unsigned char BWMODE, BLINKMODE;$/;" kind:variable line:34 -lightFSM /tmp/apUNI8a/main.ino /^void lightFSM(void);$/;" kind:prototype line:36 signature:(void) returntype:void -blinkLEDs /tmp/apUNI8a/main.ino /^void blinkLEDs(void);$/;" kind:prototype line:37 signature:(void) returntype:void -touchTimer /tmp/apUNI8a/main.ino /^unsigned touchTimer, lastTouch;$/;" kind:variable line:38 -lastTouch /tmp/apUNI8a/main.ino /^unsigned touchTimer, lastTouch;$/;" kind:variable line:38 -lightTimer /tmp/apUNI8a/main.ino /^unsigned char lightTimer;$/;" kind:variable line:40 -lamp /tmp/apUNI8a/main.ino /^unsigned int lamp;$/;" kind:variable line:45 -loops /tmp/apUNI8a/main.ino /^unsigned long loops;$/;" kind:variable line:46 -recFlag /tmp/apUNI8a/main.ino /^unsigned char recFlag; \/\/ have "we" asked for a packet?$/;" kind:variable line:48 -needAck /tmp/apUNI8a/main.ino /^unsigned char needAck;$/;" kind:variable line:49 -fsmFSM /tmp/apUNI8a/main.ino /^void fsmFSM(void);$/;" kind:prototype line:51 signature:(void) returntype:void -printFlag /tmp/apUNI8a/main.ino /^unsigned int printFlag;$/;" kind:variable line:52 -fsmTimer /tmp/apUNI8a/main.ino /^unsigned long fsmTimer;$/;" kind:variable line:53 -startval /tmp/apUNI8a/main.ino /^uint8_t startval, command;$/;" kind:variable line:57 -command /tmp/apUNI8a/main.ino /^uint8_t startval, command;$/;" kind:variable line:57 -iCnt /tmp/apUNI8a/main.ino /^int iCnt;$/;" kind:variable line:58 -myMessage /tmp/apUNI8a/main.ino /^char myMessage[8];$/;" kind:variable line:60 -ackMessage /tmp/apUNI8a/main.ino /^char ackMessage[8];$/;" kind:variable line:61 -setup /tmp/apUNI8a/main.ino /^void setup() {$/;" kind:function line:63signature:() returntype:void -valid /tmp/apUNI8a/main.ino /^unsigned char valid;$/;" kind:variable line:114 -loop /tmp/apUNI8a/main.ino /^void loop() {$/;" kind:function line:116signature:() returntype:void -listeni /tmp/apUNI8a/main.ino /^void listeni()$/;" kind:function line:165signature:() returntype:void -kickIt /tmp/apUNI8a/main.ino /^void kickIt(unsigned char xType)$/;" kind:function line:172 signature:(unsigned char xType) returntype:void -lightFSM /tmp/apUNI8a/main.ino /^void lightFSM()$/;" kind:function line:181 signature:() returntype:void -touchFSM /tmp/apUNI8a/main.ino /^void touchFSM()$/;" kind:function line:188 signature:() returntype:void -tween /tmp/apUNI8a/main.ino /^unsigned char tween[4] = {3, 5, 7, 11};$/;" kind:variable line:206 -fsmFSM /tmp/apUNI8a/main.ino /^void fsmFSM()$/;" kind:function line:207signature:() returntype:void -doBW /tmp/apUNI8a/main.ino /^void doBW(void) {$/;" kind:function line:243signature:(void) returntype:void -checkBW /tmp/apUNI8a/main.ino /^void checkBW()$/;" kind:function line:249signature:() returntype:void -getSwitches /tmp/apUNI8a/main.ino /^unsigned char getSwitches()$/;" kind:function line:260 signature:() returntype:unsigned char -xxLamp /tmp/apUNI8a/main.ino /^unsigned char xxLamp;$/;" kind:variable line:292 -setLEDs /tmp/apUNI8a/main.ino /^void setLEDs(unsigned char xx)$/;" kind:function line:294 signature:(unsigned char xx) returntype:void -blinks /tmp/apUNI8a/main.ino /^const unsigned char blinks[8] = {0, 1, 0, 1, 0, 0, 1, 1};$/;" kind:variable line:311 -blinkLEDs /tmp/apUNI8a/main.ino /^void blinkLEDs()$/;" kind:function line:312 signature:() returntype:void -proto_state /tmp/apUNI8a/protocol.ino /^static uint8_t proto_state;$/;" kind:variable line:4 -bind_time /tmp/apUNI8a/protocol.ino /^static uint32_t bind_time;$/;"kind:variable line:5 -PROTOCOL_SetBindState /tmp/apUNI8a/protocol.ino /^void PROTOCOL_SetBindState(uint32_t msec)$/;" kind:function line:11 signature:(uint32_t msec) returntype:void diff --git a/ctags_runner.go b/ctags_runner.go deleted file mode 100644 index 7933bd41..00000000 --- a/ctags_runner.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/ctags" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type CTagsRunner struct{} - -func (s *CTagsRunner) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - ctagsTargetFilePath := ctx.CTagsTargetFile - logger := ctx.GetLogger() - - properties := buildProperties.Clone() - properties.Merge(buildProperties.SubTree(constants.BUILD_PROPERTIES_TOOLS_KEY).SubTree(constants.CTAGS)) - properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, ctagsTargetFilePath) - - pattern := properties.Get(constants.BUILD_PROPERTIES_PATTERN) - if pattern == constants.EMPTY_STRING { - return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, constants.CTAGS) - } - - commandLine := properties.ExpandPropsInString(pattern) - command, err := utils.PrepareCommand(commandLine, logger, "") - if err != nil { - return i18n.WrapError(err) - } - - sourceBytes, _, err := utils.ExecCommand(ctx, command, utils.Capture /* stdout */, utils.Ignore /* stderr */) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CTagsOutput = string(sourceBytes) - - parser := &ctags.CTagsParser{} - - ctx.CTagsOfPreprocessedSource = parser.Parse(ctx.CTagsOutput, ctx.Sketch.MainFile.Name) - parser.FixCLinkageTagsDeclarations(ctx.CTagsOfPreprocessedSource) - - protos, line := parser.GeneratePrototypes() - if line != -1 { - ctx.PrototypesLineWhereToInsert = line - } - ctx.Prototypes = protos - - return nil -} diff --git a/ctags_target_file_saver.go b/ctags_target_file_saver.go deleted file mode 100644 index ef94ff95..00000000 --- a/ctags_target_file_saver.go +++ /dev/null @@ -1,57 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type CTagsTargetFileSaver struct { - Source *string - TargetFileName string -} - -func (s *CTagsTargetFileSaver) Run(ctx *types.Context) error { - source := *s.Source - - preprocPath := ctx.PreprocPath - if err := preprocPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - ctagsTargetFilePath := preprocPath.Join(s.TargetFileName) - if err := ctagsTargetFilePath.WriteFile([]byte(source)); err != nil { - return i18n.WrapError(err) - } - - ctx.CTagsTargetFile = ctagsTargetFilePath - return nil -} diff --git a/dump_build_properties.go b/dump_build_properties.go deleted file mode 100644 index b64caa8e..00000000 --- a/dump_build_properties.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "sort" - - "github.com/arduino/arduino-builder/types" -) - -type DumpBuildProperties struct{} - -func (s *DumpBuildProperties) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - - keys := buildProperties.Keys() - sort.Strings(keys) - - for _, key := range keys { - fmt.Println(key + "=" + buildProperties.Get(key)) - } - - return nil -} diff --git a/ensure_buildpath_exists.go b/ensure_buildpath_exists.go deleted file mode 100644 index 15b5c42d..00000000 --- a/ensure_buildpath_exists.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type EnsureBuildPathExists struct{} - -func (s *EnsureBuildPathExists) Run(ctx *types.Context) error { - if err := ctx.BuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - return nil -} diff --git a/fail_if_buildpath_equals_sketchpath.go b/fail_if_buildpath_equals_sketchpath.go deleted file mode 100644 index 84359db3..00000000 --- a/fail_if_buildpath_equals_sketchpath.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type FailIfBuildPathEqualsSketchPath struct{} - -func (s *FailIfBuildPathEqualsSketchPath) Run(ctx *types.Context) error { - if ctx.BuildPath == nil || ctx.SketchLocation == nil { - return nil - } - - buildPath, err := ctx.BuildPath.Abs() - if err != nil { - return i18n.WrapError(err) - } - - sketchPath, err := ctx.SketchLocation.Abs() - if err != nil { - return i18n.WrapError(err) - } - sketchPath = sketchPath.Parent() - - if buildPath.EqualsTo(sketchPath) { - return i18n.ErrorfWithLogger(ctx.GetLogger(), constants.MSG_SKETCH_CANT_BE_IN_BUILDPATH) - } - - return nil -} diff --git a/fail_if_imported_library_is_wrong.go b/fail_if_imported_library_is_wrong.go deleted file mode 100644 index 760d0e09..00000000 --- a/fail_if_imported_library_is_wrong.go +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/libraries" -) - -type FailIfImportedLibraryIsWrong struct{} - -func (s *FailIfImportedLibraryIsWrong) Run(ctx *types.Context) error { - if len(ctx.ImportedLibraries) == 0 { - 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, constants.MSG_ARCH_FOLDER_NOT_SUPPORTED) - } - for _, propName := range libraries.MandatoryProperties { - if !library.Properties.ContainsKey(propName) { - return i18n.ErrorfWithLogger(logger, constants.MSG_PROP_IN_LIBRARY, propName, library.InstallDir) - } - } - if library.Layout == libraries.RecursiveLayout { - if library.UtilityDir != nil { - return i18n.ErrorfWithLogger(logger, constants.MSG_LIBRARY_CAN_USE_SRC_AND_UTILITY_FOLDERS, library.InstallDir) - } - } - } - } - - return nil -} diff --git a/filter_sketch_source.go b/filter_sketch_source.go deleted file mode 100644 index db852665..00000000 --- a/filter_sketch_source.go +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "bufio" - "strconv" - "strings" - - "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type FilterSketchSource struct { - Source *string - RemoveLineMarkers bool -} - -func (s *FilterSketchSource) Run(ctx *types.Context) error { - fileNames := paths.NewPathList() - fileNames.Add(ctx.Sketch.MainFile.Name) - for _, file := range ctx.Sketch.OtherSketchFiles { - fileNames = append(fileNames, file.Name) - } - - inSketch := false - filtered := "" - - scanner := bufio.NewScanner(strings.NewReader(*s.Source)) - for scanner.Scan() { - line := scanner.Text() - if filename := parseLineMarker(line); filename != nil { - inSketch = fileNames.Contains(filename) - if inSketch && s.RemoveLineMarkers { - continue - } - } - - if inSketch { - filtered += line + "\n" - } - } - - *s.Source = filtered - return nil -} - -// Parses the given line as a gcc line marker and returns the contained -// filename. -func parseLineMarker(line string) *paths.Path { - // A line marker contains the line number and filename and looks like: - // # 123 /path/to/file.cpp - // It can be followed by zero or more flag number that indicate the - // preprocessor state and can be ignored. - // For exact details on this format, see: - // https://github.com/gcc-mirror/gcc/blob/edd716b6b1caa1a5cb320a8cd7f626f30198e098/gcc/c-family/c-ppoutput.c#L413-L415 - - split := strings.SplitN(line, " ", 3) - if len(split) < 3 || len(split[0]) == 0 || split[0][0] != '#' { - return nil - } - - _, err := strconv.Atoi(split[1]) - if err != nil { - return nil - } - - // If we get here, we found a # followed by a line number, so - // assume this is a line marker and see if the rest of the line - // starts with a string containing the filename - str, rest, ok := utils.ParseCppString(split[2]) - - if ok && (rest == "" || rest[0] == ' ') { - return paths.New(str) - } - return nil -} diff --git a/gcc_preproc_runner.go b/gcc_preproc_runner.go deleted file mode 100644 index e084d8af..00000000 --- a/gcc_preproc_runner.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os/exec" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" -) - -func GCCPreprocRunner(ctx *types.Context, sourceFilePath *paths.Path, targetFilePath *paths.Path, includes paths.PathList) error { - cmd, err := prepareGCCPreprocRecipeProperties(ctx, sourceFilePath, targetFilePath, includes) - if err != nil { - return i18n.WrapError(err) - } - - _, _, err = utils.ExecCommand(ctx, cmd /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func GCCPreprocRunnerForDiscoveringIncludes(ctx *types.Context, sourceFilePath *paths.Path, targetFilePath *paths.Path, includes paths.PathList) ([]byte, error) { - cmd, err := prepareGCCPreprocRecipeProperties(ctx, sourceFilePath, targetFilePath, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - - _, stderr, err := utils.ExecCommand(ctx, cmd /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Capture) - if err != nil { - return stderr, i18n.WrapError(err) - } - - return stderr, nil -} - -func prepareGCCPreprocRecipeProperties(ctx *types.Context, sourceFilePath *paths.Path, targetFilePath *paths.Path, includes paths.PathList) (*exec.Cmd, error) { - properties := ctx.BuildProperties.Clone() - properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, sourceFilePath) - properties.SetPath(constants.BUILD_PROPERTIES_PREPROCESSED_FILE_PATH, targetFilePath) - - includesStrings := utils.Map(includes.AsStrings(), utils.WrapWithHyphenI) - properties.Set(constants.BUILD_PROPERTIES_INCLUDES, strings.Join(includesStrings, constants.SPACE)) - - if properties.Get(constants.RECIPE_PREPROC_MACROS) == "" { - //generate PREPROC_MACROS from RECIPE_CPP_PATTERN - properties.Set(constants.RECIPE_PREPROC_MACROS, GeneratePreprocPatternFromCompile(properties.Get(constants.RECIPE_CPP_PATTERN))) - } - - cmd, err := builder_utils.PrepareCommandForRecipe(ctx, properties, constants.RECIPE_PREPROC_MACROS, true) - if err != nil { - return nil, i18n.WrapError(err) - } - - // Remove -MMD argument if present. Leaving it will make gcc try - // to create a /dev/null.d dependency file, which won't work. - cmd.Args = utils.Filter(cmd.Args, func(a string) bool { return a != "-MMD" }) - - return cmd, nil -} - -func GeneratePreprocPatternFromCompile(compilePattern string) string { - // add {preproc.macros.flags} - // replace "{object_file}" with "{preprocessed_file_path}" - returnString := compilePattern - returnString = strings.Replace(returnString, "{compiler.cpp.flags}", "{compiler.cpp.flags} {preproc.macros.flags}", 1) - returnString = strings.Replace(returnString, "{object_file}", "{preprocessed_file_path}", 1) - return returnString -} diff --git a/generate_buildpath_if_missing.go b/generate_buildpath_if_missing.go deleted file mode 100644 index 20afef86..00000000 --- a/generate_buildpath_if_missing.go +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - paths "github.com/arduino/go-paths-helper" -) - -type GenerateBuildPathIfMissing struct{} - -func (s *GenerateBuildPathIfMissing) Run(ctx *types.Context) error { - if ctx.BuildPath != nil { - return nil - } - - md5sum := utils.MD5Sum([]byte(ctx.SketchLocation.String())) - - buildPath := paths.TempDir().Join("arduino-sketch-" + strings.ToUpper(md5sum)) - - if ctx.DebugLevel > 5 { - logger := ctx.GetLogger() - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_SETTING_BUILD_PATH, buildPath) - } - - ctx.BuildPath = buildPath - - return nil -} diff --git a/gohasissues/go_has_issues.go b/gohasissues/go_has_issues.go deleted file mode 100644 index 60c422ac..00000000 --- a/gohasissues/go_has_issues.go +++ /dev/null @@ -1,145 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package gohasissues - -import ( - "io/ioutil" - "os" - "path/filepath" - "sort" - "strconv" - "strings" -) - -func Walk(root string, walkFn filepath.WalkFunc) error { - info, err := os.Stat(root) - if err != nil { - return walkFn(root, nil, err) - } - return walk(root, info, walkFn) -} - -func walk(path string, info os.FileInfo, walkFn filepath.WalkFunc) error { - err := walkFn(path, info, nil) - if err != nil { - if info.IsDir() && err == filepath.SkipDir { - return nil - } - return err - } - - if !info.IsDir() { - return nil - } - - names, err := readDirNames(path) - if err != nil { - return walkFn(path, info, err) - } - - for _, name := range names { - filename := filepath.Join(path, name) - fileInfo, err := os.Stat(filename) - if err != nil { - if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { - return err - } - } else { - err = walk(filename, fileInfo, walkFn) - if err != nil { - if !fileInfo.IsDir() || err != filepath.SkipDir { - return err - } - } - } - } - return nil -} - -// readDirNames reads the directory named by dirname and returns -// a sorted list of directory entries. -func readDirNames(dirname string) ([]string, error) { - f, err := os.Open(dirname) - if err != nil { - return nil, err - } - names, err := f.Readdirnames(-1) - f.Close() - if err != nil { - return nil, err - } - sort.Strings(names) - return names, nil -} - -func ReadDir(dirname string) ([]os.FileInfo, error) { - infos, err := ioutil.ReadDir(dirname) - if err != nil { - return nil, err - } - - for idx, info := range infos { - info, err := resolveSymlink(dirname, info) - if err != nil { - // unresolvable symlinks should be skipped silently - continue - } - infos[idx] = info - } - - return infos, nil -} - -func resolveSymlink(parentFolder string, info os.FileInfo) (os.FileInfo, error) { - if !isSymlink(info) { - return info, nil - } - return os.Stat(filepath.Join(parentFolder, info.Name())) -} - -func isSymlink(info os.FileInfo) bool { - return info.Mode()&os.ModeSymlink != 0 -} - -func Unquote(s string) (string, error) { - if stringStartsEndsWith(s, "'") { - s = s[1 : len(s)-1] - } - - if !stringStartsEndsWith(s, "\"") { - return s, nil - } - - return strconv.Unquote(s) -} - -func stringStartsEndsWith(s string, c string) bool { - return strings.HasPrefix(s, c) && strings.HasSuffix(s, c) -} diff --git a/grpc/proto/builder.pb.go b/grpc/proto/builder.pb.go deleted file mode 100644 index 4690c81c..00000000 --- a/grpc/proto/builder.pb.go +++ /dev/null @@ -1,396 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: builder.proto - -/* -Package proto is a generated protocol buffer package. - -It is generated from these files: - builder.proto - -It has these top-level messages: - BuildParams - VerboseParams - Response -*/ -package proto - -import proto1 "github.com/golang/protobuf/proto" -import fmt "fmt" -import math "math" - -import ( - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto1.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto1.ProtoPackageIsVersion2 // please upgrade the proto package - -type BuildParams struct { - HardwareFolders string `protobuf:"bytes,1,opt,name=hardwareFolders" json:"hardwareFolders,omitempty"` - ToolsFolders string `protobuf:"bytes,2,opt,name=toolsFolders" json:"toolsFolders,omitempty"` - BuiltInLibrariesFolders string `protobuf:"bytes,3,opt,name=builtInLibrariesFolders" json:"builtInLibrariesFolders,omitempty"` - OtherLibrariesFolders string `protobuf:"bytes,4,opt,name=otherLibrariesFolders" json:"otherLibrariesFolders,omitempty"` - SketchLocation string `protobuf:"bytes,5,opt,name=sketchLocation" json:"sketchLocation,omitempty"` - FQBN string `protobuf:"bytes,6,opt,name=fQBN" json:"fQBN,omitempty"` - ArduinoAPIVersion string `protobuf:"bytes,7,opt,name=arduinoAPIVersion" json:"arduinoAPIVersion,omitempty"` - CustomBuildProperties string `protobuf:"bytes,8,opt,name=customBuildProperties" json:"customBuildProperties,omitempty"` - BuildCachePath string `protobuf:"bytes,9,opt,name=buildCachePath" json:"buildCachePath,omitempty"` - BuildPath string `protobuf:"bytes,10,opt,name=buildPath" json:"buildPath,omitempty"` - WarningsLevel string `protobuf:"bytes,11,opt,name=warningsLevel" json:"warningsLevel,omitempty"` - CodeCompleteAt string `protobuf:"bytes,12,opt,name=codeCompleteAt" json:"codeCompleteAt,omitempty"` - Verbose bool `protobuf:"varint,13,opt,name=verbose" json:"verbose,omitempty"` -} - -func (m *BuildParams) Reset() { *m = BuildParams{} } -func (m *BuildParams) String() string { return proto1.CompactTextString(m) } -func (*BuildParams) ProtoMessage() {} -func (*BuildParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} } - -func (m *BuildParams) GetHardwareFolders() string { - if m != nil { - return m.HardwareFolders - } - return "" -} - -func (m *BuildParams) GetToolsFolders() string { - if m != nil { - return m.ToolsFolders - } - return "" -} - -func (m *BuildParams) GetBuiltInLibrariesFolders() string { - if m != nil { - return m.BuiltInLibrariesFolders - } - return "" -} - -func (m *BuildParams) GetOtherLibrariesFolders() string { - if m != nil { - return m.OtherLibrariesFolders - } - return "" -} - -func (m *BuildParams) GetSketchLocation() string { - if m != nil { - return m.SketchLocation - } - return "" -} - -func (m *BuildParams) GetFQBN() string { - if m != nil { - return m.FQBN - } - return "" -} - -func (m *BuildParams) GetArduinoAPIVersion() string { - if m != nil { - return m.ArduinoAPIVersion - } - return "" -} - -func (m *BuildParams) GetCustomBuildProperties() string { - if m != nil { - return m.CustomBuildProperties - } - return "" -} - -func (m *BuildParams) GetBuildCachePath() string { - if m != nil { - return m.BuildCachePath - } - return "" -} - -func (m *BuildParams) GetBuildPath() string { - if m != nil { - return m.BuildPath - } - return "" -} - -func (m *BuildParams) GetWarningsLevel() string { - if m != nil { - return m.WarningsLevel - } - return "" -} - -func (m *BuildParams) GetCodeCompleteAt() string { - if m != nil { - return m.CodeCompleteAt - } - return "" -} - -func (m *BuildParams) GetVerbose() bool { - if m != nil { - return m.Verbose - } - return false -} - -type VerboseParams struct { - Verbose bool `protobuf:"varint,1,opt,name=verbose" json:"verbose,omitempty"` -} - -func (m *VerboseParams) Reset() { *m = VerboseParams{} } -func (m *VerboseParams) String() string { return proto1.CompactTextString(m) } -func (*VerboseParams) ProtoMessage() {} -func (*VerboseParams) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} } - -func (m *VerboseParams) GetVerbose() bool { - if m != nil { - return m.Verbose - } - return false -} - -type Response struct { - Line string `protobuf:"bytes,1,opt,name=line" json:"line,omitempty"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto1.CompactTextString(m) } -func (*Response) ProtoMessage() {} -func (*Response) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } - -func (m *Response) GetLine() string { - if m != nil { - return m.Line - } - return "" -} - -func init() { - proto1.RegisterType((*BuildParams)(nil), "proto.BuildParams") - proto1.RegisterType((*VerboseParams)(nil), "proto.VerboseParams") - proto1.RegisterType((*Response)(nil), "proto.Response") -} - -// Reference imports to suppress errors if they are not otherwise used. -var _ context.Context -var _ grpc.ClientConn - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -const _ = grpc.SupportPackageIsVersion4 - -// Client API for Builder service - -type BuilderClient interface { - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - Build(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (Builder_BuildClient, error) - Autocomplete(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (*Response, error) - DropCache(ctx context.Context, in *VerboseParams, opts ...grpc.CallOption) (*Response, error) -} - -type builderClient struct { - cc *grpc.ClientConn -} - -func NewBuilderClient(cc *grpc.ClientConn) BuilderClient { - return &builderClient{cc} -} - -func (c *builderClient) Build(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (Builder_BuildClient, error) { - stream, err := grpc.NewClientStream(ctx, &_Builder_serviceDesc.Streams[0], c.cc, "/proto.Builder/Build", opts...) - if err != nil { - return nil, err - } - x := &builderBuildClient{stream} - if err := x.ClientStream.SendMsg(in); err != nil { - return nil, err - } - if err := x.ClientStream.CloseSend(); err != nil { - return nil, err - } - return x, nil -} - -type Builder_BuildClient interface { - Recv() (*Response, error) - grpc.ClientStream -} - -type builderBuildClient struct { - grpc.ClientStream -} - -func (x *builderBuildClient) Recv() (*Response, error) { - m := new(Response) - if err := x.ClientStream.RecvMsg(m); err != nil { - return nil, err - } - return m, nil -} - -func (c *builderClient) Autocomplete(ctx context.Context, in *BuildParams, opts ...grpc.CallOption) (*Response, error) { - out := new(Response) - err := grpc.Invoke(ctx, "/proto.Builder/Autocomplete", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *builderClient) DropCache(ctx context.Context, in *VerboseParams, opts ...grpc.CallOption) (*Response, error) { - out := new(Response) - err := grpc.Invoke(ctx, "/proto.Builder/DropCache", in, out, c.cc, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// Server API for Builder service - -type BuilderServer interface { - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - Build(*BuildParams, Builder_BuildServer) error - Autocomplete(context.Context, *BuildParams) (*Response, error) - DropCache(context.Context, *VerboseParams) (*Response, error) -} - -func RegisterBuilderServer(s *grpc.Server, srv BuilderServer) { - s.RegisterService(&_Builder_serviceDesc, srv) -} - -func _Builder_Build_Handler(srv interface{}, stream grpc.ServerStream) error { - m := new(BuildParams) - if err := stream.RecvMsg(m); err != nil { - return err - } - return srv.(BuilderServer).Build(m, &builderBuildServer{stream}) -} - -type Builder_BuildServer interface { - Send(*Response) error - grpc.ServerStream -} - -type builderBuildServer struct { - grpc.ServerStream -} - -func (x *builderBuildServer) Send(m *Response) error { - return x.ServerStream.SendMsg(m) -} - -func _Builder_Autocomplete_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(BuildParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BuilderServer).Autocomplete(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/proto.Builder/Autocomplete", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BuilderServer).Autocomplete(ctx, req.(*BuildParams)) - } - return interceptor(ctx, in, info, handler) -} - -func _Builder_DropCache_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerboseParams) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(BuilderServer).DropCache(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/proto.Builder/DropCache", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(BuilderServer).DropCache(ctx, req.(*VerboseParams)) - } - return interceptor(ctx, in, info, handler) -} - -var _Builder_serviceDesc = grpc.ServiceDesc{ - ServiceName: "proto.Builder", - HandlerType: (*BuilderServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Autocomplete", - Handler: _Builder_Autocomplete_Handler, - }, - { - MethodName: "DropCache", - Handler: _Builder_DropCache_Handler, - }, - }, - Streams: []grpc.StreamDesc{ - { - StreamName: "Build", - Handler: _Builder_Build_Handler, - ServerStreams: true, - }, - }, - Metadata: "builder.proto", -} - -func init() { proto1.RegisterFile("builder.proto", fileDescriptor0) } - -var fileDescriptor0 = []byte{ - // 420 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x93, 0x6f, 0x6b, 0x13, 0x41, - 0x10, 0xc6, 0x3d, 0x4d, 0x9a, 0x64, 0x9a, 0x58, 0x1c, 0x14, 0x17, 0x11, 0x29, 0xa1, 0x48, 0x04, - 0x09, 0x45, 0x2b, 0xf8, 0x36, 0x57, 0x11, 0x0a, 0x41, 0xce, 0xbc, 0xe8, 0xfb, 0xbd, 0xcd, 0xe8, - 0x2d, 0x5e, 0x6e, 0x8e, 0xdd, 0x4d, 0xfb, 0x59, 0xfc, 0x06, 0x7e, 0x4c, 0xd9, 0x3f, 0xd1, 0x5e, - 0x13, 0xc1, 0x57, 0x99, 0x3c, 0xcf, 0x6f, 0x6e, 0x9f, 0xdb, 0x99, 0x83, 0x49, 0xb9, 0xd5, 0xf5, - 0x9a, 0xcc, 0xbc, 0x35, 0xec, 0x18, 0xfb, 0xe1, 0x67, 0xfa, 0xb3, 0x07, 0xc7, 0xb9, 0x37, 0x0a, - 0x69, 0xe4, 0xc6, 0xe2, 0x0c, 0x4e, 0x2a, 0x69, 0xd6, 0xb7, 0xd2, 0xd0, 0x67, 0xf6, 0xb8, 0x15, - 0xd9, 0x69, 0x36, 0x1b, 0xad, 0xee, 0xcb, 0x38, 0x85, 0xb1, 0x63, 0xae, 0xed, 0x0e, 0x7b, 0x18, - 0xb0, 0x8e, 0x86, 0x1f, 0xe1, 0xb9, 0x3f, 0xd5, 0x5d, 0x35, 0x4b, 0x5d, 0x1a, 0x69, 0x34, 0xfd, - 0xc1, 0x1f, 0x05, 0xfc, 0x5f, 0x36, 0x5e, 0xc0, 0x33, 0x76, 0x15, 0x99, 0xbd, 0xbe, 0x5e, 0xe8, - 0x3b, 0x6c, 0xe2, 0x6b, 0x78, 0x6c, 0x7f, 0x90, 0x53, 0xd5, 0x92, 0x95, 0x74, 0x9a, 0x1b, 0xd1, - 0x0f, 0xf8, 0x3d, 0x15, 0x11, 0x7a, 0xdf, 0xbe, 0xe6, 0x5f, 0xc4, 0x51, 0x70, 0x43, 0x8d, 0x6f, - 0xe1, 0x89, 0x34, 0xeb, 0xad, 0x6e, 0x78, 0x51, 0x5c, 0x5d, 0x93, 0xb1, 0xbe, 0x7d, 0x10, 0x80, - 0x7d, 0xc3, 0xe7, 0x53, 0x5b, 0xeb, 0x78, 0x13, 0x2f, 0xcf, 0x70, 0x4b, 0xc6, 0x69, 0xb2, 0x62, - 0x18, 0xf3, 0x1d, 0x34, 0x7d, 0xbe, 0x30, 0x85, 0x4b, 0xa9, 0x2a, 0x2a, 0xa4, 0xab, 0xc4, 0x28, - 0xe6, 0xeb, 0xaa, 0xf8, 0x12, 0x46, 0x65, 0x1c, 0x8a, 0xab, 0x04, 0x04, 0xe4, 0xaf, 0x80, 0x67, - 0x30, 0xb9, 0x95, 0xa6, 0xd1, 0xcd, 0x77, 0xbb, 0xa4, 0x1b, 0xaa, 0xc5, 0x71, 0x20, 0xba, 0xa2, - 0x3f, 0x4b, 0xf1, 0x9a, 0x2e, 0x79, 0xd3, 0xd6, 0xe4, 0x68, 0xe1, 0xc4, 0x38, 0x9e, 0xd5, 0x55, - 0x51, 0xc0, 0xe0, 0x86, 0x4c, 0xc9, 0x96, 0xc4, 0xe4, 0x34, 0x9b, 0x0d, 0x57, 0xbb, 0xbf, 0xd3, - 0x37, 0x30, 0xb9, 0x8e, 0x65, 0x5a, 0x8e, 0x3b, 0x68, 0xd6, 0x45, 0x5f, 0xc1, 0x70, 0x45, 0xb6, - 0xe5, 0xc6, 0x92, 0xbf, 0xdc, 0x5a, 0x37, 0x94, 0xf6, 0x26, 0xd4, 0xef, 0x7e, 0x65, 0x30, 0xc8, - 0xe3, 0xfe, 0xe1, 0x39, 0xf4, 0x43, 0x89, 0x18, 0x57, 0x71, 0x7e, 0x67, 0xff, 0x5e, 0x9c, 0x24, - 0x6d, 0xf7, 0xb4, 0xe9, 0x83, 0xf3, 0x0c, 0x3f, 0xc0, 0x78, 0xb1, 0x75, 0xac, 0x52, 0xe8, 0xff, - 0x6c, 0xc4, 0x0b, 0x18, 0x7d, 0x32, 0xdc, 0x86, 0x6b, 0xc5, 0xa7, 0xc9, 0xef, 0xbc, 0xd1, 0x81, - 0xae, 0xfc, 0x0c, 0x50, 0xa9, 0x79, 0x9a, 0xf8, 0x3c, 0x7d, 0x34, 0xf9, 0x38, 0xa5, 0x2f, 0x3c, - 0x5e, 0x64, 0xe5, 0x51, 0xe8, 0x7b, 0xff, 0x3b, 0x00, 0x00, 0xff, 0xff, 0xb2, 0x39, 0x66, 0x51, - 0x56, 0x03, 0x00, 0x00, -} diff --git a/grpc/proto/builder.proto b/grpc/proto/builder.proto deleted file mode 100644 index 9b310284..00000000 --- a/grpc/proto/builder.proto +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015 gRPC authors. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// compile me with: protoc -I proto/ proto/builder.proto --go_out=plugins=grpc:proto - -syntax = "proto3"; - -option java_multiple_files = true; -option java_package = "cc.arduino.builder"; -option java_outer_classname = "BuilderProto"; - -package proto; - -// Interface exported by the server. -service Builder { - - // A server-to-client streaming RPC. - // - // Obtains the Features available within the given Rectangle. Results are - // streamed rather than returned at once (e.g. in a response message with a - // repeated field), as the rectangle may cover a large area and contain a - // huge number of features. - rpc Build(BuildParams) returns (stream Response) {} - - rpc Autocomplete(BuildParams) returns (Response) {} - - rpc DropCache(VerboseParams) returns (Response) {} -} - -message BuildParams { - string hardwareFolders = 1; - string toolsFolders = 2; - string builtInLibrariesFolders = 3; - string otherLibrariesFolders = 4; - string sketchLocation = 5; - string fQBN = 6; - string arduinoAPIVersion = 7; - string customBuildProperties = 8; - string buildCachePath = 9; - string buildPath = 10; - string warningsLevel = 11; - string codeCompleteAt = 12; - bool verbose = 13; -} - -message VerboseParams { - bool verbose = 1; -} - -message Response { - string line = 1; -} diff --git a/grpc/rpc.go b/grpc/rpc.go deleted file mode 100644 index c01f290e..00000000 --- a/grpc/rpc.go +++ /dev/null @@ -1,235 +0,0 @@ -package jsonrpc - -import ( - "fmt" - "io" - "log" - "net" - "os" - "strings" - - "github.com/arduino/arduino-cli/arduino/cores" - "github.com/arduino/go-paths-helper" - - builder "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/fsnotify/fsnotify" - "golang.org/x/net/context" - "google.golang.org/grpc" - - pb "github.com/arduino/arduino-builder/grpc/proto" -) - -type StreamLogger struct { - stream pb.Builder_BuildServer -} - -func (s StreamLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - s.stream.Send(&pb.Response{Line: fmt.Sprintf(format, a...)}) -} - -func (s StreamLogger) UnformattedFprintln(w io.Writer, str string) { - s.stream.Send(&pb.Response{Line: str}) -} - -func (s StreamLogger) UnformattedWrite(w io.Writer, data []byte) { - s.stream.Send(&pb.Response{Line: string(data)}) -} - -func (s StreamLogger) Println(level string, format string, a ...interface{}) { - s.stream.Send(&pb.Response{Line: fmt.Sprintf(format, a...)}) -} - -func (s StreamLogger) Flush() string { - return "" -} - -func (s StreamLogger) Name() string { - return "streamlogger" -} - -type builderServer struct { - resp []*pb.Response - ctx *types.Context - watcher *fsnotify.Watcher -} - -func (s *builderServer) watch() { - folders := []paths.PathList{s.ctx.HardwareDirs, s.ctx.ToolsDirs, s.ctx.BuiltInLibrariesDirs, s.ctx.OtherLibrariesDirs} - - for _, category := range folders { - for _, folder := range category { - if !s.ctx.WatchedLocations.Contains(folder) { - var subfolders []string - utils.FindAllSubdirectories(folder.String(), &subfolders) - subfolders = append(subfolders, folder.String()) - for _, element := range subfolders { - s.watcher.Add(element) - s.ctx.WatchedLocations.AddIfMissing(paths.New(element)) - } - } - } - } -} - -func (s *builderServer) DropCache(ctx context.Context, args *pb.VerboseParams) (*pb.Response, error) { - s.ctx.CanUseCachedTools = false - response := pb.Response{Line: "Tools cache dropped"} - return &response, nil -} - -// GetFeature returns the feature at the given point. -func (s *builderServer) Autocomplete(ctx context.Context, args *pb.BuildParams) (*pb.Response, error) { - - s.ctx.HardwareDirs = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) - s.ctx.ToolsDirs = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) - s.ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) - s.ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) - s.ctx.SketchLocation = paths.New(args.SketchLocation) - s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") - s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - if fqbn, err := cores.ParseFQBN(args.FQBN); err != nil { - return nil, fmt.Errorf("parsing fqbn: %s", err) - } else { - s.ctx.FQBN = fqbn - } - s.ctx.Verbose = false //p.Verbose - s.ctx.BuildCachePath = paths.New(args.BuildCachePath) - s.ctx.BuildPath = paths.New(args.BuildPath) - s.ctx.WarningsLevel = args.WarningsLevel - s.ctx.PrototypesSection = "" - s.ctx.CodeCompleteAt = args.CodeCompleteAt - s.ctx.CodeCompletions = "" - - s.ctx.IncludeFolders = s.ctx.IncludeFolders[0:0] - s.ctx.LibrariesObjectFiles = s.ctx.LibrariesObjectFiles[0:0] - s.ctx.CoreObjectsFiles = s.ctx.CoreObjectsFiles[0:0] - s.ctx.SketchObjectFiles = s.ctx.SketchObjectFiles[0:0] - - s.ctx.ImportedLibraries = s.ctx.ImportedLibraries[0:0] - - //s.watch() - - oldlogger := s.ctx.GetLogger() - logger := i18n.NoopLogger{} - s.ctx.SetLogger(logger) - - err := builder.RunPreprocess(s.ctx) - - response := pb.Response{Line: s.ctx.CodeCompletions} - s.ctx.SetLogger(oldlogger) - - return &response, err -} - -// GetFeature returns the feature at the given point. -func (s *builderServer) Build(args *pb.BuildParams, stream pb.Builder_BuildServer) error { - - s.ctx.HardwareDirs = paths.NewPathList(strings.Split(args.HardwareFolders, ",")...) - s.ctx.ToolsDirs = paths.NewPathList(strings.Split(args.ToolsFolders, ",")...) - s.ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(args.BuiltInLibrariesFolders, ",")...) - s.ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(args.OtherLibrariesFolders, ",")...) - s.ctx.SketchLocation = paths.New(args.SketchLocation) - s.ctx.CustomBuildProperties = strings.Split(args.CustomBuildProperties, ",") - s.ctx.ArduinoAPIVersion = args.ArduinoAPIVersion - if fqbn, err := cores.ParseFQBN(args.FQBN); err != nil { - return fmt.Errorf("parsing fqbn: %s", err) - } else { - s.ctx.FQBN = fqbn - } - s.ctx.Verbose = args.Verbose - s.ctx.BuildCachePath = paths.New(args.BuildCachePath) - s.ctx.BuildPath = paths.New(args.BuildPath) - s.ctx.WarningsLevel = args.WarningsLevel - s.ctx.PrototypesSection = "" - s.ctx.CodeCompleteAt = "" - - s.ctx.IncludeFolders = s.ctx.IncludeFolders[0:0] - s.ctx.LibrariesObjectFiles = s.ctx.LibrariesObjectFiles[0:0] - s.ctx.CoreObjectsFiles = s.ctx.CoreObjectsFiles[0:0] - s.ctx.SketchObjectFiles = s.ctx.SketchObjectFiles[0:0] - - s.ctx.ImportedLibraries = s.ctx.ImportedLibraries[0:0] - - // setup logger to send via protobuf - oldlogger := s.ctx.GetLogger() - logger := StreamLogger{stream} - s.ctx.SetLogger(logger) - - //s.watch() - - err := builder.RunBuilder(s.ctx) - s.ctx.SetLogger(oldlogger) - if err != nil { - return err - } - - // No feature was found, return an unnamed feature - return nil -} - -/* -func (h *WatchHandler) ServeJSONRPC(c context.Context, params *json.RawMessage) (interface{}, *jsonrpc.Error) { - - var p WatchParams - if err := jsonrpc.Unmarshal(params, &p); err != nil { - return nil, err - } - - err := h.watcher.Add(p.Path) - if err != nil { - return nil, jsonrpc.ErrInvalidParams() - } - return BuildResult{ - Message: "OK " + p.Path, - }, nil -} -*/ - -func startWatching(ctx *types.Context) *fsnotify.Watcher { - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Fatal(err) - } - - go func() { - for { - select { - case event := <-watcher.Events: - ctx.CanUseCachedTools = false - log.Println("event:", event) - case err := <-watcher.Errors: - log.Println("error:", err) - } - } - }() - return watcher -} - -func newServerWithWatcher(ctx *types.Context, watcher *fsnotify.Watcher) *builderServer { - s := new(builderServer) - s.ctx = ctx - s.watcher = watcher - return s -} - -func newServer(ctx *types.Context) *builderServer { - s := new(builderServer) - s.ctx = ctx - return s -} - -func RegisterAndServeJsonRPC(ctx *types.Context) { - lis, err := net.Listen("tcp", "localhost:12345") - if err != nil { - //can't spawn two grpc servers on the same port - os.Exit(0) - } - //watcher := startWatching(ctx) - - grpcServer := grpc.NewServer() - pb.RegisterBuilderServer(grpcServer, newServer(ctx)) - grpcServer.Serve(lis) -} diff --git a/hardware/platform.keys.rewrite.txt b/hardware/platform.keys.rewrite.txt deleted file mode 100644 index 4e8c93fb..00000000 --- a/hardware/platform.keys.rewrite.txt +++ /dev/null @@ -1,42 +0,0 @@ -old.0.compiler.path={runtime.ide.path}/hardware/tools/avr/bin/ -new.0.compiler.path={runtime.tools.avr-gcc.path}/bin/ - -old.1.tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude -new.1.tools.avrdude.cmd.path={path}/bin/avrdude - -old.2.tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf -new.2.tools.avrdude.config.path={path}/etc/avrdude.conf - -old.3.compiler.path={runtime.ide.path}/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/ -new.3.compiler.path={runtime.tools.arm-none-eabi-gcc.path}/bin/ - -old.4.tools.bossac.path={runtime.ide.path}/hardware/tools -new.4.tools.bossac.path={runtime.tools.bossac.path} - -old.5.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group "{build.path}/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc -new.5.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group "{build.path}/core/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc - -#specific to RedBearLab nRF51822 Boards -old.6.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb -Wl,--gc-sections --specs=nano.specs -Wl,--wrap,main -Wl,-Map={build.path}/{build.project_name}.map,--cref "-T{build.variant.path}/{build.ldscript}" -o "{build.path}/{build.project_name}.elf" -Wl,--start-group "{build.path}/system_nrf51.c.o" {object_files} "{build.path}/startup_NRF51822.s.o" "{build.path}/{archive_file}" -Wl,--end-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys -new.6.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" -mcpu={build.mcu} -mthumb -Wl,--gc-sections --specs=nano.specs -Wl,--wrap,main -Wl,-Map={build.path}/{build.project_name}.map,--cref "-T{build.variant.path}/{build.ldscript}" -o "{build.path}/{build.project_name}.elf" -Wl,--start-group "{build.path}/core/mbed/targets/cmsis/TARGET_NORDIC/TARGET_MCU_NRF51822/system_nrf51.c.o" {object_files} "{build.path}/core/startup_NRF51822.S.o" "{build.path}/{archive_file}" -Wl,--end-group -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys - -#specific to RFduino 1.6.3 -old.7.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} {build.extra_flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" -Wl,--cref -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/syscalls.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.variant.path}/libRFduino.a" "{build.variant.path}/libRFduinoBLE.a" "{build.variant.path}/libRFduinoGZLL.a" "{build.path}/{archive_file}" -Wl,--end-group -new.7.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} {build.extra_flags} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" -Wl,--cref -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/core/syscalls.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.variant.path}/libRFduino.a" "{build.variant.path}/libRFduinoBLE.a" "{build.variant.path}/libRFduinoGZLL.a" "{build.path}/{archive_file}" -Wl,--end-group - -old.8.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}" -new.8.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{archive_file_path}" "{object_file}" - -old.9.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc -new.9.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mcpu={build.mcu} "-T{build.variant.path}/{build.ldscript}" "-Wl,-Map,{build.path}/{build.project_name}.map" {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" "-L{build.path}" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--start-group "{build.path}/core/syscalls_sam3.c.o" {object_files} "{build.variant.path}/{build.variant_system_lib}" "{build.path}/{archive_file}" -Wl,--end-group -lm -gcc - -#specific to Digistump AVR Boards 1.5.4 -old.10.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} "{build.path}/{archive_file}" "{object_file}" -new.10.recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} "{archive_file_path}" "{object_file}" - -old.11.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} -o "{build.path}/{build.project_name}.elf" {object_files} "{build.path}/{archive_file}" "-L{build.path}" -lm -new.11.recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} -o "{build.path}/{build.project_name}.elf" {object_files} "{archive_file_path}" "-L{build.path}" -lm - -#generic again -old.12.recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -new.12.recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{preprocessed_file_path}" \ No newline at end of file diff --git a/hardware_loader.go b/hardware_loader.go deleted file mode 100644 index ecea2cc9..00000000 --- a/hardware_loader.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores/packagemanager" -) - -type HardwareLoader struct{} - -func (s *HardwareLoader) Run(ctx *types.Context) error { - if ctx.PackageManager == nil { - pm := packagemanager.NewPackageManager(nil, nil, nil, nil) - if err := pm.LoadHardwareFromDirectories(ctx.HardwareDirs); err != nil { - return i18n.WrapError(err) - } - ctx.PackageManager = pm - } - ctx.Hardware = ctx.PackageManager.GetPackages() - return nil -} diff --git a/i18n/errors.go b/i18n/errors.go deleted file mode 100644 index b3617800..00000000 --- a/i18n/errors.go +++ /dev/null @@ -1,31 +0,0 @@ -package i18n - -import "github.com/arduino/arduino-builder/constants" -import "github.com/go-errors/errors" -import "os" - -func ErrorfWithLogger(logger Logger, format string, a ...interface{}) *errors.Error { - if logger.Name() == "machine" { - logger.Fprintln(os.Stderr, constants.LOG_LEVEL_ERROR, format, a...) - return errors.Errorf("") - } - return errors.Errorf(Format(format, a...)) -} - -func WrapError(err error) error { - if err == nil { - return nil - } - return errors.Wrap(err, 0) -} - -func UnwrapError(err error) error { - // Perhaps go-errors can do this already in later versions? - // See https://github.com/go-errors/errors/issues/14 - switch e := err.(type) { - case *errors.Error: - return e.Err - default: - return err - } -} diff --git a/i18n/i18n.go b/i18n/i18n.go deleted file mode 100644 index 2597b377..00000000 --- a/i18n/i18n.go +++ /dev/null @@ -1,274 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package i18n - -import ( - "fmt" - "io" - "net/url" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "sync" -) - -var PLACEHOLDER = regexp.MustCompile("{(\\d)}") - -type Logger interface { - Fprintln(w io.Writer, level string, format string, a ...interface{}) - UnformattedFprintln(w io.Writer, s string) - UnformattedWrite(w io.Writer, data []byte) - Println(level string, format string, a ...interface{}) - Name() string - Flush() string -} - -type LoggerToCustomStreams struct { - Stdout io.Writer - Stderr io.Writer -} - -func (s LoggerToCustomStreams) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - target := s.Stdout - if w == os.Stderr { - target = s.Stderr - } - fmt.Fprintln(target, Format(format, a...)) -} - -func (s LoggerToCustomStreams) UnformattedFprintln(w io.Writer, str string) { - target := s.Stdout - if w == os.Stderr { - target = s.Stderr - } - fmt.Fprintln(target, str) -} - -func (s LoggerToCustomStreams) UnformattedWrite(w io.Writer, data []byte) { - target := s.Stdout - if w == os.Stderr { - target = s.Stderr - } - target.Write(data) -} - -func (s LoggerToCustomStreams) Println(level string, format string, a ...interface{}) { - s.Fprintln(nil, level, format, a...) -} - -func (s LoggerToCustomStreams) Flush() string { - return "" -} - -func (s LoggerToCustomStreams) Name() string { - return "LoggerToCustomStreams" -} - -type NoopLogger struct{} - -func (s NoopLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) {} - -func (s NoopLogger) UnformattedFprintln(w io.Writer, str string) {} - -func (s NoopLogger) UnformattedWrite(w io.Writer, data []byte) {} - -func (s NoopLogger) Println(level string, format string, a ...interface{}) {} - -func (s NoopLogger) Flush() string { - return "" -} - -func (s NoopLogger) Name() string { - return "noop" -} - -type AccumulatorLogger struct { - Buffer *[]string -} - -func (s AccumulatorLogger) Fprintln(w io.Writer, level string, format string, a ...interface{}) { - *s.Buffer = append(*s.Buffer, Format(format, a...)) -} - -func (s AccumulatorLogger) UnformattedFprintln(w io.Writer, str string) { - *s.Buffer = append(*s.Buffer, str) -} - -func (s AccumulatorLogger) UnformattedWrite(w io.Writer, data []byte) { - *s.Buffer = append(*s.Buffer, string(data)) -} - -func (s AccumulatorLogger) Println(level string, format string, a ...interface{}) { - s.Fprintln(nil, level, format, a...) -} - -func (s AccumulatorLogger) Flush() string { - str := strings.Join(*s.Buffer, "\n") - *s.Buffer = (*s.Buffer)[0:0] - return str -} - -func (s AccumulatorLogger) Name() string { - return "accumulator" -} - -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...) -} - -func (s HumanTagsLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s HumanTagsLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func (s HumanTagsLogger) Flush() string { - return "" -} - -func (s HumanTagsLogger) Name() string { - return "humantags" -} - -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...) -} - -func (s HumanLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s HumanLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func (s HumanLogger) Flush() string { - return "" -} - -func (s HumanLogger) Name() string { - return "human" -} - -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 (s MachineLogger) UnformattedFprintln(w io.Writer, str string) { - fprintln(w, str) -} - -func (s MachineLogger) Flush() string { - return "" -} - -func (s MachineLogger) Name() string { - return "machine" -} - -func (s MachineLogger) UnformattedWrite(w io.Writer, data []byte) { - write(w, data) -} - -func printMachineFormattedLogLine(w io.Writer, level string, format string, a []interface{}) { - a = append([]interface{}(nil), a...) - for idx, value := range a { - typeof := reflect.Indirect(reflect.ValueOf(value)).Kind() - if typeof == reflect.String { - a[idx] = url.QueryEscape(value.(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 write(w io.Writer, data []byte) { - lock.Lock() - defer lock.Unlock() - w.Write(data) -} - -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/includes_finder_with_regexp.go b/includes_finder_with_regexp.go deleted file mode 100644 index abfe7635..00000000 --- a/includes_finder_with_regexp.go +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/types" - "regexp" - "strings" -) - -var INCLUDE_REGEXP = regexp.MustCompile("(?ms)^\\s*#[ \t]*include\\s*[<\"](\\S+)[\">]") - -func IncludesFinderWithRegExp(ctx *types.Context, source string) string { - match := INCLUDE_REGEXP.FindStringSubmatch(source) - if match != nil { - return strings.TrimSpace(match[1]) - } else { - return findIncludeForOldCompilers(source) - } -} - -func findIncludeForOldCompilers(source string) string { - lines := strings.Split(source, "\n") - for _, line := range lines { - splittedLine := strings.Split(line, ":") - for i, _ := range splittedLine { - if strings.Contains(splittedLine[i], "fatal error") { - return strings.TrimSpace(splittedLine[i+1]) - } - } - } - return "" -} diff --git a/libraries_loader.go b/libraries_loader.go deleted file mode 100644 index 37dc3820..00000000 --- a/libraries_loader.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/libraries" - "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" - "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" -) - -type LibrariesLoader struct{} - -func (s *LibrariesLoader) Run(ctx *types.Context) error { - lm := librariesmanager.NewLibraryManager(nil, nil) - ctx.LibrariesManager = lm - - builtInLibrariesFolders := ctx.BuiltInLibrariesDirs - if err := builtInLibrariesFolders.ToAbs(); err != nil { - return i18n.WrapError(err) - } - for _, folder := range builtInLibrariesFolders { - lm.AddLibrariesDir(folder, libraries.IDEBuiltIn) - } - - debugLevel := ctx.DebugLevel - logger := ctx.GetLogger() - - actualPlatform := ctx.ActualPlatform - platform := ctx.TargetPlatform - if actualPlatform != platform { - lm.AddPlatformReleaseLibrariesDir(actualPlatform, libraries.ReferencedPlatformBuiltIn) - } - lm.AddPlatformReleaseLibrariesDir(platform, libraries.PlatformBuiltIn) - - librariesFolders := ctx.OtherLibrariesDirs - if err := librariesFolders.ToAbs(); err != nil { - return i18n.WrapError(err) - } - for _, folder := range librariesFolders { - lm.AddLibrariesDir(folder, libraries.Sketchbook) - } - - if err := lm.RescanLibraries(); err != nil { - return i18n.WrapError(err) - } - - if debugLevel > 0 { - for _, lib := range lm.Libraries { - for _, libAlt := range lib.Alternatives { - warnings, err := libAlt.Lint() - if err != nil { - return i18n.WrapError(err) - } - for _, warning := range warnings { - logger.Fprintln(os.Stdout, "warn", warning) - } - } - } - } - - resolver := librariesresolver.NewCppResolver() - if err := resolver.ScanFromLibrariesManager(lm); err != nil { - return i18n.WrapError(err) - } - ctx.LibrariesResolver = resolver - - return nil -} diff --git a/load_previous_build_options.go b/load_previous_build_options.go deleted file mode 100644 index 2c22d2e8..00000000 --- a/load_previous_build_options.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type LoadPreviousBuildOptionsMap struct{} - -func (s *LoadPreviousBuildOptionsMap) Run(ctx *types.Context) error { - buildOptionsFile := ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE) - - if buildOptionsFile.NotExist() { - return nil - } - - bytes, err := buildOptionsFile.ReadFile() - if err != nil { - return i18n.WrapError(err) - } - - ctx.BuildOptionsJsonPrevious = string(bytes) - return nil -} diff --git a/load_vid_pid_specific_properties.go b/load_vid_pid_specific_properties.go deleted file mode 100644 index ea59c60e..00000000 --- a/load_vid_pid_specific_properties.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "strconv" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-orderedmap" -) - -type LoadVIDPIDSpecificProperties struct{} - -func (s *LoadVIDPIDSpecificProperties) Run(ctx *types.Context) error { - if ctx.USBVidPid == "" { - return nil - } - - vidPid := ctx.USBVidPid - vidPid = strings.ToLower(vidPid) - vidPidParts := strings.Split(vidPid, "_") - vid := vidPidParts[0] - pid := vidPidParts[1] - - buildProperties := ctx.BuildProperties - VIDPIDIndex, err := findVIDPIDIndex(buildProperties, vid, pid) - if err != nil { - return i18n.WrapError(err) - } - if VIDPIDIndex < 0 { - return nil - } - - vidPidSpecificProperties := buildProperties.SubTree(constants.BUILD_PROPERTIES_VID).SubTree(strconv.Itoa(VIDPIDIndex)) - buildProperties.Merge(vidPidSpecificProperties) - - return nil -} - -func findVIDPIDIndex(buildProperties *properties.Map, vid, pid string) (int, error) { - for key, value := range buildProperties.SubTree(constants.BUILD_PROPERTIES_VID).AsMap() { - if !strings.Contains(key, ".") { - if vid == strings.ToLower(value) && pid == strings.ToLower(buildProperties.Get(constants.BUILD_PROPERTIES_PID+"."+key)) { - return strconv.Atoi(key) - } - } - } - - return -1, nil -} diff --git a/arduino-builder/main.go b/main.go similarity index 100% rename from arduino-builder/main.go rename to main.go diff --git a/merge_sketch_with_bootloader.go b/merge_sketch_with_bootloader.go deleted file mode 100644 index 0fcc2488..00000000 --- a/merge_sketch_with_bootloader.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "strings" - - "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type MergeSketchWithBootloader struct{} - -func (s *MergeSketchWithBootloader) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - if !buildProperties.ContainsKey(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) && !buildProperties.ContainsKey(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) { - return nil - } - - buildPath := ctx.BuildPath - sketch := ctx.Sketch - sketchFileName := sketch.MainFile.Name.Base() - logger := ctx.GetLogger() - - sketchInBuildPath := buildPath.Join(sketchFileName + ".hex") - sketchInSubfolder := buildPath.Join(constants.FOLDER_SKETCH, sketchFileName+".hex") - - var builtSketchPath *paths.Path - if sketchInBuildPath.Exist() { - builtSketchPath = sketchInBuildPath - } else if sketchInSubfolder.Exist() { - builtSketchPath = sketchInSubfolder - } else { - return nil - } - - bootloader := constants.EMPTY_STRING - if bootloaderNoBlink, ok := buildProperties.GetOk(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK); ok { - bootloader = bootloaderNoBlink - } else { - bootloader = buildProperties.Get(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) - } - bootloader = buildProperties.ExpandPropsInString(bootloader) - - bootloaderPath := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH).Join(constants.FOLDER_BOOTLOADERS, bootloader) - if bootloaderPath.NotExist() { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_BOOTLOADER_FILE_MISSING, bootloaderPath) - return nil - } - - mergedSketchPath := builtSketchPath.Parent().Join(sketchFileName + ".with_bootloader.hex") - - return merge(builtSketchPath, bootloaderPath, mergedSketchPath) -} - -func hexLineOnlyContainsFF(line string) bool { - //:206FE000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFB1 - if len(line) <= 11 { - return false - } - byteArray := []byte(line) - for _, char := range byteArray[9:(len(byteArray) - 2)] { - if char != 'F' { - return false - } - } - return true -} - -func extractActualBootloader(bootloader []string) []string { - - var realBootloader []string - - // skip until we find a line full of FFFFFF (except address and checksum) - for i, row := range bootloader { - if hexLineOnlyContainsFF(row) { - realBootloader = bootloader[i:len(bootloader)] - break - } - } - - // drop all "empty" lines - for i, row := range realBootloader { - if !hexLineOnlyContainsFF(row) { - realBootloader = realBootloader[i:len(realBootloader)] - break - } - } - - if len(realBootloader) == 0 { - // we didn't find any line full of FFFF, thus it's a standalone bootloader - realBootloader = bootloader - } - - return realBootloader -} - -func merge(builtSketchPath, bootloaderPath, mergedSketchPath *paths.Path) error { - sketch, err := builtSketchPath.ReadFileAsLines() - if err != nil { - return i18n.WrapError(err) - } - sketch = sketch[:len(sketch)-2] - - bootloader, err := bootloaderPath.ReadFileAsLines() - if err != nil { - return i18n.WrapError(err) - } - - realBootloader := extractActualBootloader(bootloader) - - for _, row := range realBootloader { - sketch = append(sketch, row) - } - - return mergedSketchPath.WriteFile([]byte(strings.Join(sketch, "\n"))) -} diff --git a/phases/core_builder.go b/phases/core_builder.go deleted file mode 100644 index d3220a1f..00000000 --- a/phases/core_builder.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "os" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" -) - -type CoreBuilder struct{} - -func (s *CoreBuilder) Run(ctx *types.Context) error { - coreBuildPath := ctx.CoreBuildPath - coreBuildCachePath := ctx.CoreBuildCachePath - buildProperties := ctx.BuildProperties - - if err := coreBuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - if coreBuildCachePath != nil { - if err := coreBuildCachePath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - } - - archiveFile, objectFiles, err := compileCore(ctx, coreBuildPath, coreBuildCachePath, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - ctx.CoreArchiveFilePath = archiveFile - ctx.CoreObjectsFiles = objectFiles - - return nil -} - -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(constants.BUILD_PROPERTIES_BUILD_CORE_PATH) - variantFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_VARIANT_PATH) - - targetCoreFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH) - - includes := []string{} - includes = append(includes, coreFolder.String()) - if variantFolder != nil { - includes = append(includes, variantFolder.String()) - } - includes = utils.Map(includes, utils.WrapWithHyphenI) - - var err error - - variantObjectFiles := paths.NewPathList() - if variantFolder != nil { - variantObjectFiles, err = builder_utils.CompileFiles(ctx, variantFolder, true, buildPath, buildProperties, includes) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - } - - // Recreate the archive if ANY of the core files (including platform.txt) has changed - realCoreFolder := coreFolder.Parent().Parent() - - var targetArchivedCore *paths.Path - if buildCachePath != nil { - archivedCoreName := builder_utils.GetCachedCoreArchiveFileName(buildProperties.Get(constants.BUILD_PROPERTIES_FQBN), realCoreFolder) - targetArchivedCore = buildCachePath.Join(archivedCoreName) - canUseArchivedCore := !builder_utils.CoreOrReferencedCoreHasChanged(realCoreFolder, targetCoreFolder, targetArchivedCore) - - if canUseArchivedCore { - // use archived core - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, "Using precompiled core: {0}", targetArchivedCore) - } - return targetArchivedCore, variantObjectFiles, nil - } - } - - coreObjectFiles, err := builder_utils.CompileFiles(ctx, coreFolder, true, buildPath, buildProperties, includes) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - archiveFile, err := builder_utils.ArchiveCompiledFiles(ctx, buildPath, paths.New("core.a"), coreObjectFiles, buildProperties) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - // archive core.a - if targetArchivedCore != nil { - err := archiveFile.CopyTo(targetArchivedCore) - if ctx.Verbose { - if err == nil { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_ARCHIVING_CORE_CACHE, targetArchivedCore) - } else if os.IsNotExist(err) { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_CORE_CACHE_UNAVAILABLE, ctx.ActualPlatform) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_ERROR_ARCHIVING_CORE_CACHE, targetArchivedCore, err) - } - } - } - - return archiveFile, variantObjectFiles, nil -} diff --git a/phases/libraries_builder.go b/phases/libraries_builder.go deleted file mode 100644 index d9a151ca..00000000 --- a/phases/libraries_builder.go +++ /dev/null @@ -1,179 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "path/filepath" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/arduino-cli/arduino/libraries" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" -) - -var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC = map[string]bool{".a": true} -var PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_DYNAMIC = map[string]bool{".so": true} - -type LibrariesBuilder struct{} - -func (s *LibrariesBuilder) Run(ctx *types.Context) error { - librariesBuildPath := ctx.LibrariesBuildPath - buildProperties := ctx.BuildProperties - includes := utils.Map(ctx.IncludeFolders.AsStrings(), utils.WrapWithHyphenI) - libs := ctx.ImportedLibraries - - if err := librariesBuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - objectFiles, err := compileLibraries(ctx, libs, librariesBuildPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - - ctx.LibrariesObjectFiles = objectFiles - - // Search for precompiled libraries - fixLDFLAGforPrecompiledLibraries(ctx, libs) - - return nil -} - -func fixLDFLAGforPrecompiledLibraries(ctx *types.Context, libs libraries.List) error { - - for _, library := range libs { - if library.Precompiled { - // add library src path to compiler.c.elf.extra_flags - // use library.Name as lib name and srcPath/{mcpu} as location - mcu := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) - path := library.SourceDir.Join(mcu).String() - // find all library names in the folder and prepend -l - filePaths := []string{} - libs_cmd := library.LDflags + " " - extensions := func(ext string) bool { return PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_DYNAMIC[ext] } - utils.FindFilesInFolder(&filePaths, path, extensions, true) - for _, lib := range filePaths { - name := strings.TrimSuffix(filepath.Base(lib), filepath.Ext(lib)) - // strip "lib" first occurrence - name = strings.Replace(name, "lib", "", 1) - libs_cmd += "-l" + name + " " - } - - currLDFlags := ctx.BuildProperties.Get(constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS) - ctx.BuildProperties.Set(constants.BUILD_PROPERTIES_COMPILER_LIBRARIES_LDFLAGS, currLDFlags+"\"-L"+path+"\" "+libs_cmd+" ") - } - } - return nil -} - -func compileLibraries(ctx *types.Context, libraries libraries.List, buildPath *paths.Path, buildProperties *properties.Map, includes []string) (paths.PathList, error) { - objectFiles := paths.NewPathList() - for _, library := range libraries { - libraryObjectFiles, err := compileLibrary(ctx, library, buildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles = append(objectFiles, libraryObjectFiles...) - } - - return objectFiles, nil -} - -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, "Compiling library \"{0}\"", library.Name) - } - libraryBuildPath := buildPath.Join(library.Name) - - if err := libraryBuildPath.MkdirAll(); err != nil { - return nil, i18n.WrapError(err) - } - - objectFiles := paths.NewPathList() - - if library.Precompiled { - // search for files with PRECOMPILED_LIBRARIES_VALID_EXTENSIONS - extensions := func(ext string) bool { return PRECOMPILED_LIBRARIES_VALID_EXTENSIONS_STATIC[ext] } - - filePaths := []string{} - mcu := buildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) - err := utils.FindFilesInFolder(&filePaths, library.SourceDir.Join(mcu).String(), extensions, true) - if err != nil { - return nil, i18n.WrapError(err) - } - for _, path := range filePaths { - if strings.Contains(filepath.Base(path), library.RealName) { - objectFiles.Add(paths.New(path)) - } - } - } - - if library.Layout == libraries.RecursiveLayout { - libObjectFiles, err := builder_utils.CompileFilesRecursive(ctx, library.SourceDir, libraryBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - if library.DotALinkage { - archiveFile, err := builder_utils.ArchiveCompiledFiles(ctx, libraryBuildPath, paths.New(library.Name+".a"), libObjectFiles, buildProperties) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles.Add(archiveFile) - } else { - objectFiles.AddAll(libObjectFiles) - } - } else { - if library.UtilityDir != nil { - includes = append(includes, utils.WrapWithHyphenI(library.UtilityDir.String())) - } - libObjectFiles, err := builder_utils.CompileFiles(ctx, library.SourceDir, false, libraryBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles.AddAll(libObjectFiles) - - if library.UtilityDir != nil { - utilityBuildPath := libraryBuildPath.Join("utility") - utilityObjectFiles, err := builder_utils.CompileFiles(ctx, library.UtilityDir, false, utilityBuildPath, buildProperties, includes) - if err != nil { - return nil, i18n.WrapError(err) - } - objectFiles.AddAll(utilityObjectFiles) - } - } - - return objectFiles, nil -} diff --git a/phases/linker.go b/phases/linker.go deleted file mode 100644 index e3e140ae..00000000 --- a/phases/linker.go +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" -) - -type Linker struct{} - -func (s *Linker) Run(ctx *types.Context) error { - objectFilesSketch := ctx.SketchObjectFiles - objectFilesLibraries := ctx.LibrariesObjectFiles - objectFilesCore := ctx.CoreObjectsFiles - - objectFiles := paths.NewPathList() - objectFiles.AddAll(objectFilesSketch) - objectFiles.AddAll(objectFilesLibraries) - objectFiles.AddAll(objectFilesCore) - - coreArchiveFilePath := ctx.CoreArchiveFilePath - buildPath := ctx.BuildPath - coreDotARelPath, err := buildPath.RelTo(coreArchiveFilePath) - if err != nil { - return i18n.WrapError(err) - } - - buildProperties := ctx.BuildProperties - - err = link(ctx, objectFiles, coreDotARelPath, coreArchiveFilePath, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func link(ctx *types.Context, objectFiles paths.PathList, coreDotARelPath *paths.Path, coreArchiveFilePath *paths.Path, buildProperties *properties.Map) error { - optRelax := addRelaxTrickIfATMEGA2560(buildProperties) - - quotedObjectFiles := utils.Map(objectFiles.AsStrings(), wrapWithDoubleQuotes) - objectFileList := strings.Join(quotedObjectFiles, constants.SPACE) - - properties := buildProperties.Clone() - properties.Set(constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_C_ELF_FLAGS)+optRelax) - properties.Set(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS, properties.Get(constants.BUILD_PROPERTIES_COMPILER_WARNING_FLAGS+"."+ctx.WarningsLevel)) - properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE, coreDotARelPath.String()) - properties.Set(constants.BUILD_PROPERTIES_ARCHIVE_FILE_PATH, coreArchiveFilePath.String()) - properties.Set(constants.BUILD_PROPERTIES_OBJECT_FILES, objectFileList) - - _, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_C_COMBINE_PATTERN, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - return err -} - -func wrapWithDoubleQuotes(value string) string { - return "\"" + value + "\"" -} - -func addRelaxTrickIfATMEGA2560(buildProperties *properties.Map) string { - if buildProperties.Get(constants.BUILD_PROPERTIES_BUILD_MCU) == "atmega2560" { - return ",--relax" - } - return constants.EMPTY_STRING -} diff --git a/phases/sizer.go b/phases/sizer.go deleted file mode 100644 index 04aa161d..00000000 --- a/phases/sizer.go +++ /dev/null @@ -1,182 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2016 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "errors" - "regexp" - "strconv" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-properties-orderedmap" -) - -type Sizer struct { - SketchError bool -} - -func (s *Sizer) Run(ctx *types.Context) error { - - if s.SketchError { - return nil - } - - buildProperties := ctx.BuildProperties - - err := checkSize(ctx, buildProperties) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -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)) - - maxTextSizeString := properties.Get(constants.PROPERTY_UPLOAD_MAX_SIZE) - maxDataSizeString := properties.Get(constants.PROPERTY_UPLOAD_MAX_DATA_SIZE) - - if maxTextSizeString == "" { - return nil - } - - maxTextSize, err := strconv.Atoi(maxTextSizeString) - if err != nil { - return err - } - - maxDataSize := -1 - if maxDataSizeString != "" { - maxDataSize, err = strconv.Atoi(maxDataSizeString) - if err != nil { - return err - } - } - - textSize, dataSize, _, err := execSizeRecipe(ctx, properties) - if err != nil { - logger.Println(constants.LOG_LEVEL_WARN, constants.MSG_SIZER_ERROR_NO_RULE) - return nil - } - - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_TEXT_FULL, strconv.Itoa(textSize), strconv.Itoa(maxTextSize), strconv.Itoa(textSize*100/maxTextSize)) - if dataSize >= 0 { - if maxDataSize > 0 { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_DATA_FULL, strconv.Itoa(dataSize), strconv.Itoa(maxDataSize), strconv.Itoa(dataSize*100/maxDataSize), strconv.Itoa(maxDataSize-dataSize)) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_SIZER_DATA, strconv.Itoa(dataSize)) - } - } - - if textSize > maxTextSize { - logger.Println(constants.LOG_LEVEL_ERROR, constants.MSG_SIZER_TEXT_TOO_BIG) - return errors.New("") - } - - if maxDataSize > 0 && dataSize > maxDataSize { - logger.Println(constants.LOG_LEVEL_ERROR, constants.MSG_SIZER_DATA_TOO_BIG) - return errors.New("") - } - - if properties.Get(constants.PROPERTY_WARN_DATA_PERCENT) != "" { - warnDataPercentage, err := strconv.Atoi(properties.Get(constants.PROPERTY_WARN_DATA_PERCENT)) - if err != nil { - return err - } - if maxDataSize > 0 && dataSize > maxDataSize*warnDataPercentage/100 { - logger.Println(constants.LOG_LEVEL_WARN, constants.MSG_SIZER_LOW_MEMORY) - } - } - - return nil -} - -func execSizeRecipe(ctx *types.Context, properties *properties.Map) (textSize int, dataSize int, eepromSize int, resErr error) { - out, _, err := builder_utils.ExecRecipe(ctx, properties, constants.RECIPE_SIZE_PATTERN, false /* stdout */, utils.Capture /* stderr */, utils.Show) - if err != nil { - resErr = errors.New("Error while determining sketch size: " + err.Error()) - return - } - - // force multiline match prepending "(?m)" to the actual regexp - // return an error if RECIPE_SIZE_REGEXP doesn't exist - - textSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP), out) - if err != nil { - resErr = errors.New("Invalid size regexp: " + err.Error()) - return - } - if textSize == -1 { - resErr = errors.New("Missing size regexp") - return - } - - dataSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP_DATA), out) - if err != nil { - resErr = errors.New("Invalid data size regexp: " + err.Error()) - return - } - - eepromSize, err = computeSize(properties.Get(constants.RECIPE_SIZE_REGEXP_EEPROM), out) - if err != nil { - resErr = errors.New("Invalid eeprom size regexp: " + err.Error()) - return - } - - return -} - -func computeSize(re string, output []byte) (int, error) { - if re == "" { - return -1, nil - } - r, err := regexp.Compile("(?m)" + re) - if err != nil { - return -1, err - } - result := r.FindAllSubmatch(output, -1) - size := 0 - for _, b := range result { - for _, c := range b { - if res, err := strconv.Atoi(string(c)); err == nil { - size += res - } - } - } - return size, nil -} diff --git a/phases/sizer_test.go b/phases/sizer_test.go deleted file mode 100644 index 3f0f704f..00000000 --- a/phases/sizer_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2016 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestSizerWithAVRData(t *testing.T) { - output := []byte(`/tmp/test597119152/sketch.ino.elf : -section size addr -.data 36 8388864 -.text 3966 0 -.bss 112 8388900 -.comment 17 0 -.debug_aranges 704 0 -.debug_info 21084 0 -.debug_abbrev 4704 0 -.debug_line 5456 0 -.debug_frame 1964 0 -.debug_str 8251 0 -.debug_loc 7747 0 -.debug_ranges 856 0 -Total 54897 -`) - - size, err := computeSize(`^(?:\.text|\.data|\.bootloader)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 4002, size) - - size, err = computeSize(`^(?:\.data|\.bss|\.noinit)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 148, size) - - size, err = computeSize(`^(?:\.eeprom)\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 0, size) -} - -func TestSizerWithSAMDData(t *testing.T) { - output := []byte(`/tmp/test737785204/sketch_usbhost.ino.elf : -section size addr -.text 8076 8192 -.data 152 536870912 -.bss 1984 536871064 -.ARM.attributes 40 0 -.comment 128 0 -.debug_info 178841 0 -.debug_abbrev 14968 0 -.debug_aranges 2080 0 -.debug_ranges 3840 0 -.debug_line 26068 0 -.debug_str 55489 0 -.debug_frame 5036 0 -.debug_loc 20978 0 -Total 317680 -`) - - size, err := computeSize(`\.text\s+([0-9]+).*`, output) - require.NoError(t, err) - require.Equal(t, 8076, size) -} - -func TestSizerEmptyRegexpReturnsMinusOne(t *testing.T) { - size, err := computeSize(``, []byte(`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)) - require.NoError(t, err) - require.Equal(t, -1, size) -} - -func TestSizerWithInvalidRegexp(t *testing.T) { - _, err := computeSize(`[xx`, []byte(`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`)) - require.Error(t, err) -} diff --git a/phases/sketch_builder.go b/phases/sketch_builder.go deleted file mode 100644 index 55c88e50..00000000 --- a/phases/sketch_builder.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package phases - -import ( - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type SketchBuilder struct{} - -func (s *SketchBuilder) Run(ctx *types.Context) error { - sketchBuildPath := ctx.SketchBuildPath - buildProperties := ctx.BuildProperties - includes := utils.Map(ctx.IncludeFolders.AsStrings(), utils.WrapWithHyphenI) - - if err := sketchBuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - objectFiles, err := builder_utils.CompileFiles(ctx, sketchBuildPath, false, sketchBuildPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - - // The "src/" subdirectory of a sketch is compiled recursively - sketchSrcPath := sketchBuildPath.Join(constants.SKETCH_FOLDER_SRC) - if sketchSrcPath.IsDir() { - srcObjectFiles, err := builder_utils.CompileFiles(ctx, sketchSrcPath, true, sketchSrcPath, buildProperties, includes) - if err != nil { - return i18n.WrapError(err) - } - objectFiles.AddAll(srcObjectFiles) - } - - ctx.SketchObjectFiles = objectFiles - - return nil -} diff --git a/platform_keys_rewrite_loader.go b/platform_keys_rewrite_loader.go deleted file mode 100644 index c4f90a63..00000000 --- a/platform_keys_rewrite_loader.go +++ /dev/null @@ -1,109 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "sort" - "strconv" - "strings" - - "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-orderedmap" -) - -type PlatformKeysRewriteLoader struct{} - -func (s *PlatformKeysRewriteLoader) Run(ctx *types.Context) error { - folders := ctx.HardwareDirs - - platformKeysRewriteTxtPath, err := findPlatformKeysRewriteTxt(folders) - if err != nil { - return i18n.WrapError(err) - } - if platformKeysRewriteTxtPath == nil { - return nil - } - - platformKeysRewrite := types.PlatforKeysRewrite{} - platformKeysRewrite.Rewrites = []types.PlatforKeyRewrite{} - - txt, err := properties.LoadFromPath(platformKeysRewriteTxtPath) - if err != nil { - return i18n.WrapError(err) - } - keys := txt.Keys() - sort.Strings(keys) - - for _, key := range keys { - keyParts := strings.Split(key, ".") - if keyParts[0] == constants.PLATFORM_REWRITE_OLD { - index, err := strconv.Atoi(keyParts[1]) - if err != nil { - return i18n.WrapError(err) - } - rewriteKey := strings.Join(keyParts[2:], ".") - oldValue := txt.Get(key) - newValue := txt.Get(constants.PLATFORM_REWRITE_NEW + "." + strings.Join(keyParts[1:], ".")) - platformKeyRewrite := types.PlatforKeyRewrite{Key: rewriteKey, OldValue: oldValue, NewValue: newValue} - platformKeysRewrite.Rewrites = growSliceOfRewrites(platformKeysRewrite.Rewrites, index) - platformKeysRewrite.Rewrites[index] = platformKeyRewrite - } - } - - ctx.PlatformKeyRewrites = platformKeysRewrite - - return nil -} - -func findPlatformKeysRewriteTxt(folders paths.PathList) (*paths.Path, error) { - for _, folder := range folders { - txtPath := folder.Join(constants.FILE_PLATFORM_KEYS_REWRITE_TXT) - if exist, err := txtPath.ExistCheck(); exist { - return txtPath, nil - } else if err != nil { - return nil, i18n.WrapError(err) - } - } - - return nil, nil -} - -func growSliceOfRewrites(originalSlice []types.PlatforKeyRewrite, maxIndex int) []types.PlatforKeyRewrite { - if cap(originalSlice) > maxIndex { - return originalSlice - } - newSlice := make([]types.PlatforKeyRewrite, maxIndex+1) - copy(newSlice, originalSlice) - return newSlice -} diff --git a/preprocess_sketch.go b/preprocess_sketch.go deleted file mode 100644 index c509b8d1..00000000 --- a/preprocess_sketch.go +++ /dev/null @@ -1,162 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "errors" - "fmt" - "os/exec" - "path/filepath" - "runtime" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - properties "github.com/arduino/go-properties-orderedmap" -) - -// ArduinoPreprocessorProperties are the platform properties needed to run arduino-preprocessor -var ArduinoPreprocessorProperties = properties.NewFromHashmap(map[string]string{ - // Ctags - "tools.arduino-preprocessor.path": "{runtime.tools.arduino-preprocessor.path}", - "tools.arduino-preprocessor.cmd.path": "{path}/arduino-preprocessor", - "tools.arduino-preprocessor.pattern": `"{cmd.path}" "{source_file}" "{codecomplete}" -- -std=gnu++11`, - - "preproc.macros.flags": "-w -x c++ -E -CC", -}) - -type PreprocessSketchArduino struct{} - -func (s *PreprocessSketchArduino) Run(ctx *types.Context) error { - sourceFile := ctx.SketchBuildPath.Join(ctx.Sketch.MainFile.Name.Base() + ".cpp") - commands := []types.Command{ - &ArduinoPreprocessorRunner{}, - } - - if err := ctx.PreprocPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - if ctx.CodeCompleteAt != "" { - commands = append(commands, &OutputCodeCompletions{}) - } else { - commands = append(commands, &SketchSaver{}) - } - - GCCPreprocRunner(ctx, sourceFile, ctx.PreprocPath.Join(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E), ctx.IncludeFolders) - - for _, command := range commands { - PrintRingNameIfDebug(ctx, command) - err := command.Run(ctx) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -type ArduinoPreprocessorRunner struct{} - -func (s *ArduinoPreprocessorRunner) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - targetFilePath := ctx.PreprocPath.Join(constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E) - logger := ctx.GetLogger() - - properties := buildProperties.Clone() - toolProps := buildProperties.SubTree("tools").SubTree("arduino-preprocessor") - properties.Merge(toolProps) - properties.SetPath(constants.BUILD_PROPERTIES_SOURCE_FILE, targetFilePath) - if ctx.CodeCompleteAt != "" { - if runtime.GOOS == "windows" { - //use relative filepath to avoid ":" escaping - splt := strings.Split(ctx.CodeCompleteAt, ":") - if len(splt) == 3 { - //all right, do nothing - } else { - splt[1] = filepath.Base(splt[0] + ":" + splt[1]) - ctx.CodeCompleteAt = strings.Join(splt[1:], ":") - } - } - properties.Set("codecomplete", "-output-code-completions="+ctx.CodeCompleteAt) - } else { - properties.Set("codecomplete", "") - } - - pattern := properties.Get(constants.BUILD_PROPERTIES_PATTERN) - if pattern == constants.EMPTY_STRING { - return i18n.ErrorfWithLogger(logger, constants.MSG_PATTERN_MISSING, "arduino-preprocessor") - } - - commandLine := properties.ExpandPropsInString(pattern) - command, err := utils.PrepareCommand(commandLine, logger, "") - if err != nil { - return i18n.WrapError(err) - } - - if runtime.GOOS == "windows" { - // chdir in the uppermost directory to avoid UTF-8 bug in clang (https://github.com/arduino/arduino-preprocessor/issues/2) - command.Dir = filepath.VolumeName(command.Args[0]) + "/" - //command.Args[0], _ = filepath.Rel(command.Dir, command.Args[0]) - } - - verbose := ctx.Verbose - if verbose { - fmt.Println(commandLine) - } - - buf, err := command.Output() - if err != nil { - return errors.New(i18n.WrapError(err).Error() + string(err.(*exec.ExitError).Stderr)) - } - - result := utils.NormalizeUTF8(buf) - - //fmt.Printf("PREPROCESSOR OUTPUT:\n%s\n", output) - if ctx.CodeCompleteAt != "" { - ctx.CodeCompletions = string(result) - } else { - ctx.Source = string(result) - } - return nil -} - -type OutputCodeCompletions struct{} - -func (s *OutputCodeCompletions) Run(ctx *types.Context) error { - if ctx.CodeCompletions == "" { - // we assume it is a json, let's make it compliant at least - ctx.CodeCompletions = "[]" - } - ctx.GetLogger().Println(constants.LOG_LEVEL_INFO, ctx.CodeCompletions) - return nil -} diff --git a/print_preprocessed_source.go b/print_preprocessed_source.go deleted file mode 100644 index b320c127..00000000 --- a/print_preprocessed_source.go +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - - "github.com/arduino/arduino-builder/types" -) - -type PrintPreprocessedSource struct{} - -func (s *PrintPreprocessedSource) Run(ctx *types.Context) error { - if ctx.SourceGccMinusE != "" { - fmt.Println(ctx.SourceGccMinusE) - } - return nil -} diff --git a/print_used_and_not_used_libraries.go b/print_used_and_not_used_libraries.go deleted file mode 100644 index 43ae1c7e..00000000 --- a/print_used_and_not_used_libraries.go +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "time" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" -) - -type PrintUsedAndNotUsedLibraries struct { - // Was there an error while compiling the sketch? - SketchError bool -} - -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 { - return nil - } - - logger := ctx.GetLogger() - libraryResolutionResults := ctx.LibrariesResolutionResults - - for header, libResResult := range libraryResolutionResults { - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_MULTIPLE_LIBS_FOUND_FOR, header) - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_USED, libResResult.Library.InstallDir) - for _, notUsedLibrary := range libResResult.NotUsedLibraries { - logger.Fprintln(os.Stdout, logLevel, constants.MSG_LIBRARIES_NOT_USED, notUsedLibrary.InstallDir) - } - } - - time.Sleep(100 * time.Millisecond) - - return nil -} diff --git a/print_used_libraries_if_verbose.go b/print_used_libraries_if_verbose.go deleted file mode 100644 index 4d8ecb9c..00000000 --- a/print_used_libraries_if_verbose.go +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "time" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-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 { - return nil - } - - for _, library := range ctx.ImportedLibraries { - legacy := "" - if library.IsLegacy { - legacy = constants.MSG_LIB_LEGACY - } - if library.Version.String() == "" { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY, library.Name, library.InstallDir, legacy) - } else { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_LIBRARY_AT_VERSION, library.Name, library.Version, library.InstallDir, legacy) - } - } - - time.Sleep(100 * time.Millisecond) - - return nil -} diff --git a/prototypes_adder.go b/prototypes_adder.go deleted file mode 100644 index 91a7eb63..00000000 --- a/prototypes_adder.go +++ /dev/null @@ -1,120 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "strconv" - "strings" -) - -type PrototypesAdder struct{} - -func (s *PrototypesAdder) Run(ctx *types.Context) error { - debugOutput := ctx.DebugPreprocessor - source := ctx.Source - - source = strings.Replace(source, "\r\n", "\n", -1) - source = strings.Replace(source, "\r", "\n", -1) - - sourceRows := strings.Split(source, "\n") - - firstFunctionLine := ctx.PrototypesLineWhereToInsert - if isFirstFunctionOutsideOfSource(firstFunctionLine, sourceRows) { - return nil - } - - insertionLine := firstFunctionLine + ctx.LineOffset - 1 - firstFunctionChar := len(strings.Join(sourceRows[:insertionLine], "\n")) + 1 - prototypeSection := composePrototypeSection(firstFunctionLine, ctx.Prototypes) - ctx.PrototypesSection = prototypeSection - source = source[:firstFunctionChar] + prototypeSection + source[firstFunctionChar:] - - if debugOutput { - fmt.Println("#PREPROCESSED SOURCE") - prototypesRows := strings.Split(prototypeSection, "\n") - prototypesRows = prototypesRows[:len(prototypesRows)-1] - for i := 0; i < len(sourceRows)+len(prototypesRows); i++ { - if i < insertionLine { - fmt.Printf(" |%s\n", sourceRows[i]) - } else if i < insertionLine+len(prototypesRows) { - fmt.Printf("PRO|%s\n", prototypesRows[i-insertionLine]) - } else { - fmt.Printf(" |%s\n", sourceRows[i-len(prototypesRows)]) - } - } - fmt.Println("#END OF PREPROCESSED SOURCE") - } - ctx.Source = source - - return nil -} - -func composePrototypeSection(line int, prototypes []*types.Prototype) string { - if len(prototypes) == 0 { - return constants.EMPTY_STRING - } - - str := joinPrototypes(prototypes) - str += "\n#line " - str += strconv.Itoa(line) - str += " " + utils.QuoteCppString(prototypes[0].File) - str += "\n" - - return str -} - -func joinPrototypes(prototypes []*types.Prototype) string { - prototypesSlice := []string{} - for _, proto := range prototypes { - if signatureContainsaDefaultArg(proto) { - continue - } - prototypesSlice = append(prototypesSlice, "#line "+strconv.Itoa(proto.Line)+" "+utils.QuoteCppString(proto.File)) - prototypeParts := []string{} - if proto.Modifiers != "" { - prototypeParts = append(prototypeParts, proto.Modifiers) - } - prototypeParts = append(prototypeParts, proto.Prototype) - prototypesSlice = append(prototypesSlice, strings.Join(prototypeParts, " ")) - } - return strings.Join(prototypesSlice, "\n") -} - -func signatureContainsaDefaultArg(proto *types.Prototype) bool { - return strings.Contains(proto.Prototype, "=") -} - -func isFirstFunctionOutsideOfSource(firstFunctionLine int, sourceRows []string) bool { - return firstFunctionLine > len(sourceRows)-1 -} diff --git a/read_file_and_store_in_context.go b/read_file_and_store_in_context.go deleted file mode 100644 index e79e3312..00000000 --- a/read_file_and_store_in_context.go +++ /dev/null @@ -1,52 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" -) - -type ReadFileAndStoreInContext struct { - FileToRead *paths.Path - Target *string -} - -func (s *ReadFileAndStoreInContext) Run(ctx *types.Context) error { - bytes, err := s.FileToRead.ReadFile() - if err != nil { - return i18n.WrapError(err) - } - - *s.Target = string(bytes) - - return nil -} diff --git a/recipe_runner.go b/recipe_runner.go deleted file mode 100644 index 0fd9e6d4..00000000 --- a/recipe_runner.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "sort" - "strings" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - properties "github.com/arduino/go-properties-orderedmap" -) - -type RecipeByPrefixSuffixRunner struct { - Prefix string - Suffix string -} - -func (s *RecipeByPrefixSuffixRunner) Run(ctx *types.Context) error { - logger := ctx.GetLogger() - if ctx.DebugLevel >= 10 { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_DEBUG, constants.MSG_LOOKING_FOR_RECIPES, 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, constants.MSG_RUNNING_RECIPE, recipe) - } - _, _, err := builder_utils.ExecRecipe(ctx, properties, recipe, false /* stdout */, utils.ShowIfVerbose /* stderr */, utils.Show) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil - -} - -func findRecipes(buildProperties *properties.Map, patternPrefix string, patternSuffix string) []string { - var recipes []string - for _, key := range buildProperties.Keys() { - if strings.HasPrefix(key, patternPrefix) && strings.HasSuffix(key, patternSuffix) && buildProperties.Get(key) != "" { - recipes = append(recipes, key) - } - } - - sort.Strings(recipes) - - return recipes -} diff --git a/resolve_library.go b/resolve_library.go deleted file mode 100644 index ef8b4fff..00000000 --- a/resolve_library.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/libraries" -) - -func ResolveLibrary(ctx *types.Context, header string) *libraries.Library { - resolver := ctx.LibrariesResolver - importedLibraries := ctx.ImportedLibraries - logger := ctx.GetLogger() - - candidates := resolver.AlternativesFor(header) - logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf("Alternatives for %s: %s", header, candidates)) - logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf("ResolveLibrary(%s)", header)) - logger.Println(constants.LOG_LEVEL_INFO, fmt.Sprintf(" -> candidates: %s", candidates)) - - if candidates == nil || len(candidates) == 0 { - return nil - } - - for _, candidate := range candidates { - if importedLibraries.Contains(candidate) { - return nil - } - } - - selected := resolver.ResolveFor(header, ctx.TargetPlatform.Platform.Architecture) - if alreadyImported := importedLibraries.FindByName(selected.Name); alreadyImported != nil { - selected = alreadyImported - } - - ctx.LibrariesResolutionResults[header] = types.LibraryResolutionResult{ - Library: selected, - NotUsedLibraries: filterOutLibraryFrom(candidates, selected), - } - - return selected -} - -func filterOutLibraryFrom(libs libraries.List, libraryToRemove *libraries.Library) libraries.List { - filteredOutLibraries := []*libraries.Library{} - for _, lib := range libs { - if lib != libraryToRemove { - filteredOutLibraries = append(filteredOutLibraries, lib) - } - } - return filteredOutLibraries -} diff --git a/rewrite_hardware_keys.go b/rewrite_hardware_keys.go deleted file mode 100644 index 56cf17e5..00000000 --- a/rewrite_hardware_keys.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" -) - -type RewriteHardwareKeys struct{} - -func (s *RewriteHardwareKeys) Run(ctx *types.Context) error { - if ctx.PlatformKeyRewrites.Empty() { - return nil - } - - packages := ctx.Hardware - platformKeysRewrite := ctx.PlatformKeyRewrites - hardwareRewriteResults := ctx.HardwareRewriteResults - - for _, aPackage := range packages.Packages { - for _, platform := range aPackage.Platforms { - for _, platformRelease := range platform.Releases { - if platformRelease.Properties.Get(constants.REWRITING) != constants.REWRITING_DISABLED { - for _, rewrite := range platformKeysRewrite.Rewrites { - if platformRelease.Properties.Get(rewrite.Key) == rewrite.OldValue { - platformRelease.Properties.Set(rewrite.Key, rewrite.NewValue) - appliedRewrites := rewritesAppliedToPlatform(platformRelease, hardwareRewriteResults) - appliedRewrites = append(appliedRewrites, rewrite) - hardwareRewriteResults[platformRelease] = appliedRewrites - } - } - } - } - } - } - - return nil -} - -func rewritesAppliedToPlatform(platform *cores.PlatformRelease, hardwareRewriteResults map[*cores.PlatformRelease][]types.PlatforKeyRewrite) []types.PlatforKeyRewrite { - if hardwareRewriteResults[platform] == nil { - hardwareRewriteResults[platform] = []types.PlatforKeyRewrite{} - } - return hardwareRewriteResults[platform] -} diff --git a/set_custom_build_properties.go b/set_custom_build_properties.go deleted file mode 100644 index 689dddc6..00000000 --- a/set_custom_build_properties.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-orderedmap" -) - -type SetCustomBuildProperties struct{} - -func (s *SetCustomBuildProperties) Run(ctx *types.Context) error { - buildProperties := ctx.BuildProperties - customBuildProperties, err := properties.LoadFromSlice(ctx.CustomBuildProperties) - if err != nil { - return i18n.WrapError(err) - } - - buildProperties.Merge(customBuildProperties) - - return nil -} diff --git a/setup_build_properties.go b/setup_build_properties.go deleted file mode 100644 index e8b0194f..00000000 --- a/setup_build_properties.go +++ /dev/null @@ -1,133 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "path/filepath" - "strconv" - "strings" - "time" - - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/arduino-cli/arduino/cores" - properties "github.com/arduino/go-properties-orderedmap" - timeutils "github.com/arduino/go-timeutils" -) - -type SetupBuildProperties struct{} - -func (s *SetupBuildProperties) Run(ctx *types.Context) error { - packages := ctx.Hardware - - targetPlatform := ctx.TargetPlatform - actualPlatform := ctx.ActualPlatform - targetBoard := ctx.TargetBoard - - buildProperties := properties.NewMap() - buildProperties.Merge(actualPlatform.Properties) - buildProperties.Merge(targetPlatform.Properties) - buildProperties.Merge(targetBoard.Properties) - - if ctx.BuildPath != nil { - buildProperties.SetPath("build.path", ctx.BuildPath) - } - if ctx.Sketch != nil { - buildProperties.Set("build.project_name", ctx.Sketch.MainFile.Name.Base()) - } - buildProperties.Set("build.arch", strings.ToUpper(targetPlatform.Platform.Architecture)) - - // get base folder and use it to populate BUILD_PROPERTIES_RUNTIME_IDE_PATH (arduino and arduino-builder live in the same dir) - ex, err := os.Executable() - exPath := "" - if err == nil { - exPath = filepath.Dir(ex) - } - - buildProperties.Set("build.core", ctx.BuildCore) - buildProperties.SetPath("build.core.path", actualPlatform.InstallDir.Join("cores", buildProperties.Get("build.core"))) - buildProperties.Set("build.system.path", actualPlatform.InstallDir.Join("system").String()) - buildProperties.Set("runtime.platform.path", targetPlatform.InstallDir.String()) - buildProperties.Set("runtime.hardware.path", targetPlatform.InstallDir.Join("..").String()) - buildProperties.Set("runtime.ide.version", ctx.ArduinoAPIVersion) - buildProperties.Set("runtime.ide.path", exPath) - buildProperties.Set("build.fqbn", ctx.FQBN.String()) - buildProperties.Set("ide_version", ctx.ArduinoAPIVersion) - buildProperties.Set("runtime.os", utils.PrettyOSName()) - - variant := buildProperties.Get("build.variant") - if variant == "" { - buildProperties.Set("build.variant.path", "") - } else { - var variantPlatformRelease *cores.PlatformRelease - variantParts := strings.Split(variant, ":") - if len(variantParts) > 1 { - variantPlatform := packages.Packages[variantParts[0]].Platforms[targetPlatform.Platform.Architecture] - variantPlatformRelease = ctx.PackageManager.GetInstalledPlatformRelease(variantPlatform) - variant = variantParts[1] - } else { - variantPlatformRelease = targetPlatform - } - buildProperties.SetPath("build.variant.path", variantPlatformRelease.InstallDir.Join("variants", variant)) - } - - for _, tool := range ctx.AllTools { - buildProperties.SetPath("runtime.tools."+tool.Tool.Name+".path", tool.InstallDir) - buildProperties.SetPath("runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path", tool.InstallDir) - } - for _, tool := range ctx.RequiredTools { - buildProperties.SetPath("runtime.tools."+tool.Tool.Name+".path", tool.InstallDir) - buildProperties.SetPath("runtime.tools."+tool.Tool.Name+"-"+tool.Version.String()+".path", tool.InstallDir) - } - - if !buildProperties.ContainsKey("software") { - buildProperties.Set("software", DEFAULT_SOFTWARE) - } - - if ctx.SketchLocation != nil { - sourcePath, err := ctx.SketchLocation.Abs() - if err != nil { - return err - } - sourcePath = sourcePath.Parent() - buildProperties.SetPath("build.source.path", sourcePath) - } - - now := time.Now() - buildProperties.Set("extra.time.utc", strconv.FormatInt(now.Unix(), 10)) - buildProperties.Set("extra.time.local", strconv.FormatInt(timeutils.LocalUnix(now), 10)) - buildProperties.Set("extra.time.zone", strconv.Itoa(timeutils.TimezoneOffsetNoDST(now))) - buildProperties.Set("extra.time.dst", strconv.Itoa(timeutils.DaylightSavingsOffset(now))) - - ctx.BuildProperties = buildProperties - - return nil -} diff --git a/sketch_loader.go b/sketch_loader.go deleted file mode 100644 index 007519da..00000000 --- a/sketch_loader.go +++ /dev/null @@ -1,137 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "sort" - "strings" - - paths "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type SketchLoader struct{} - -func (s *SketchLoader) Run(ctx *types.Context) error { - if ctx.SketchLocation == nil { - return nil - } - - sketchLocation := ctx.SketchLocation - - sketchLocation, err := sketchLocation.Abs() - if err != nil { - return i18n.WrapError(err) - } - mainSketchStat, err := sketchLocation.Stat() - if err != nil { - return i18n.WrapError(err) - } - if mainSketchStat.IsDir() { - sketchLocation = sketchLocation.Join(mainSketchStat.Name() + ".ino") - } - - ctx.SketchLocation = sketchLocation - - allSketchFilePaths, err := collectAllSketchFiles(sketchLocation.Parent()) - if err != nil { - return i18n.WrapError(err) - } - - logger := ctx.GetLogger() - - if !allSketchFilePaths.Contains(sketchLocation) { - return i18n.ErrorfWithLogger(logger, constants.MSG_CANT_FIND_SKETCH_IN_PATH, sketchLocation, sketchLocation.Parent()) - } - - sketch, err := makeSketch(sketchLocation, allSketchFilePaths, ctx.BuildPath, logger) - if err != nil { - return i18n.WrapError(err) - } - - ctx.SketchLocation = sketchLocation - ctx.Sketch = sketch - - return nil -} - -func collectAllSketchFiles(from *paths.Path) (paths.PathList, error) { - filePaths := []string{} - // Source files in the root are compiled, non-recursively. This - // is the only place where .ino files can be present. - rootExtensions := func(ext string) bool { return MAIN_FILE_VALID_EXTENSIONS[ext] || ADDITIONAL_FILE_VALID_EXTENSIONS[ext] } - err := utils.FindFilesInFolder(&filePaths, from.String(), rootExtensions, true /* recurse */) - if err != nil { - return nil, i18n.WrapError(err) - } - - return paths.NewPathList(filePaths...), i18n.WrapError(err) -} - -func makeSketch(sketchLocation *paths.Path, allSketchFilePaths paths.PathList, buildLocation *paths.Path, logger i18n.Logger) (*types.Sketch, error) { - sketchFilesMap := make(map[string]types.SketchFile) - for _, sketchFilePath := range allSketchFilePaths { - source, err := sketchFilePath.ReadFile() - if err != nil { - return nil, i18n.WrapError(err) - } - sketchFilesMap[sketchFilePath.String()] = types.SketchFile{Name: sketchFilePath, Source: string(source)} - } - - mainFile := sketchFilesMap[sketchLocation.String()] - delete(sketchFilesMap, sketchLocation.String()) - - additionalFiles := []types.SketchFile{} - otherSketchFiles := []types.SketchFile{} - mainFileDir := mainFile.Name.Parent() - for _, sketchFile := range sketchFilesMap { - ext := strings.ToLower(sketchFile.Name.Ext()) - if MAIN_FILE_VALID_EXTENSIONS[ext] { - if sketchFile.Name.Parent().EqualsTo(mainFileDir) { - otherSketchFiles = append(otherSketchFiles, sketchFile) - } - } else if ADDITIONAL_FILE_VALID_EXTENSIONS[ext] { - if buildLocation == nil || !strings.Contains(sketchFile.Name.Parent().String(), buildLocation.String()) { - additionalFiles = append(additionalFiles, sketchFile) - } - } else { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_UNKNOWN_SKETCH_EXT, sketchFile.Name) - } - } - - sort.Sort(types.SketchFileSortByName(additionalFiles)) - sort.Sort(types.SketchFileSortByName(otherSketchFiles)) - - return &types.Sketch{MainFile: mainFile, OtherSketchFiles: otherSketchFiles, AdditionalFiles: additionalFiles}, nil -} diff --git a/sketch_saver.go b/sketch_saver.go deleted file mode 100644 index a4dd3785..00000000 --- a/sketch_saver.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" -) - -type SketchSaver struct{} - -func (s *SketchSaver) Run(ctx *types.Context) error { - sketch := ctx.Sketch - sketchBuildPath := ctx.SketchBuildPath - - if err := sketchBuildPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - - err := sketchBuildPath.Join(sketch.MainFile.Name.Base() + ".cpp").WriteFile([]byte(ctx.Source)) - return i18n.WrapError(err) -} diff --git a/sketch_source_merger.go b/sketch_source_merger.go deleted file mode 100644 index a4166fb9..00000000 --- a/sketch_source_merger.go +++ /dev/null @@ -1,82 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package builder - -import ( - "regexp" - - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" -) - -type SketchSourceMerger struct{} - -func (s *SketchSourceMerger) Run(ctx *types.Context) error { - sketch := ctx.Sketch - - lineOffset := 0 - includeSection := "" - if !sketchIncludesArduinoH(&sketch.MainFile) { - includeSection += "#include \n" - lineOffset++ - } - includeSection += "#line 1 " + utils.QuoteCppString(sketch.MainFile.Name.String()) + "\n" - lineOffset++ - ctx.IncludeSection = includeSection - - source := includeSection - source += addSourceWrappedWithLineDirective(&sketch.MainFile) - lineOffset += 1 - for _, file := range sketch.OtherSketchFiles { - source += addSourceWrappedWithLineDirective(&file) - } - - ctx.LineOffset = lineOffset - ctx.Source = source - - return nil -} - -func sketchIncludesArduinoH(sketch *types.SketchFile) bool { - if matched, err := regexp.MatchString("(?m)^\\s*#\\s*include\\s*[<\"]Arduino\\.h[>\"]", sketch.Source); err != nil { - panic(err) - } else { - return matched - } -} - -func addSourceWrappedWithLineDirective(sketch *types.SketchFile) string { - source := "#line 1 " + utils.QuoteCppString(sketch.Name.String()) + "\n" - source += sketch.Source - source += "\n" - - return source -} diff --git a/store_build_options_map.go b/store_build_options_map.go deleted file mode 100644 index 6cb6d71c..00000000 --- a/store_build_options_map.go +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" -) - -type StoreBuildOptionsMap struct{} - -func (s *StoreBuildOptionsMap) Run(ctx *types.Context) error { - ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE).WriteFile([]byte(ctx.BuildOptionsJson)) - return nil -} diff --git a/target_board_resolver.go b/target_board_resolver.go deleted file mode 100644 index 4b361403..00000000 --- a/target_board_resolver.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-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, "Error resolving FQBN: {0}", err) - } - - targetBoard.Properties = buildProperties // FIXME.... - - core := targetBoard.Properties.Get("build.core") - if core == "" { - core = "arduino" - } - // select the core name in case of "package:core" format - core = core[strings.Index(core, ":")+1:] - - if ctx.Verbose { - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_BOARD, targetBoard.BoardID, targetPlatform.InstallDir) - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_USING_CORE, core, actualPlatform.InstallDir) - } - - ctx.BuildCore = core - ctx.TargetBoard = targetBoard - ctx.TargetPlatform = targetPlatform - ctx.TargetPackage = targetPackage - ctx.ActualPlatform = actualPlatform - return nil -} diff --git a/test/.gitignore b/test/.gitignore deleted file mode 100644 index c49bbb5b..00000000 --- a/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -downloaded_* diff --git a/test/add_additional_entries_to_context_test.go b/test/add_additional_entries_to_context_test.go deleted file mode 100644 index ee904b78..00000000 --- a/test/add_additional_entries_to_context_test.go +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestAddAdditionalEntriesToContextNoBuildPath(t *testing.T) { - ctx := &types.Context{} - - command := builder.AddAdditionalEntriesToContext{} - NoError(t, command.Run(ctx)) - - require.Empty(t, ctx.PreprocPath) - require.Empty(t, ctx.SketchBuildPath) - require.Empty(t, ctx.LibrariesBuildPath) - require.Empty(t, ctx.CoreBuildPath) - - require.NotNil(t, ctx.WarningsLevel) - - require.True(t, ctx.CollectedSourceFiles.Empty()) - - require.Equal(t, 0, len(ctx.LibrariesResolutionResults)) -} - -func TestAddAdditionalEntriesToContextWithBuildPath(t *testing.T) { - ctx := &types.Context{} - ctx.BuildPath = paths.New("folder") - - command := builder.AddAdditionalEntriesToContext{} - NoError(t, command.Run(ctx)) - - require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_PREPROC)), ctx.PreprocPath) - require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_SKETCH)), ctx.SketchBuildPath) - require.Equal(t, Abs(t, paths.New("folder", "libraries")), ctx.LibrariesBuildPath) - require.Equal(t, Abs(t, paths.New("folder", constants.FOLDER_CORE)), ctx.CoreBuildPath) - - require.NotNil(t, ctx.WarningsLevel) - - require.True(t, ctx.CollectedSourceFiles.Empty()) - - require.Equal(t, 0, len(ctx.LibrariesResolutionResults)) -} diff --git a/test/add_build_board_property_if_missing_test.go b/test/add_build_board_property_if_missing_test.go deleted file mode 100644 index 4ef6c097..00000000 --- a/test/add_build_board_property_if_missing_test.go +++ /dev/null @@ -1,109 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" - "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func parseFQBN(t *testing.T, fqbnIn string) *cores.FQBN { - fqbn, err := cores.ParseFQBN(fqbnIn) - require.NoError(t, err) - return fqbn -} - -func TestAddBuildBoardPropertyIfMissing(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega"), - Verbose: true, - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.AddBuildBoardPropertyIfMissing{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.NotNil(t, targetPlatform) - require.NotNil(t, targetPlatform.Platform) - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, "atmega2560", targetBoard.Properties.Get("build.mcu")) - require.Equal(t, "AVR_MYMEGA2560", targetBoard.Properties.Get("build.board")) -} - -func TestAddBuildBoardPropertyIfMissingNotMissing(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega1280"), - Verbose: true, - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.AddBuildBoardPropertyIfMissing{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "mymega", targetBoard.BoardID) - require.Equal(t, "atmega1280", targetBoard.Properties.Get("build.mcu")) - require.Equal(t, "AVR_MYMEGA", targetBoard.Properties.Get("build.board")) -} diff --git a/test/additional_sketch_files_copier_test.go b/test/additional_sketch_files_copier_test.go deleted file mode 100644 index 7656ab34..00000000 --- a/test/additional_sketch_files_copier_test.go +++ /dev/null @@ -1,134 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os" - "sort" - "testing" - "time" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -type ByFileInfoName []os.FileInfo - -func (s ByFileInfoName) Len() int { - return len(s) -} -func (s ByFileInfoName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByFileInfoName) Less(i, j int) bool { - return s[i].Name() < s[j].Name() -} - -func TestCopyOtherFiles(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch1", "sketch.ino"), - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.SketchLoader{}, - &builder.AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - exist, err1 := buildPath.Join(constants.FOLDER_SKETCH, "header.h").ExistCheck() - NoError(t, err1) - require.True(t, exist) - - files, err1 := gohasissues.ReadDir(buildPath.Join(constants.FOLDER_SKETCH).String()) - NoError(t, err1) - require.Equal(t, 3, len(files)) - - sort.Sort(ByFileInfoName(files)) - require.Equal(t, "header.h", files[0].Name()) - require.Equal(t, "s_file.S", files[1].Name()) - require.Equal(t, "src", files[2].Name()) - - files, err1 = gohasissues.ReadDir(buildPath.Join(constants.FOLDER_SKETCH, "src").String()) - NoError(t, err1) - require.Equal(t, 1, len(files)) - require.Equal(t, "helper.h", files[0].Name()) -} - -func TestCopyOtherFilesOnlyIfChanged(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch1", "sketch.ino"), - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.SketchLoader{}, - &builder.AdditionalSketchFilesCopier{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - headerStatBefore, err := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Stat() - NoError(t, err) - - time.Sleep(2 * time.Second) - - ctx = &types.Context{ - SketchLocation: paths.New("sketch1", "sketch.ino"), - BuildPath: buildPath, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - headerStatAfter, err := buildPath.Join(constants.FOLDER_SKETCH, "header.h").Stat() - NoError(t, err) - - require.Equal(t, headerStatBefore.ModTime().Unix(), headerStatAfter.ModTime().Unix()) -} diff --git a/test/builder_test.go b/test/builder_test.go deleted file mode 100644 index 78317b55..00000000 --- a/test/builder_test.go +++ /dev/null @@ -1,422 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os/exec" - "path/filepath" - "testing" - "time" - - "github.com/arduino/go-paths-helper" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func prepareBuilderTestContext(t *testing.T, sketchPath *paths.Path, fqbn string) *types.Context { - return &types.Context{ - SketchLocation: sketchPath, - FQBN: parseFQBN(t, fqbn), - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - ArduinoAPIVersion: "10600", - Verbose: false, - } -} - -func TestBuilderEmptySketch(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") - ctx.DebugLevel = 10 - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("sketch.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("sketch.ino.hex").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderBridge(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderSketchWithConfig(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch_with_config", "sketch_with_config.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "sketch_with_config.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("sketch_with_config.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("sketch_with_config.ino.hex").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderBridgeTwice(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - // Run builder again - command = builder.Builder{} - err = command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderBridgeSAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:sam:arduino_due_x_dbg") - ctx.WarningsLevel = "all" - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "syscalls_sam3.c.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_CORE, "USB", "PluggableUSB.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_CORE, "avr", "dtostrf.c.d").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.bin").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - - cmd := exec.Command(filepath.Join("downloaded_tools", "arm-none-eabi-gcc", "4.8.3-2014q1", "bin", "arm-none-eabi-objdump"), "-f", buildPath.Join(constants.FOLDER_CORE, "core.a").String()) - bytes, err := cmd.CombinedOutput() - NoError(t, err) - require.NotContains(t, string(bytes), "variant.cpp.o") -} - -func TestBuilderBridgeRedBearLab(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "RedBearLab:avr:blend") - ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join(constants.FOLDER_CORE, "HardwareSerial.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_PREPROC, constants.FILE_CTAGS_TARGET_FOR_GCC_MINUS_E).ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join(constants.FOLDER_SKETCH, "Bridge.ino.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.elf").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("Bridge.ino.hex").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = buildPath.Join("libraries", "Bridge", "Mailbox.cpp.o").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderSketchNoFunctions(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch_no_functions", "main.ino"), "RedBearLab:avr:blend") - ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - require.Error(t, err) -} - -func TestBuilderSketchWithBackup(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch_with_backup_files", "sketch.ino"), "arduino:avr:uno") - ctx.HardwareDirs = append(ctx.HardwareDirs, paths.New("downloaded_board_manager_stuff")) - ctx.ToolsDirs = append(ctx.ToolsDirs, paths.New("downloaded_board_manager_stuff")) - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchWithOldLib(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch_with_old_lib", "sketch.ino"), "arduino:avr:uno") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchWithSubfolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), "arduino:avr:uno") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) -} - -func TestBuilderSketchBuildPathContainsUnusedPreviouslyCompiledLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), "arduino:avr:leonardo") - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - NoError(t, buildPath.Join("libraries", "SPI").MkdirAll()) - - // Run builder - command := builder.Builder{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join("libraries", "SPI").ExistCheck() - NoError(t, err) - require.False(t, exist) - exist, err = buildPath.Join("libraries", "Bridge").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestBuilderWithBuildPathInSketchDir(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") - - var err error - ctx.BuildPath, err = paths.New("sketch1", "build").Abs() - NoError(t, err) - defer ctx.BuildPath.RemoveAll() - - // Run build - command := builder.Builder{} - err = command.Run(ctx) - NoError(t, err) - - // Run build twice, to verify the build still works when the - // build directory is present at the start - err = command.Run(ctx) - NoError(t, err) -} - -func TestBuilderCacheCoreAFile(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := prepareBuilderTestContext(t, paths.New("sketch1", "sketch.ino"), "arduino:avr:uno") - - SetupBuildPath(t, ctx) - defer ctx.BuildPath.RemoveAll() - SetupBuildCachePath(t, ctx) - defer ctx.BuildCachePath.RemoveAll() - - // Run build - bldr := builder.Builder{} - err := bldr.Run(ctx) - NoError(t, err) - - // Pick timestamp of cached core - coreFolder := paths.New("downloaded_hardware", "arduino", "avr") - coreFileName := builder_utils.GetCachedCoreArchiveFileName(ctx.FQBN.String(), coreFolder) - cachedCoreFile := ctx.CoreBuildCachePath.Join(coreFileName) - coreStatBefore, err := cachedCoreFile.Stat() - require.NoError(t, err) - - // Run build again, to verify that the builder skips rebuilding core.a - err = bldr.Run(ctx) - NoError(t, err) - - coreStatAfterRebuild, err := cachedCoreFile.Stat() - require.NoError(t, err) - require.Equal(t, coreStatBefore.ModTime(), coreStatAfterRebuild.ModTime()) - - // Touch a file of the core and check if the builder invalidate the cache - time.Sleep(time.Second) - now := time.Now().Local() - err = coreFolder.Join("cores", "arduino", "Arduino.h").Chtimes(now, now) - require.NoError(t, err) - - // Run build again, to verify that the builder rebuilds core.a - err = bldr.Run(ctx) - NoError(t, err) - - coreStatAfterTouch, err := cachedCoreFile.Stat() - require.NoError(t, err) - require.NotEqual(t, coreStatBefore.ModTime(), coreStatAfterTouch.ModTime()) -} diff --git a/test/builder_utils_test.go b/test/builder_utils_test.go deleted file mode 100644 index 99634235..00000000 --- a/test/builder_utils_test.go +++ /dev/null @@ -1,191 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "io/ioutil" - "testing" - "time" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func sleep(t *testing.T) { - dur, err := time.ParseDuration("1s") - NoError(t, err) - time.Sleep(dur) -} - -func tempFile(t *testing.T, prefix string) *paths.Path { - file, err := ioutil.TempFile("", prefix) - file.Close() - NoError(t, err) - return paths.New(file.Name()) -} - -func TestObjFileIsUpToDateObjMissing(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, nil, nil) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateDepMissing(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, nil) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateObjOlder(t *testing.T) { - ctx := &types.Context{} - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - depFile := tempFile(t, "dep") - defer depFile.RemoveAll() - - sleep(t) - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateObjNewer(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - sleep(t) - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - depFile := tempFile(t, "dep") - defer depFile.RemoveAll() - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.True(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsNewer(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - sleep(t) - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - depFile := tempFile(t, "dep") - defer depFile.RemoveAll() - - sleep(t) - - headerFile := tempFile(t, "header") - defer headerFile.RemoveAll() - - data := objFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() - depFile.WriteFile([]byte(data)) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsOlder(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - headerFile := tempFile(t, "header") - defer headerFile.RemoveAll() - - sleep(t) - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - depFile := tempFile(t, "dep") - defer depFile.RemoveAll() - - res := objFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() - depFile.WriteFile([]byte(res)) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.True(t, upToDate) -} - -func TestObjFileIsUpToDateDepIsWrong(t *testing.T) { - ctx := &types.Context{} - - sourceFile := tempFile(t, "source") - defer sourceFile.RemoveAll() - - sleep(t) - - objFile := tempFile(t, "obj") - defer objFile.RemoveAll() - depFile := tempFile(t, "dep") - defer depFile.RemoveAll() - - sleep(t) - - headerFile := tempFile(t, "header") - defer headerFile.RemoveAll() - - res := sourceFile.String() + ": \\\n\t" + sourceFile.String() + " \\\n\t" + headerFile.String() - depFile.WriteFile([]byte(res)) - - upToDate, err := builder_utils.ObjFileIsUpToDate(ctx, sourceFile, objFile, depFile) - NoError(t, err) - require.False(t, upToDate) -} diff --git a/test/create_build_options_map_test.go b/test/create_build_options_map_test.go deleted file mode 100644 index 929b0a23..00000000 --- a/test/create_build_options_map_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestCreateBuildOptionsMap(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("hardware", "hardware2"), - ToolsDirs: paths.NewPathList("tools"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketchLocation"), - FQBN: parseFQBN(t, "my:nice:fqbn"), - ArduinoAPIVersion: "ideVersion", - Verbose: true, - BuildPath: paths.New("buildPath"), - DebugLevel: 5, - } - - create := builder.CreateBuildOptionsMap{} - err := create.Run(ctx) - NoError(t, err) - - require.Equal(t, "{\n"+ - " \"additionalFiles\": \"\",\n"+ - " \"builtInLibrariesFolders\": \"\",\n"+ - " \"customBuildProperties\": \"\",\n"+ - " \"fqbn\": \"my:nice:fqbn\",\n"+ - " \"hardwareFolders\": \"hardware,hardware2\",\n"+ - " \"otherLibrariesFolders\": \"libraries\",\n"+ - " \"runtime.ide.version\": \"ideVersion\",\n"+ - " \"sketchLocation\": \"sketchLocation\",\n"+ - " \"toolsFolders\": \"tools\"\n"+ - "}", ctx.BuildOptionsJson) -} diff --git a/test/ctags_runner_test.go b/test/ctags_runner_test.go deleted file mode 100644 index 26982a0e..00000000 --- a/test/ctags_runner_test.go +++ /dev/null @@ -1,279 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestCTagsRunner(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino")) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) - expectedOutput := "server " + quotedSketchLocation + " /^BridgeServer server;$/;\" kind:variable line:31\n" + - "setup " + quotedSketchLocation + " /^void setup() {$/;\" kind:function line:33 signature:() returntype:void\n" + - "loop " + quotedSketchLocation + " /^void loop() {$/;\" kind:function line:46 signature:() returntype:void\n" + - "process " + quotedSketchLocation + " /^void process(BridgeClient client) {$/;\" kind:function line:62 signature:(BridgeClient client) returntype:void\n" + - "digitalCommand " + quotedSketchLocation + " /^void digitalCommand(BridgeClient client) {$/;\" kind:function line:82 signature:(BridgeClient client) returntype:void\n" + - "analogCommand " + quotedSketchLocation + " /^void analogCommand(BridgeClient client) {$/;\" kind:function line:109 signature:(BridgeClient client) returntype:void\n" + - "modeCommand " + quotedSketchLocation + " /^void modeCommand(BridgeClient client) {$/;\" kind:function line:149 signature:(BridgeClient client) returntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithClass(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, paths.New("sketch_with_class", "sketch.ino")) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) - expectedOutput := "set_values\t" + quotedSketchLocation + "\t/^ void set_values (int,int);$/;\"\tkind:prototype\tline:4\tclass:Rectangle\tsignature:(int,int)\treturntype:void\n" + - "area\t" + quotedSketchLocation + "\t/^ int area() {return width*height;}$/;\"\tkind:function\tline:5\tclass:Rectangle\tsignature:()\treturntype:int\n" + - "set_values\t" + quotedSketchLocation + "\t/^void Rectangle::set_values (int x, int y) {$/;\"\tkind:function\tline:8\tclass:Rectangle\tsignature:(int x, int y)\treturntype:void\n" + - "setup\t" + quotedSketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:13\tsignature:()\treturntype:void\n" + - "loop\t" + quotedSketchLocation + "\t/^void loop() {$/;\"\tkind:function\tline:17\tsignature:()\treturntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithTypename(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, paths.New("sketch_with_typename", "sketch.ino")) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) - expectedOutput := "Foo\t" + quotedSketchLocation + "\t/^ struct Foo{$/;\"\tkind:struct\tline:2\n" + - "setup\t" + quotedSketchLocation + "\t/^void setup() {$/;\"\tkind:function\tline:6\tsignature:()\treturntype:void\n" + - "loop\t" + quotedSketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "func\t" + quotedSketchLocation + "\t/^typename Foo::Bar func(){$/;\"\tkind:function\tline:12\tsignature:()\treturntype:Foo::Bar\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithNamespace(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, paths.New("sketch_with_namespace", "sketch.ino")) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) - expectedOutput := "value\t" + quotedSketchLocation + "\t/^\tint value() {$/;\"\tkind:function\tline:2\tnamespace:Test\tsignature:()\treturntype:int\n" + - "setup\t" + quotedSketchLocation + "\t/^void setup() {}$/;\"\tkind:function\tline:7\tsignature:()\treturntype:void\n" + - "loop\t" + quotedSketchLocation + "\t/^void loop() {}$/;\"\tkind:function\tline:8\tsignature:()\treturntype:void\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} - -func TestCTagsRunnerSketchWithTemplates(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := Abs(t, paths.New("sketch_with_templates_and_shift", "template_and_shift.cpp")) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - &builder.CTagsTargetFileSaver{Source: &ctx.Source, TargetFileName: "ctags_target.cpp"}, - &builder.CTagsRunner{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - quotedSketchLocation := strings.Replace(sketchLocation.String(), "\\", "\\\\", -1) - expectedOutput := "printGyro\t" + quotedSketchLocation + "\t/^void printGyro()$/;\"\tkind:function\tline:10\tsignature:()\treturntype:void\n" + - "bVar\t" + quotedSketchLocation + "\t/^c< 8 > bVar;$/;\"\tkind:variable\tline:15\n" + - "aVar\t" + quotedSketchLocation + "\t/^c< 1<<8 > aVar;$/;\"\tkind:variable\tline:16\n" + - "func\t" + quotedSketchLocation + "\t/^template func( c< 1< & aParam) {$/;\"\tkind:function\tline:18\tsignature:( c< 1< & aParam)\treturntype:template\n" - - require.Equal(t, expectedOutput, strings.Replace(ctx.CTagsOutput, "\r\n", "\n", -1)) -} diff --git a/test/dependent_libraries/library1/library1.h b/test/dependent_libraries/library1/library1.h deleted file mode 100644 index 20e0d9eb..00000000 --- a/test/dependent_libraries/library1/library1.h +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/dependent_libraries/library2/library2.h b/test/dependent_libraries/library2/library2.h deleted file mode 100644 index a5d75ad7..00000000 --- a/test/dependent_libraries/library2/library2.h +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/dependent_libraries/library3/library3.cpp b/test/dependent_libraries/library3/library3.cpp deleted file mode 100644 index be5c8d45..00000000 --- a/test/dependent_libraries/library3/library3.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include -#include \ No newline at end of file diff --git a/test/dependent_libraries/library3/library3.h b/test/dependent_libraries/library3/library3.h deleted file mode 100644 index 0be00b9c..00000000 --- a/test/dependent_libraries/library3/library3.h +++ /dev/null @@ -1 +0,0 @@ -#warning included! \ No newline at end of file diff --git a/test/dependent_libraries/library4/library4.h b/test/dependent_libraries/library4/library4.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/eol_processing/sketch.ino b/test/eol_processing/sketch.ino deleted file mode 100644 index 9037a7fa..00000000 --- a/test/eol_processing/sketch.ino +++ /dev/null @@ -1 +0,0 @@ -int led = 7; void setup() { } void loop() { } \ No newline at end of file diff --git a/test/fail_if_buildpath_equals_sketchpath_test.go b/test/fail_if_buildpath_equals_sketchpath_test.go deleted file mode 100644 index 0e7ddc3f..00000000 --- a/test/fail_if_buildpath_equals_sketchpath_test.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestFailIfBuildPathEqualsSketchPath(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("buildPath/sketch.ino"), - BuildPath: paths.New("buildPath"), - } - - command := builder.FailIfBuildPathEqualsSketchPath{} - require.Error(t, command.Run(ctx)) -} - -func TestFailIfBuildPathEqualsSketchPathSketchPathDiffers(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketchPath/sketch.ino"), - BuildPath: paths.New("buildPath"), - } - - command := builder.FailIfBuildPathEqualsSketchPath{} - NoError(t, command.Run(ctx)) -} diff --git a/test/generate_buildpath_if_missing_test.go b/test/generate_buildpath_if_missing_test.go deleted file mode 100644 index 03f5aff8..00000000 --- a/test/generate_buildpath_if_missing_test.go +++ /dev/null @@ -1,102 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "os" - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestGenerateBuildPathIfMissing(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("test"), - } - - command := builder.GenerateBuildPathIfMissing{} - err := command.Run(ctx) - NoError(t, err) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) - _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - require.True(t, os.IsNotExist(err)) -} - -func TestGenerateBuildPathIfEmpty(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("test"), - } - - createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} - err := createBuildPathIfMissing.Run(ctx) - NoError(t, err) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) - _, err = os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - require.True(t, os.IsNotExist(err)) -} - -func TestDontGenerateBuildPathIfPresent(t *testing.T) { - ctx := &types.Context{} - ctx.BuildPath = paths.New("test") - - createBuildPathIfMissing := builder.GenerateBuildPathIfMissing{} - err := createBuildPathIfMissing.Run(ctx) - NoError(t, err) - - require.Equal(t, ctx.BuildPath.String(), "test") -} - -func TestGenerateBuildPathAndEnsureItExists(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("test"), - } - - commands := []types.Command{ - &builder.GenerateBuildPathIfMissing{}, - &builder.EnsureBuildPathExists{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - defer os.RemoveAll(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - - require.Equal(t, filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6"), ctx.BuildPath.String()) - _, err := os.Stat(filepath.Join(os.TempDir(), "arduino-sketch-098F6BCD4621D373CADE4E832627B4F6")) - NoError(t, err) -} diff --git a/test/hardware/arduino/avr/boards.local.txt b/test/hardware/arduino/avr/boards.local.txt deleted file mode 100644 index b3f7e812..00000000 --- a/test/hardware/arduino/avr/boards.local.txt +++ /dev/null @@ -1,11 +0,0 @@ -## Arduino Duemilanove or Diecimila w/ ATmega123 -## --------------------------------------------- -diecimila.menu.cpu.atmega123=ATmega123 - -diecimila.menu.cpu.atmega123.upload.maximum_size=14336 -diecimila.menu.cpu.atmega123.upload.maximum_data_size=1024 -diecimila.menu.cpu.atmega123.upload.speed=19200 - -diecimila.menu.cpu.atmega123.bootloader.high_fuses=0xdd -diecimila.menu.cpu.atmega123.bootloader.extended_fuses=0x00 -diecimila.menu.cpu.atmega123.bootloader.file=atmega/ATmegaBOOT_123_diecimila.hex diff --git a/test/hardware/arduino/avr/boards.txt b/test/hardware/arduino/avr/boards.txt deleted file mode 100644 index bcea2331..00000000 --- a/test/hardware/arduino/avr/boards.txt +++ /dev/null @@ -1,18 +0,0 @@ - -micro.vid.4=0x2341 -micro.pid.4=0x0237 -# If the board is a 2341:0237 use 2341:8237 for build and set -# other parameters as well -micro.vid.4.build.vid=0x2341 -micro.vid.4.build.pid=0x8237 -micro.vid.4.build.usb_product="Genuino Micro" -micro.vid.4.bootloader.file=caterina/Caterina-Genuino-Micro.hex - -micro.vid.5=0x2341 -micro.pid.5=0x8237 -# If the board is a 2341:8237 use 2341:8237 for build and set -# other paramters as well -micro.vid.5.build.vid=0x2341 -micro.vid.5.build.pid=0x8237 -micro.vid.5.build.usb_product="Genuino Micro" -micro.vid.5.bootloader.file=caterina/Caterina-Genuino-Micro.hex diff --git a/test/hardware/arduino/avr/platform.local.txt b/test/hardware/arduino/avr/platform.local.txt deleted file mode 100644 index aef16166..00000000 --- a/test/hardware/arduino/avr/platform.local.txt +++ /dev/null @@ -1 +0,0 @@ -tools.avrdude.cmd.path=/my/personal/avrdude \ No newline at end of file diff --git a/test/hardware/platform.txt b/test/hardware/platform.txt deleted file mode 100644 index 8b137891..00000000 --- a/test/hardware/platform.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/test/hardware/watterott/avr/boards.txt b/test/hardware/watterott/avr/boards.txt deleted file mode 100644 index be844787..00000000 --- a/test/hardware/watterott/avr/boards.txt +++ /dev/null @@ -1,130 +0,0 @@ -# VID 0x6666 is a prototype product Vendor ID -# http://www.linux-usb.org/usb.ids - -menu.speed=Speed -menu.core=Core -menu.info=Info - - -# ATmega32u4 @ 16 MHz -atmega32u4.name=ATmega32u4 -atmega32u4.menu.speed.16mhz=16 MHz -atmega32u4.menu.speed.16mhz.build.f_cpu=16000000L -atmega32u4.menu.speed.16mhz.bootloader.file=caterina_16mhz.hex -atmega32u4.menu.speed.8mhz=8 MHz -atmega32u4.menu.speed.8mhz.build.f_cpu=8000000L -atmega32u4.menu.speed.8mhz.bootloader.file=caterina_8mhz.hex -atmega32u4.vid.0=0x1D50 -atmega32u4.pid.0=0x60B0 -atmega32u4.vid.1=0x6666 -atmega32u4.pid.1=0x60B0 -atmega32u4.vid.2=0x2341 -atmega32u4.pid.2=0x0036 -atmega32u4.vid.3=0x2341 -atmega32u4.pid.3=0x8036 -atmega32u4.vid.4=0x2A03 -atmega32u4.pid.4=0x0036 -atmega32u4.vid.5=0x2A03 -atmega32u4.pid.5=0x8036 -atmega32u4.bootloader.tool=avrdude -atmega32u4.bootloader.low_fuses=0xff -atmega32u4.bootloader.high_fuses=0xd8 -atmega32u4.bootloader.extended_fuses=0xcb -#atmega32u4.bootloader.file=caterina_16mhz.hex -atmega32u4.bootloader.unlock_bits=0x3F -atmega32u4.bootloader.lock_bits=0x2F -atmega32u4.upload.tool=avrdude -atmega32u4.upload.protocol=avr109 -atmega32u4.upload.maximum_size=28672 -atmega32u4.upload.maximum_data_size=2560 -atmega32u4.upload.speed=57600 -atmega32u4.upload.disable_flushing=true -atmega32u4.upload.use_1200bps_touch=true -atmega32u4.upload.wait_for_upload_port=true -atmega32u4.build.mcu=atmega32u4 -#atmega32u4.build.f_cpu=16000000L -atmega32u4.build.vid=0x6666 -atmega32u4.build.pid=0x60B0 -atmega32u4.build.usb_product="USB IO Board" -atmega32u4.build.usb_manufacturer="ATmega32u4" -atmega32u4.build.board=AVR_LEONARDO -atmega32u4.build.core=arduino:arduino -atmega32u4.build.variant=leonardo -atmega32u4.build.extra_flags={build.usb_flags} -DMOUSE_ABS_ENABLED - - -# ATtiny841 @ internal 8 MHz -attiny841.name=ATtiny841 (8 MHz) -# use Standard Arduino Core -attiny841.menu.core.arduino=Standard Arduino -attiny841.menu.core.arduino.build.core=arduino:arduino -attiny841.menu.core.arduino.build.variant=tiny14 -# use Spence Konde Core: https://github.com/SpenceKonde/arduino-tiny-841/ -attiny841.menu.core.spencekonde=ATtiny841 (by Spence Konde) -#attiny841.menu.core.spencekonde.build.core=arduino-tiny-841:tiny -attiny841.menu.core.spencekonde.build.core=tiny841 -attiny841.menu.core.spencekonde.build.variant=tiny14 -# info menu item -attiny841.menu.info.info=Press Reset, when Uploading is shown. -attiny841.vid.0=0x16D0 -attiny841.pid.0=0x0753 -attiny841.bootloader.tool=avrdude -attiny841.bootloader.low_fuses=0xE2 -attiny841.bootloader.high_fuses=0xDD -attiny841.bootloader.extended_fuses=0xFE -attiny841.bootloader.unlock_bits=0xFF -attiny841.bootloader.lock_bits=0xFF -attiny841.bootloader.file=micronucleus-t841.hex -attiny841.upload.tool=micronucleus -attiny841.upload.protocol=usb -attiny841.upload.wait_for_upload_port=false -attiny841.upload.use_1200bps_touch=false -attiny841.upload.disable_flushing=false -attiny841.upload.maximum_size=6500 -attiny841.build.mcu=attiny841 -attiny841.build.f_cpu=8000000L -attiny841.build.board=AVR_ATTINY841 -#attiny841.build.core=arduino:arduino -#attiny841.build.variant=tiny14 - - -# ATtiny85 @ internal 16.5 MHz -attiny85.name=ATtiny85 (16.5 MHz) -# use Standard Arduino Core -attiny85.menu.core.arduino=Standard Arduino -attiny85.menu.core.arduino.build.board=AVR_ATTINY85 -attiny85.menu.core.arduino.build.core=arduino:arduino -attiny85.menu.core.arduino.build.variant=tiny8 -# use Spence Konde Core: https://github.com/SpenceKonde/ATTinyCore -attiny85.menu.core.spencekonde=ATtiny85 (by Spence Konde) -attiny85.menu.core.spencekonde.build.board=AVR_ATTINY85 -#attiny85.menu.core.spencekonde.build.core=ATTinyCore:tiny -attiny85.menu.core.spencekonde.build.core=tiny85 -attiny85.menu.core.spencekonde.build.variant=tiny8 -# use Digistump Core: https://github.com/digistump/DigistumpArduino -attiny85.menu.core.digistump=Digistump/Digispark -attiny85.menu.core.digistump.build.board=AVR_DIGISPARK -attiny85.menu.core.digistump.build.core=digistump:tiny -attiny85.menu.core.digistump.build.variant=digispark -# info menu item -attiny85.menu.info.info=Press Reset, when Uploading is shown. -attiny85.vid.0=0x16D0 -attiny85.pid.0=0x0753 -attiny85.bootloader.tool=avrdude -attiny85.bootloader.low_fuses=0xE1 -attiny85.bootloader.high_fuses=0xDD -attiny85.bootloader.extended_fuses=0xFE -attiny85.bootloader.unlock_bits=0xFF -attiny85.bootloader.lock_bits=0xFF -attiny85.bootloader.file=micronucleus-t85.hex -attiny85.upload.tool=micronucleus -attiny85.upload.protocol=usb -attiny85.upload.wait_for_upload_port=false -attiny85.upload.use_1200bps_touch=false -attiny85.upload.disable_flushing=false -attiny85.upload.maximum_size=6300 -attiny85.build.mcu=attiny85 -attiny85.build.f_cpu=16500000L -attiny85.build.board=AVR_ATTINY85 -#attiny85.build.core=arduino:arduino -#attiny85.build.variant=tiny8 diff --git a/test/hardware/watterott/avr/platform.txt b/test/hardware/watterott/avr/platform.txt deleted file mode 100644 index 13d46cea..00000000 --- a/test/hardware/watterott/avr/platform.txt +++ /dev/null @@ -1,146 +0,0 @@ - -# Watterott AVR Core and platform. -# ------------------------------ -# -# For more info: -# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification - -name=Watterott AVR Boards -version=1.0.0 - -# AVR compile variables -# --------------------- - -compiler.warning_flags=-w -compiler.warning_flags.none=-w -compiler.warning_flags.default= -compiler.warning_flags.more=-Wall -compiler.warning_flags.all=-Wall -Wextra - -# Default "compiler.path" is correct, change only if you want to overidde the initial value -#compiler.path={runtime.ide.path}/hardware/tools/avr/bin/ -compiler.path={runtime.tools.avr-gcc.path}/bin/ -compiler.c.cmd=avr-gcc -compiler.c.flags=-c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD -# -w flag added to avoid printing a wrong warning http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59396 -# This is fixed in gcc 4.8.3 and will be removed as soon as we update the toolchain -compiler.c.elf.flags=-Os {compiler.warning_flags} -Wl,--gc-sections -compiler.c.elf.cmd=avr-gcc -compiler.S.flags=-c -g -x assembler-with-cpp -compiler.cpp.cmd=avr-g++ -compiler.cpp.flags=-c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -compiler.ar.cmd=avr-ar -compiler.ar.flags=rcs -compiler.objcopy.cmd=avr-objcopy -compiler.objcopy.eep.flags=-O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 -compiler.elf2hex.flags=-O ihex -R .eeprom -compiler.elf2hex.cmd=avr-objcopy -compiler.ldflags= -compiler.size.cmd=avr-size - -# This can be overriden in boards.txt -build.extra_flags= - -# These can be overridden in platform.local.txt -compiler.c.extra_flags= -compiler.c.elf.extra_flags= -compiler.S.extra_flags= -compiler.cpp.extra_flags= -compiler.ar.extra_flags= -compiler.objcopy.eep.extra_flags= -compiler.elf2hex.extra_flags= - -# AVR compile patterns -# -------------------- - -## Compile c files -recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Compile c++ files -recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Compile S files -recipe.S.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.S.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {includes} "{source_file}" -o "{object_file}" - -## Create archives -recipe.ar.pattern="{compiler.path}{compiler.ar.cmd}" {compiler.ar.flags} {compiler.ar.extra_flags} "{build.path}/{archive_file}" "{object_file}" - -## Combine gc-sections, archives, and objects -recipe.c.combine.pattern="{compiler.path}{compiler.c.elf.cmd}" {compiler.c.elf.flags} -mmcu={build.mcu} {compiler.c.elf.extra_flags} -o "{build.path}/{build.project_name}.elf" {object_files} "{build.path}/{archive_file}" "-L{build.path}" -lm - -## Create output files (.eep and .hex) -recipe.objcopy.eep.pattern="{compiler.path}{compiler.objcopy.cmd}" {compiler.objcopy.eep.flags} {compiler.objcopy.eep.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.eep" -recipe.objcopy.hex.pattern="{compiler.path}{compiler.elf2hex.cmd}" {compiler.elf2hex.flags} {compiler.elf2hex.extra_flags} "{build.path}/{build.project_name}.elf" "{build.path}/{build.project_name}.hex" - -## Save hex -recipe.output.tmp_file={build.project_name}.hex -recipe.output.save_file={build.project_name}.{build.variant}.hex - -## Compute size -recipe.size.pattern="{compiler.path}{compiler.size.cmd}" -A "{build.path}/{build.project_name}.elf" -recipe.size.regex=^(?:\.text|\.data|\.bootloader)\s+([0-9]+).* -recipe.size.regex.data=^(?:\.data|\.bss|\.noinit)\s+([0-9]+).* -recipe.size.regex.eeprom=^(?:\.eeprom)\s+([0-9]+).* - -## Preprocessor -preproc.includes.flags=-w -x c++ -M -MG -MP -recipe.preproc.includes="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" -preproc.macros.flags=-w -x c++ -E -CC -recipe.preproc.macros="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} {preproc.macros.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} "{source_file}" - - -# AVR Uploader/Programmers tools -# ------------------------------ - -## AVRdude -#tools.avrdude.path={runtime.ide.path}/hardware/tools/avr/ -tools.avrdude.path={runtime.tools.avrdude.path} -tools.avrdude.cmd.path={path}/bin/avrdude -#tools.avrdude.config.path={path}/etc/avrdude.conf -tools.avrdude.config.path={runtime.platform.path}/tools/avrdude.conf - -tools.avrdude.upload.params.verbose=-v -tools.avrdude.upload.params.quiet=-q -q -tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i" - -tools.avrdude.program.params.verbose=-v -tools.avrdude.program.params.quiet=-q -q -tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i" - -tools.avrdude.erase.params.verbose=-v -tools.avrdude.erase.params.quiet=-q -q -tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uefuse:w:{bootloader.extended_fuses}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m - -tools.avrdude.bootloader.params.verbose=-v -tools.avrdude.bootloader.params.quiet=-q -q -tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} -P{serial.port} {program.extra_params} "-Uflash:w:{runtime.platform.path}/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m - -## Micronucleus -tools.micronucleus.path={runtime.tools.micronucleus.path} -tools.micronucleus.cmd=micronucleus -tools.micronucleus.cmd.windows=micronucleus.exe - -tools.micronucleus.upload.params.verbose= -tools.micronucleus.upload.params.quiet= -tools.micronucleus.upload.pattern="{path}/{cmd}" --run --timeout 60 "{build.path}/{build.project_name}.hex" - -tools.micronucleus.program.params.verbose= -tools.micronucleus.program.params.quiet= -tools.micronucleus.program.pattern="{path}/{cmd}" --run --timeout 60 "{build.path}/{build.project_name}.hex" - -tools.micronucleus.erase.params.verbose= -tools.micronucleus.erase.params.quiet= -tools.micronucleus.erase.pattern= -#tools.micronucleus.erase.pattern="{path}/{cmd}" --erase-only --timeout 60 - -tools.micronucleus.bootloader.params.verbose= -tools.micronucleus.bootloader.params.quiet= -tools.micronucleus.bootloader.pattern="{path}/{cmd}" --run --timeout 60 "{runtime.platform.path}/bootloaders/{bootloader.file}" - - -# USB Default Flags -# Default blank usb manufacturer will be filled it at compile time -# - from numeric vendor ID, set to Unknown otherwise -build.usb_manufacturer="Unknown" -build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}' - diff --git a/test/hardware/watterott/avr/programmers.txt b/test/hardware/watterott/avr/programmers.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/test/hardware_loader_test.go b/test/hardware_loader_test.go deleted file mode 100644 index 37acae17..00000000 --- a/test/hardware_loader_test.go +++ /dev/null @@ -1,243 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "runtime" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestLoadHardware(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - require.Equal(t, 2, len(packages.Packages)) - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties.Get("_id")) - - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties.Get("upload.wait_for_upload_port")) - - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties.Get("build.extra_flags")) - - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) - - require.Equal(t, "ATmega123", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["diecimila"].Properties.Get("menu.cpu.atmega123")) - - avrPlatform := packages.Packages["arduino"].Platforms["avr"] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Releases[""].Properties.Get("name")) - require.Equal(t, "-v", avrPlatform.Releases[""].Properties.Get("tools.avrdude.bootloader.params.verbose")) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Releases[""].Properties.Get("tools.avrdude.cmd.path")) - - require.Equal(t, "AVRISP mkII", avrPlatform.Releases[""].Programmers["avrispmkii"].Get("name")) - - //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties.Get("tools.ctags.path"]) - //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties.Get("tools.ctags.pattern"]) - //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties.Get("tools.avrdude.path"]) - //require.Equal(t, "-w -x c++ -E -CC", packages.Properties.Get("preproc.macros.flags"]) -} - -func TestLoadHardwareMixingUserHardwareFolder(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.PlatformKeysRewriteLoader{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - - if runtime.GOOS == "windows" { - //a package is a symlink, and windows does not support them - require.Equal(t, 3, len(packages.Packages)) - } else { - require.Equal(t, 4, len(packages.Packages)) - } - - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms)) - - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].BoardID) - require.Equal(t, "uno", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["uno"].Properties.Get("_id")) - - require.Equal(t, "yun", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].BoardID) - require.Equal(t, "true", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["yun"].Properties.Get("upload.wait_for_upload_port")) - - require.Equal(t, "{build.usb_flags}", packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards["robotMotor"].Properties.Get("build.extra_flags")) - - require.Equal(t, "arduino_due_x", packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards["arduino_due_x"].BoardID) - - avrPlatform := packages.Packages["arduino"].Platforms["avr"].Releases[""] - require.Equal(t, "Arduino AVR Boards", avrPlatform.Properties.Get("name")) - require.Equal(t, "-v", avrPlatform.Properties.Get("tools.avrdude.bootloader.params.verbose")) - require.Equal(t, "/my/personal/avrdude", avrPlatform.Properties.Get("tools.avrdude.cmd.path")) - - require.Equal(t, "AVRISP mkII", avrPlatform.Programmers["avrispmkii"].Get("name")) - - require.Equal(t, "-w -x c++ -M -MG -MP", avrPlatform.Properties.Get("preproc.includes.flags")) - require.Equal(t, "-w -x c++ -E -CC", avrPlatform.Properties.Get("preproc.macros.flags")) - require.Equal(t, "\"{compiler.path}{compiler.cpp.cmd}\" {compiler.cpp.flags} {preproc.includes.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {includes} \"{source_file}\"", avrPlatform.Properties.Get("recipe.preproc.includes")) - require.False(t, avrPlatform.Properties.ContainsKey("preproc.macros.compatibility_flags")) - - require.NotNil(t, packages.Packages["my_avr_platform"]) - myAVRPlatform := packages.Packages["my_avr_platform"] - //require.Equal(t, "hello world", myAVRPlatform.Properties.Get("example")) - myAVRPlatformAvrArch := myAVRPlatform.Platforms["avr"].Releases[""] - require.Equal(t, "custom_yun", myAVRPlatformAvrArch.Boards["custom_yun"].BoardID) - - require.False(t, myAVRPlatformAvrArch.Properties.ContainsKey("preproc.includes.flags")) - - //require.Equal(t, "{runtime.tools.ctags.path}", packages.Properties.Get("tools.ctags.path")) - //require.Equal(t, "\"{cmd.path}\" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives \"{source_file}\"", packages.Properties.Get("tools.ctags.pattern")) - //require.Equal(t, "{runtime.tools.avrdude.path}", packages.Properties.Get("tools.avrdude.path")) - //require.Equal(t, "-w -x c++ -E -CC", packages.Properties.Get("preproc.macros.flags")) - - if runtime.GOOS != "windows" { - require.NotNil(t, packages.Packages["my_symlinked_avr_platform"]) - require.NotNil(t, packages.Packages["my_symlinked_avr_platform"].Platforms["avr"]) - } -} - -func TestLoadHardwareWithBoardManagerFolderStructure(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - require.Equal(t, 3, len(packages.Packages)) - require.NotNil(t, packages.Packages["arduino"]) - require.Equal(t, 1, len(packages.Packages["arduino"].Platforms)) - require.NotNil(t, packages.Packages["RedBearLab"]) - require.Equal(t, 1, len(packages.Packages["RedBearLab"].Platforms)) - require.NotNil(t, packages.Packages["RFduino"]) - require.Equal(t, 0, len(packages.Packages["RFduino"].Platforms)) - - samdPlatform := packages.Packages["arduino"].Platforms["samd"].Releases["1.6.5"] - require.Equal(t, 3, len(samdPlatform.Boards)) - - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].BoardID) - require.Equal(t, "arduino_zero_edbg", samdPlatform.Boards["arduino_zero_edbg"].Properties.Get("_id")) - - require.Equal(t, "arduino_zero", samdPlatform.Boards["arduino_zero_native"].Properties.Get("build.variant")) - require.Equal(t, "-D__SAMD21G18A__ {build.usb_flags}", samdPlatform.Boards["arduino_zero_native"].Properties.Get("build.extra_flags")) - - require.Equal(t, "Arduino SAMD (32-bits ARM Cortex-M0+) Boards", samdPlatform.Properties.Get("name")) - require.Equal(t, "-d3", samdPlatform.Properties.Get("tools.openocd.erase.params.verbose")) - - require.Equal(t, 3, len(samdPlatform.Programmers)) - - require.Equal(t, "Atmel EDBG", samdPlatform.Programmers["edbg"].Get("name")) - require.Equal(t, "openocd", samdPlatform.Programmers["edbg"].Get("program.tool")) - - avrRedBearPlatform := packages.Packages["RedBearLab"].Platforms["avr"].Releases["1.0.0"] - require.Equal(t, 3, len(avrRedBearPlatform.Boards)) - - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].BoardID) - require.Equal(t, "blend", avrRedBearPlatform.Boards["blend"].Properties.Get("_id")) - require.Equal(t, "arduino:arduino", avrRedBearPlatform.Boards["blend"].Properties.Get("build.core")) -} - -func TestLoadLotsOfHardware(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff", "downloaded_hardware", filepath.Join("..", "hardware"), "hardware", "user_hardware"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - packages := ctx.Hardware - - if runtime.GOOS == "windows" { - //a package is a symlink, and windows does not support them - require.Equal(t, 5, len(packages.Packages)) - } else { - require.Equal(t, 6, len(packages.Packages)) - } - - require.NotNil(t, packages.Packages["arduino"]) - require.NotNil(t, packages.Packages["my_avr_platform"]) - - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms)) - require.Equal(t, 20, len(packages.Packages["arduino"].Platforms["avr"].Releases[""].Boards)) - require.Equal(t, 2, len(packages.Packages["arduino"].Platforms["sam"].Releases[""].Boards)) - require.Equal(t, 3, len(packages.Packages["arduino"].Platforms["samd"].Releases["1.6.5"].Boards)) - - require.Equal(t, 1, len(packages.Packages["my_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_avr_platform"].Platforms["avr"].Releases[""].Boards)) - - if runtime.GOOS != "windows" { - require.Equal(t, 1, len(packages.Packages["my_symlinked_avr_platform"].Platforms)) - require.Equal(t, 2, len(packages.Packages["my_symlinked_avr_platform"].Platforms["avr"].Releases[""].Boards)) - } -} diff --git a/test/helper.go b/test/helper.go deleted file mode 100644 index 1f2e68d6..00000000 --- a/test/helper.go +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "bytes" - "fmt" - "path/filepath" - "testing" - "text/template" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/arduino-cli/arduino/libraries" - paths "github.com/arduino/go-paths-helper" - "github.com/go-errors/errors" - "github.com/stretchr/testify/assert" -) - -func LoadAndInterpolate(t *testing.T, filename string, ctx *types.Context) string { - funcsMap := template.FuncMap{ - "QuoteCppString": utils.QuoteCppPath, - } - - tpl, err := template.New(filepath.Base(filename)).Funcs(funcsMap).ParseFiles(filename) - NoError(t, err) - - var buf bytes.Buffer - data := make(map[string]interface{}) - data["sketch"] = ctx.Sketch - err = tpl.Execute(&buf, data) - NoError(t, err) - - return buf.String() -} - -func Abs(t *testing.T, rel *paths.Path) *paths.Path { - absPath, err := rel.Abs() - NoError(t, err) - return absPath -} - -func NoError(t *testing.T, err error, msgAndArgs ...interface{}) { - if !assert.NoError(t, err, msgAndArgs...) { - switch err.(type) { - case *errors.Error: - fmt.Println(err.(*errors.Error).ErrorStack()) - } - t.FailNow() - } -} - -func SetupBuildPath(t *testing.T, ctx *types.Context) *paths.Path { - buildPath, err := paths.MkTempDir("", "test_build_path") - NoError(t, err) - ctx.BuildPath = buildPath - return buildPath -} - -func SetupBuildCachePath(t *testing.T, ctx *types.Context) *paths.Path { - buildCachePath, err := paths.MkTempDir(constants.EMPTY_STRING, "test_build_cache") - NoError(t, err) - ctx.BuildCachePath = buildCachePath - return buildCachePath -} - -type ByLibraryName []*libraries.Library - -func (s ByLibraryName) Len() int { - return len(s) -} -func (s ByLibraryName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByLibraryName) Less(i, j int) bool { - return s[i].Name < s[j].Name -} diff --git a/test/helper_tools_downloader.go b/test/helper_tools_downloader.go deleted file mode 100644 index 8e092a7e..00000000 --- a/test/helper_tools_downloader.go +++ /dev/null @@ -1,853 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/go-paths-helper" - "github.com/arduino/go-properties-orderedmap" - "github.com/go-errors/errors" -) - -var hardwareFolder = paths.New("downloaded_hardware") -var boardManagerFolder = paths.New("downloaded_board_manager_stuff") -var toolsFolder = paths.New("downloaded_tools") -var librariesFolder = paths.New("downloaded_libraries") -var patchesFolder = paths.New("downloaded_stuff_patches") - -type Tool struct { - Name string - Package string - Version string - OsUrls []OsUrl -} - -type OsUrl struct { - Os string - Url string -} - -type Library struct { - Name string - Version string - VersionInLibProperties string - Url string -} - -type Core struct { - Maintainer string - Arch string - Version string - Url string -} - -func DownloadCoresAndToolsAndLibraries(t *testing.T) { - cores := []Core{ - Core{Maintainer: "arduino", Arch: "avr", Version: "1.6.10"}, - Core{Maintainer: "arduino", Arch: "sam", Version: "1.6.7"}, - } - - boardsManagerCores := []Core{ - Core{Maintainer: "arduino", Arch: "samd", Version: "1.6.5"}, - } - - boardsManagerRedBearCores := []Core{ - Core{Maintainer: "RedBearLab", Arch: "avr", Version: "1.0.0", Url: "https://redbearlab.github.io/arduino/Blend/blend_boards.zip"}, - } - - toolsMultipleVersions := []Tool{ - Tool{Name: "bossac", Version: "1.6.1-arduino"}, - Tool{Name: "bossac", Version: "1.5-arduino"}, - } - - tools := []Tool{ - Tool{Name: "avrdude", Version: "6.0.1-arduino5"}, - Tool{Name: "avr-gcc", Version: "4.8.1-arduino5"}, - Tool{Name: "arm-none-eabi-gcc", Version: "4.8.3-2014q1"}, - Tool{Name: "ctags", Version: "5.8-arduino11", - OsUrls: []OsUrl{ - OsUrl{Os: "i686-pc-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-i686-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "x86_64-pc-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-x86_64-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "i686-mingw32", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-i686-mingw32.zip"}, - OsUrl{Os: "x86_64-apple-darwin", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-x86_64-apple-darwin.zip"}, - OsUrl{Os: "arm-linux-gnueabihf", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-armv6-linux-gnueabihf.tar.bz2"}, - OsUrl{Os: "aarch64-linux-gnu", Url: "http://downloads.arduino.cc/tools/ctags-5.8-arduino11-aarch64-linux-gnu.tar.bz2"}, - }, - }, - Tool{Name: "arduino-preprocessor", Version: "0.1.5", - OsUrls: []OsUrl{ - OsUrl{Os: "i686-pc-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-i686-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "x86_64-pc-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-x86_64-pc-linux-gnu.tar.bz2"}, - OsUrl{Os: "i686-mingw32", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-i686-w64-mingw32.tar.bz2"}, - OsUrl{Os: "x86_64-apple-darwin", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-x86_64-apple-darwin11.tar.bz2"}, - OsUrl{Os: "arm-linux-gnueabihf", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-arm-linux-gnueabihf.tar.bz2"}, - OsUrl{Os: "aarch64-linux-gnu", Url: "https://github.com/arduino/arduino-preprocessor/releases/download/0.1.5/arduino-preprocessor-0.1.5-aarch64-linux-gnu.tar.bz2"}, - }, - }, - } - - boardsManagerTools := []Tool{ - Tool{Name: "openocd", Version: "0.9.0-arduino", Package: "arduino"}, - Tool{Name: "CMSIS", Version: "4.0.0-atmel", Package: "arduino"}, - } - - boardsManagerRFduinoTools := []Tool{ - Tool{Name: "arm-none-eabi-gcc", Version: "4.8.3-2014q1", Package: "RFduino"}, - } - - libraries := []Library{ - Library{Name: "Audio", Version: "1.0.4"}, - Library{Name: "Adafruit PN532", Version: "1.0.0"}, - Library{Name: "Bridge", Version: "1.6.1"}, - Library{Name: "CapacitiveSensor", Version: "0.5.0", VersionInLibProperties: "0.5"}, - Library{Name: "Ethernet", Version: "1.1.1"}, - Library{Name: "Robot IR Remote", Version: "2.0.0"}, - Library{Name: "FastLED", Version: "3.1.0"}, - } - - download(t, cores, boardsManagerCores, boardsManagerRedBearCores, tools, toolsMultipleVersions, boardsManagerTools, boardsManagerRFduinoTools, libraries) - - patchFiles(t) -} - -func patchFiles(t *testing.T) { - err := patchesFolder.MkdirAll() - NoError(t, err) - files, err := patchesFolder.ReadDir() - NoError(t, err) - - for _, file := range files { - if file.Ext() == ".patch" { - panic("Patching for downloaded tools is not available! (see https://github.com/arduino/arduino-builder/issues/147)") - // XXX: find an alternative to x/codereview/patch - // https://github.com/arduino/arduino-builder/issues/147 - /* - data, err := ioutil.ReadFile(Abs(t, filepath.Join(PATCHES_FOLDER, file.Name()))) - NoError(t, err) - patchSet, err := patch.Parse(data) - NoError(t, err) - operations, err := patchSet.Apply(ioutil.ReadFile) - for _, op := range operations { - utils.WriteFileBytes(op.Dst, op.Data) - } - */ - } - } -} - -func download(t *testing.T, cores, boardsManagerCores, boardsManagerRedBearCores []Core, tools, toolsMultipleVersions, boardsManagerTools, boardsManagerRFduinoTools []Tool, libraries []Library) { - allCoresDownloaded, err := allCoresAlreadyDownloadedAndUnpacked(hardwareFolder, cores) - NoError(t, err) - if allCoresDownloaded && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerCores) && - allBoardsManagerCoresAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerRedBearCores) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerTools) && - allBoardsManagerToolsAlreadyDownloadedAndUnpacked(boardManagerFolder, boardsManagerRFduinoTools) && - allToolsAlreadyDownloadedAndUnpacked(toolsFolder, tools) && - allToolsAlreadyDownloadedAndUnpacked(toolsFolder, toolsMultipleVersions) && - allLibrariesAlreadyDownloadedAndUnpacked(librariesFolder, libraries) { - return - } - - index, err := downloadIndex("http://downloads.arduino.cc/packages/package_index.json") - NoError(t, err) - - err = downloadCores(cores, index) - NoError(t, err) - - err = downloadBoardManagerCores(boardsManagerCores, index) - NoError(t, err) - - err = downloadTools(tools, index) - NoError(t, err) - - err = downloadToolsMultipleVersions(toolsMultipleVersions, index) - NoError(t, err) - - err = downloadBoardsManagerTools(boardsManagerTools, index) - NoError(t, err) - - rfduinoIndex, err := downloadIndex("http://downloads.arduino.cc/packages/test_package_rfduino_index.json") - NoError(t, err) - - err = downloadBoardsManagerTools(boardsManagerRFduinoTools, rfduinoIndex) - NoError(t, err) - - err = downloadBoardManagerCores(boardsManagerRedBearCores, nil) - NoError(t, err) - - librariesIndex, err := downloadIndex("http://downloads.arduino.cc/libraries/library_index.json") - NoError(t, err) - - err = downloadLibraries(libraries, librariesIndex) - NoError(t, err) -} - -func downloadIndex(url string) (map[string]interface{}, error) { - res, err := http.Get(url) - if err != nil { - return nil, err - } - - bytes, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, err - } - res.Body.Close() - - index := make(map[string]interface{}) - err = json.Unmarshal(bytes, &index) - if err != nil { - return nil, err - } - - return index, nil -} - -func downloadCores(cores []Core, index map[string]interface{}) error { - for _, core := range cores { - url, err := findCoreUrl(index, core) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackCore(core, url, hardwareFolder) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func downloadBoardManagerCores(cores []Core, index map[string]interface{}) error { - for _, core := range cores { - url, err := findCoreUrl(index, core) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackBoardManagerCore(core, url, boardManagerFolder) - if err != nil { - return i18n.WrapError(err) - } - } - return nil -} - -func findCoreUrl(index map[string]interface{}, core Core) (string, error) { - if core.Url != "" { - return core.Url, nil - } - packages := index["packages"].([]interface{}) - for _, p := range packages { - pack := p.(map[string]interface{}) - if pack[constants.PACKAGE_NAME].(string) == core.Maintainer { - packagePlatforms := pack["platforms"].([]interface{}) - for _, pt := range packagePlatforms { - packagePlatform := pt.(map[string]interface{}) - if packagePlatform[constants.PLATFORM_ARCHITECTURE] == core.Arch && packagePlatform[constants.PLATFORM_VERSION] == core.Version { - return packagePlatform[constants.PLATFORM_URL].(string), nil - } - } - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find tool " + core.Maintainer + " " + core.Arch + " " + core.Version) -} - -func downloadTools(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackTool(tool, url, toolsFolder, true) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func downloadToolsMultipleVersions(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - if !toolAlreadyDownloadedAndUnpacked(toolsFolder, tool) { - if toolsFolder.Join(tool.Name).Exist() { - if err := toolsFolder.Join(tool.Name).RemoveAll(); err != nil { - return i18n.WrapError(err) - } - } - } - } - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackTool(tool, url, toolsFolder, false) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func downloadBoardsManagerTools(tools []Tool, index map[string]interface{}) error { - host := translateGOOSGOARCHToPackageIndexValue() - - for _, tool := range tools { - url, err := findToolUrl(index, tool, host) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackBoardsManagerTool(tool, url, boardManagerFolder) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func allBoardsManagerCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) bool { - for _, core := range cores { - if !boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { - return false - } - } - return true -} - -func boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) bool { - return targetPath.Join(core.Maintainer, "hardware", core.Arch, core.Version).Exist() -} - -func allCoresAlreadyDownloadedAndUnpacked(targetPath *paths.Path, cores []Core) (bool, error) { - for _, core := range cores { - alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) - if err != nil { - return false, i18n.WrapError(err) - } - if !alreadyDownloaded { - return false, nil - } - } - return true, nil -} - -func coreAlreadyDownloadedAndUnpacked(targetPath *paths.Path, core Core) (bool, error) { - corePath := targetPath.Join(core.Maintainer, core.Arch) - - if corePath.NotExist() { - return false, nil - } - platform, err := properties.LoadFromPath(corePath.Join("platform.txt")) - if err != nil { - return false, i18n.WrapError(err) - } - - if core.Version != platform.Get("version") { - err := corePath.RemoveAll() - return false, i18n.WrapError(err) - } - - return true, nil -} - -func allBoardsManagerToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) bool { - for _, tool := range tools { - if !boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return false - } - } - return true -} - -func boardManagerToolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { - return targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).Exist() -} - -func allToolsAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tools []Tool) bool { - for _, tool := range tools { - if !toolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return false - } - } - return true -} - -func toolAlreadyDownloadedAndUnpacked(targetPath *paths.Path, tool Tool) bool { - return targetPath.Join(tool.Name, tool.Version).Exist() -} - -func allLibrariesAlreadyDownloadedAndUnpacked(targetPath *paths.Path, libraries []Library) bool { - for _, library := range libraries { - if !libraryAlreadyDownloadedAndUnpacked(targetPath, library) { - return false - } - } - return true -} - -func libraryAlreadyDownloadedAndUnpacked(targetPath *paths.Path, library Library) bool { - libPath := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)) - if !libPath.Exist() { - return false - } - - libProps, err := properties.LoadFromPath(libPath.Join("library.properties")) - if err != nil { - return false - } - return libProps.Get("version") == library.Version || libProps.Get("version") == library.VersionInLibProperties -} - -func downloadAndUnpackCore(core Core, url string, targetPath *paths.Path) error { - alreadyDownloaded, err := coreAlreadyDownloadedAndUnpacked(targetPath, core) - if err != nil { - return i18n.WrapError(err) - } - if alreadyDownloaded { - return nil - } - - if err := targetPath.ToAbs(); err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer unpackFolder.RemoveAll() - - packagerPath := targetPath.Join(core.Maintainer) - corePath := targetPath.Join(core.Maintainer, core.Arch) - - if corePath.Exist() { - if err := corePath.RemoveAll(); err != nil { - return i18n.WrapError(err) - } - } - - if len(files) == 1 && files[0].IsDir() { - if err := packagerPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(core.Maintainer, core.Arch)) - if err != nil { - return i18n.WrapError(err) - } - } else { - if err := targetPath.Join(core.Maintainer, core.Arch).MkdirAll(); err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(core.Maintainer, core.Arch, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackBoardManagerCore(core Core, url string, targetPath *paths.Path) error { - if boardManagerCoreAlreadyDownloadedAndUnpacked(targetPath, core) { - return nil - } - - if err := targetPath.ToAbs(); err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer unpackFolder.RemoveAll() - - corePath := targetPath.Join(core.Maintainer, "hardware", core.Arch) - if corePath.Exist() { - if err := corePath.RemoveAll(); err != nil { - return i18n.WrapError(err) - } - } - - if len(files) == 1 && files[0].IsDir() { - if err := corePath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(unpackFolder.Join(files[0].Name()), corePath.Join(core.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - if err := corePath.Join(core.Version).MkdirAll(); err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), corePath.Join(core.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackBoardsManagerTool(tool Tool, url string, targetPath *paths.Path) error { - if boardManagerToolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return nil - } - - if err := targetPath.ToAbs(); err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer unpackFolder.RemoveAll() - - if len(files) == 1 && files[0].IsDir() { - if err := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name).MkdirAll(); err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(unpackFolder.Join(files[0].Name()), targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - if err := targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version).MkdirAll(); err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), targetPath.Join(tool.Package, constants.FOLDER_TOOLS, tool.Name, tool.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpackTool(tool Tool, url string, targetPath *paths.Path, deleteIfMissing bool) error { - if toolAlreadyDownloadedAndUnpacked(targetPath, tool) { - return nil - } - - if err := targetPath.ToAbs(); err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer unpackFolder.RemoveAll() - - toolPath := targetPath.Join(tool.Name) - if deleteIfMissing { - if toolPath.Exist() { - if err := toolPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - } - } - - if len(files) == 1 && files[0].IsDir() { - if err := toolPath.MkdirAll(); err != nil { - return i18n.WrapError(err) - } - err = copyRecursive(unpackFolder.Join(files[0].Name()), toolPath.Join(tool.Version)) - if err != nil { - return i18n.WrapError(err) - } - } else { - if err := toolPath.Join(tool.Version).MkdirAll(); err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - err = copyRecursive(unpackFolder.Join(file.Name()), toolPath.Join(tool.Version, file.Name())) - if err != nil { - return i18n.WrapError(err) - } - } - } - - return nil -} - -func downloadAndUnpack(url string) (*paths.Path, []os.FileInfo, error) { - fmt.Fprintln(os.Stderr, "Downloading "+url) - - unpackFolder, err := paths.MkTempDir("", "arduino-builder-tool") - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - urlParts := strings.Split(url, "/") - archiveFileName := urlParts[len(urlParts)-1] - archiveFilePath := unpackFolder.Join(archiveFileName) - - res, err := http.Get(url) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - bytes, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - res.Body.Close() - - archiveFilePath.WriteFile(bytes) - - cmd := buildUnpackCmd(archiveFilePath) - out, err := cmd.CombinedOutput() - if err != nil { - fmt.Println(string(out)) - return nil, nil, i18n.WrapError(err) - } - if len(out) > 0 { - fmt.Println(string(out)) - } - - archiveFilePath.Remove() - - files, err := gohasissues.ReadDir(unpackFolder.String()) - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - return unpackFolder, files, nil -} - -func buildUnpackCmd(file *paths.Path) *exec.Cmd { - var cmd *exec.Cmd - if file.Ext() == ".zip" { - cmd = exec.Command("unzip", "-qq", file.Base()) - } else { - cmd = exec.Command("tar", "xf", file.Base()) - } - cmd.Dir = file.Parent().String() - return cmd -} - -func translateGOOSGOARCHToPackageIndexValue() []string { - switch value := runtime.GOOS + "-" + runtime.GOARCH; value { - case "linux-amd64": - return []string{"x86_64-pc-linux-gnu", "x86_64-linux-gnu"} - case "linux-386": - return []string{"i686-pc-linux-gnu", "i686-linux-gnu"} - case "windows-amd64": - return []string{"i686-mingw32", "i686-cygwin"} - case "windows-386": - return []string{"i686-mingw32", "i686-cygwin"} - case "darwin-amd64": - return []string{"i386-apple-darwin11", "x86_64-apple-darwin"} - case "linux-arm": - return []string{"arm-linux-gnueabihf"} - default: - panic("Unknown OS: " + value) - } -} - -func findToolUrl(index map[string]interface{}, tool Tool, host []string) (string, error) { - if len(tool.OsUrls) > 0 { - for _, osUrl := range tool.OsUrls { - if utils.SliceContains(host, osUrl.Os) { - return osUrl.Url, nil - } - } - } else { - packages := index["packages"].([]interface{}) - for _, p := range packages { - pack := p.(map[string]interface{}) - packageTools := pack[constants.PACKAGE_TOOLS].([]interface{}) - for _, pt := range packageTools { - packageTool := pt.(map[string]interface{}) - name := packageTool[constants.TOOL_NAME].(string) - version := packageTool[constants.TOOL_VERSION].(string) - if name == tool.Name && version == tool.Version { - systems := packageTool["systems"].([]interface{}) - for _, s := range systems { - system := s.(map[string]interface{}) - if utils.SliceContains(host, system["host"].(string)) { - return system[constants.TOOL_URL].(string), nil - } - } - } - } - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find tool " + tool.Name + " " + tool.Version) -} - -func downloadLibraries(libraries []Library, index map[string]interface{}) error { - for _, library := range libraries { - url, err := findLibraryUrl(index, library) - if err != nil { - return i18n.WrapError(err) - } - err = downloadAndUnpackLibrary(library, url, librariesFolder) - if err != nil { - return i18n.WrapError(err) - } - } - - return nil -} - -func findLibraryUrl(index map[string]interface{}, library Library) (string, error) { - if library.Url != "" { - return library.Url, nil - } - libs := index["libraries"].([]interface{}) - for _, l := range libs { - lib := l.(map[string]interface{}) - if library.Name == lib["name"].(string) && library.Version == lib["version"].(string) { - return lib["url"].(string), nil - } - } - - return constants.EMPTY_STRING, errors.Errorf("Unable to find library " + library.Name + " " + library.Version) -} - -func downloadAndUnpackLibrary(library Library, url string, targetPath *paths.Path) error { - if libraryAlreadyDownloadedAndUnpacked(targetPath, library) { - return nil - } - - if err := targetPath.ToAbs(); err != nil { - return i18n.WrapError(err) - } - - unpackFolder, files, err := downloadAndUnpack(url) - if err != nil { - return i18n.WrapError(err) - } - defer unpackFolder.RemoveAll() - - libPath := targetPath.Join(strings.Replace(library.Name, " ", "_", -1)) - if libPath.Exist() { - if err := libPath.RemoveAll(); err != nil { - return i18n.WrapError(err) - } - } - - err = copyRecursive(unpackFolder.Join(files[0].Name()), libPath) - if err != nil { - return i18n.WrapError(err) - } - - return nil -} - -func copyRecursive(from, to *paths.Path) error { - copyFunc := func(currentPath string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - rel, err := filepath.Rel(from.String(), currentPath) - if err != nil { - return i18n.WrapError(err) - } - targetPath := filepath.Join(to.String(), rel) - if info.IsDir() { - err := os.MkdirAll(targetPath, info.Mode()) - if err != nil { - return i18n.WrapError(err) - } - } else if info.Mode().IsRegular() { - fromFile, err := os.Open(currentPath) - if err != nil { - return i18n.WrapError(err) - } - defer fromFile.Close() - targetFile, err := os.Create(targetPath) - if err != nil { - return i18n.WrapError(err) - } - defer targetFile.Close() - _, err = io.Copy(targetFile, fromFile) - if err != nil { - return i18n.WrapError(err) - } - err = os.Chmod(targetPath, info.Mode()) - if err != nil { - return i18n.WrapError(err) - } - } else if info.Mode()&os.ModeSymlink == os.ModeSymlink { - linkedFile, err := os.Readlink(currentPath) - if err != nil { - return i18n.WrapError(err) - } - fromFile := filepath.Join(filepath.Dir(targetPath), linkedFile) - err = os.Symlink(fromFile, targetPath) - if err != nil { - return i18n.WrapError(err) - } - } else { - return errors.Errorf("unable to copy file " + currentPath) - } - - return nil - } - err := gohasissues.Walk(from.String(), copyFunc) - return i18n.WrapError(err) -} diff --git a/test/i18n_test.go b/test/i18n_test.go deleted file mode 100644 index dbfae0d3..00000000 --- a/test/i18n_test.go +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "fmt" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/i18n" - "github.com/stretchr/testify/require" - "testing" -) - -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/test/includes_finder_with_regexp_test.go b/test/includes_finder_with_regexp_test.go deleted file mode 100644 index c3c048cc..00000000 --- a/test/includes_finder_with_regexp_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestIncludesFinderWithRegExp(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:17: fatal error: SPI.h: No such file or directory\n" + - "#include \n" + - "^\n" + - "compilation terminated." - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "SPI.h", include) -} - -func TestIncludesFinderWithRegExpEmptyOutput(t *testing.T) { - ctx := &types.Context{} - - include := builder.IncludesFinderWithRegExp(ctx, "") - - require.Equal(t, "", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: Wire.h: No such file or directory\n" + - " # include \n" + - " ^\n" + - "compilation terminated.\n" - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "Wire.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes2(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: Wire.h: No such file or directory\n" + - " #\t\t\tinclude \n" + - " ^\n" + - "compilation terminated.\n" - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "Wire.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes3(t *testing.T) { - ctx := &types.Context{} - - output := "/some/path/sketch.ino:1:33: fatal error: SPI.h: No such file or directory\n" + - "compilation terminated.\n" - - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "SPI.h", include) -} - -func TestIncludesFinderWithRegExpPaddedIncludes4(t *testing.T) { - ctx := &types.Context{} - - output := "In file included from /tmp/arduino_modified_sketch_815412/binouts.ino:52:0:\n" + - "/tmp/arduino_build_static/sketch/regtable.h:31:22: fatal error: register.h: No such file or directory\n" - - include := builder.IncludesFinderWithRegExp(ctx, output) - - require.Equal(t, "register.h", include) -} diff --git a/test/includes_to_include_folders_test.go b/test/includes_to_include_folders_test.go deleted file mode 100644 index 59f60c4c..00000000 --- a/test/includes_to_include_folders_test.go +++ /dev/null @@ -1,339 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "fmt" - "path/filepath" - "sort" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestIncludesToIncludeFolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "Bridge", importedLibraries[0].Name) -} - -func TestIncludesToIncludeFoldersSketchWithIfDef(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - require.Equal(t, 0, len(importedLibraries)) -} - -func TestIncludesToIncludeFoldersIRremoteLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch9", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 2, len(importedLibraries)) - require.Equal(t, "Bridge", importedLibraries[0].Name) - require.Equal(t, "IRremote", importedLibraries[1].Name) -} - -func TestIncludesToIncludeFoldersANewLibrary(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch10", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.ContainerMergeCopySketchFiles{}, - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 2, len(importedLibraries)) - require.Equal(t, "ANewLibrary-master", importedLibraries[0].Name) - require.Equal(t, "IRremote", importedLibraries[1].Name) -} - -func TestIncludesToIncludeFoldersDuplicateLibs(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "SPI", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("user_hardware", "my_avr_platform", "avr", "libraries", "SPI")) -} - -func TestIncludesToIncludeFoldersDuplicateLibsWithConflictingLibsOutsideOfPlatform(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("user_hardware", "my_avr_platform", "avr", "libraries", "SPI", "examples", "BarometricPressureSensor", "BarometricPressureSensor.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "SPI", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("libraries", "SPI")) -} - -func TestIncludesToIncludeFoldersDuplicateLibs2(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_usbhost", "sketch_usbhost.ino"), - FQBN: parseFQBN(t, "arduino:samd:arduino_zero_native"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - require.Equal(t, 1, len(importedLibraries)) - require.Equal(t, "USBHost", importedLibraries[0].Name) - requireEquivalentPaths(t, importedLibraries[0].SourceDir.String(), filepath.Join("libraries", "USBHost", "src")) -} - -func TestIncludesToIncludeFoldersSubfolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_with_subfolders", "sketch_with_subfolders.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - importedLibraries := ctx.ImportedLibraries - sort.Sort(ByLibraryName(importedLibraries)) - fmt.Println(importedLibraries) - require.Equal(t, 3, len(importedLibraries)) - require.Equal(t, "testlib1", importedLibraries[0].Name) - require.Equal(t, "testlib2", importedLibraries[1].Name) - require.Equal(t, "testlib3", importedLibraries[2].Name) -} diff --git a/test/libraries/ANewLibrary-master/anewlibrary.h b/test/libraries/ANewLibrary-master/anewlibrary.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Balanduino.h b/test/libraries/Balanduino/Balanduino.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Kalman.h b/test/libraries/Balanduino/Kalman.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/PS3BT.h b/test/libraries/Balanduino/PS3BT.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/SPP.h b/test/libraries/Balanduino/SPP.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/Wii.h b/test/libraries/Balanduino/Wii.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/XBOXRECV.h b/test/libraries/Balanduino/XBOXRECV.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/adk.h b/test/libraries/Balanduino/adk.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/Balanduino/usbhub.h b/test/libraries/Balanduino/usbhub.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/FakeAudio/Audio.h b/test/libraries/FakeAudio/Audio.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/FakeAudio/FakeAudio.h b/test/libraries/FakeAudio/FakeAudio.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/IRremote/IRremote.h b/test/libraries/IRremote/IRremote.h deleted file mode 100644 index 5497fbd7..00000000 --- a/test/libraries/IRremote/IRremote.h +++ /dev/null @@ -1 +0,0 @@ -#warning IRRemote included! \ No newline at end of file diff --git a/test/libraries/IRremote/IRremoteInt.h b/test/libraries/IRremote/IRremoteInt.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/SPI/SPI.cpp b/test/libraries/SPI/SPI.cpp deleted file mode 100644 index af14e07b..00000000 --- a/test/libraries/SPI/SPI.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "SPI.h" - -SPIClass SPI; - -uint8_t SPIClass::initialized = 0; -uint8_t SPIClass::interruptMode = 0; -uint8_t SPIClass::interruptMask = 0; -uint8_t SPIClass::interruptSave = 0; -#ifdef SPI_TRANSACTION_MISMATCH_LED -uint8_t SPIClass::inTransactionFlag = 0; -#endif - -void SPIClass::begin() -{ - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - if (!initialized) { - // Set SS to high so a connected chip will be "deselected" by default - uint8_t port = digitalPinToPort(SS); - uint8_t bit = digitalPinToBitMask(SS); - volatile uint8_t *reg = portModeRegister(port); - - // if the SS pin is not already configured as an output - // then set it high (to enable the internal pull-up resistor) - if(!(*reg & bit)){ - digitalWrite(SS, HIGH); - } - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); - } - initialized++; // reference count - SREG = sreg; -} - -void SPIClass::end() { - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - // Decrease the reference counter - if (initialized) - initialized--; - // If there are no more references disable SPI - if (!initialized) { - SPCR &= ~_BV(SPE); - interruptMode = 0; - #ifdef SPI_TRANSACTION_MISMATCH_LED - inTransactionFlag = 0; - #endif - } - SREG = sreg; -} - -// mapping of interrupt numbers to bits within SPI_AVR_EIMSK -#if defined(__AVR_ATmega32U4__) - #define SPI_INT0_MASK (1< - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include - -// SPI_HAS_TRANSACTION means SPI has beginTransaction(), endTransaction(), -// usingInterrupt(), and SPISetting(clock, bitOrder, dataMode) -#define SPI_HAS_TRANSACTION 1 - -// SPI_HAS_NOTUSINGINTERRUPT means that SPI has notUsingInterrupt() method -#define SPI_HAS_NOTUSINGINTERRUPT 1 - -// SPI_ATOMIC_VERSION means that SPI has atomicity fixes and what version. -// This way when there is a bug fix you can check this define to alert users -// of your code if it uses better version of this library. -// This also implies everything that SPI_HAS_TRANSACTION as documented above is -// available too. -#define SPI_ATOMIC_VERSION 1 - -// Uncomment this line to add detection of mismatched begin/end transactions. -// A mismatch occurs if other libraries fail to use SPI.endTransaction() for -// each SPI.beginTransaction(). Connect an LED to this pin. The LED will turn -// on if any mismatch is ever detected. -//#define SPI_TRANSACTION_MISMATCH_LED 5 - -#ifndef LSBFIRST -#define LSBFIRST 0 -#endif -#ifndef MSBFIRST -#define MSBFIRST 1 -#endif - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -// define SPI_AVR_EIMSK for AVR boards with external interrupt pins -#if defined(EIMSK) - #define SPI_AVR_EIMSK EIMSK -#elif defined(GICR) - #define SPI_AVR_EIMSK GICR -#elif defined(GIMSK) - #define SPI_AVR_EIMSK GIMSK -#endif - -class SPISettings { -public: - SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - if (__builtin_constant_p(clock)) { - init_AlwaysInline(clock, bitOrder, dataMode); - } else { - init_MightInline(clock, bitOrder, dataMode); - } - } - SPISettings() { - init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); - } -private: - void init_MightInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - init_AlwaysInline(clock, bitOrder, dataMode); - } - void init_AlwaysInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) - __attribute__((__always_inline__)) { - // Clock settings are defined as follows. Note that this shows SPI2X - // inverted, so the bits form increasing numbers. Also note that - // fosc/64 appears twice - // SPR1 SPR0 ~SPI2X Freq - // 0 0 0 fosc/2 - // 0 0 1 fosc/4 - // 0 1 0 fosc/8 - // 0 1 1 fosc/16 - // 1 0 0 fosc/32 - // 1 0 1 fosc/64 - // 1 1 0 fosc/64 - // 1 1 1 fosc/128 - - // We find the fastest clock that is less than or equal to the - // given clock rate. The clock divider that results in clock_setting - // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the - // slowest (128 == 2 ^^ 7, so clock_div = 6). - uint8_t clockDiv; - - // When the clock is known at compiletime, use this if-then-else - // cascade, which the compiler knows how to completely optimize - // away. When clock is not known, use a loop instead, which generates - // shorter code. - if (__builtin_constant_p(clock)) { - if (clock >= F_CPU / 2) { - clockDiv = 0; - } else if (clock >= F_CPU / 4) { - clockDiv = 1; - } else if (clock >= F_CPU / 8) { - clockDiv = 2; - } else if (clock >= F_CPU / 16) { - clockDiv = 3; - } else if (clock >= F_CPU / 32) { - clockDiv = 4; - } else if (clock >= F_CPU / 64) { - clockDiv = 5; - } else { - clockDiv = 6; - } - } else { - uint32_t clockSetting = F_CPU / 2; - clockDiv = 0; - while (clockDiv < 6 && clock < clockSetting) { - clockSetting /= 2; - clockDiv++; - } - } - - // Compensate for the duplicate fosc/64 - if (clockDiv == 6) - clockDiv = 7; - - // Invert the SPI2X bit - clockDiv ^= 0x1; - - // Pack into the SPISettings class - spcr = _BV(SPE) | _BV(MSTR) | ((bitOrder == LSBFIRST) ? _BV(DORD) : 0) | - (dataMode & SPI_MODE_MASK) | ((clockDiv >> 1) & SPI_CLOCK_MASK); - spsr = clockDiv & SPI_2XCLOCK_MASK; - } - uint8_t spcr; - uint8_t spsr; - friend class SPIClass; -}; - - -class SPIClass { -public: - // Initialize the SPI library - static void begin(); - - // If SPI is used from within an interrupt, this function registers - // that interrupt with the SPI library, so beginTransaction() can - // prevent conflicts. The input interruptNumber is the number used - // with attachInterrupt. If SPI is used from a different interrupt - // (eg, a timer), interruptNumber should be 255. - static void usingInterrupt(uint8_t interruptNumber); - // And this does the opposite. - static void notUsingInterrupt(uint8_t interruptNumber); - // Note: the usingInterrupt and notUsingInterrupt functions should - // not to be called from ISR context or inside a transaction. - // For details see: - // https://github.com/arduino/Arduino/pull/2381 - // https://github.com/arduino/Arduino/pull/2449 - - // Before using SPI.transfer() or asserting chip select pins, - // this function is used to gain exclusive access to the SPI bus - // and configure the correct settings. - inline static void beginTransaction(SPISettings settings) { - if (interruptMode > 0) { - uint8_t sreg = SREG; - noInterrupts(); - - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - interruptSave = SPI_AVR_EIMSK; - SPI_AVR_EIMSK &= ~interruptMask; - SREG = sreg; - } else - #endif - { - interruptSave = sreg; - } - } - - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 1; - #endif - - SPCR = settings.spcr; - SPSR = settings.spsr; - } - - // Write to the SPI bus (MOSI pin) and also receive (MISO pin) - inline static uint8_t transfer(uint8_t data) { - SPDR = data; - /* - * The following NOP introduces a small delay that can prevent the wait - * loop form iterating when running at the maximum speed. This gives - * about 10% more speed, even if it seems counter-intuitive. At lower - * speeds it is unnoticed. - */ - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; // wait - return SPDR; - } - inline static uint16_t transfer16(uint16_t data) { - union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; - in.val = data; - if (!(SPCR & _BV(DORD))) { - SPDR = in.msb; - asm volatile("nop"); // See transfer(uint8_t) function - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - } else { - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - SPDR = in.msb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - } - return out.val; - } - inline static void transfer(void *buf, size_t count) { - if (count == 0) return; - uint8_t *p = (uint8_t *)buf; - SPDR = *p; - while (--count > 0) { - uint8_t out = *(p + 1); - while (!(SPSR & _BV(SPIF))) ; - uint8_t in = SPDR; - SPDR = out; - *p++ = in; - } - while (!(SPSR & _BV(SPIF))) ; - *p = SPDR; - } - // After performing a group of transfers and releasing the chip select - // signal, this function allows others to access the SPI bus - inline static void endTransaction(void) { - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (!inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 0; - #endif - - if (interruptMode > 0) { - #ifdef SPI_AVR_EIMSK - uint8_t sreg = SREG; - #endif - noInterrupts(); - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - SPI_AVR_EIMSK = interruptSave; - SREG = sreg; - } else - #endif - { - SREG = interruptSave; - } - } - } - - // Disable the SPI bus - static void end(); - - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setBitOrder(uint8_t bitOrder) { - if (bitOrder == LSBFIRST) SPCR |= _BV(DORD); - else SPCR &= ~(_BV(DORD)); - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setDataMode(uint8_t dataMode) { - SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode; - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setClockDivider(uint8_t clockDiv) { - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK); - } - // These undocumented functions should not be used. SPI.transfer() - // polls the hardware flag which is automatically cleared as the - // AVR responds to SPI's interrupt - inline static void attachInterrupt() { SPCR |= _BV(SPIE); } - inline static void detachInterrupt() { SPCR &= ~_BV(SPIE); } - -private: - static uint8_t initialized; - static uint8_t interruptMode; // 0=none, 1=mask, 2=global - static uint8_t interruptMask; // which interrupts to mask - static uint8_t interruptSave; // temp storage, to restore state - #ifdef SPI_TRANSACTION_MISMATCH_LED - static uint8_t inTransactionFlag; - #endif -}; - -extern SPIClass SPI; - -#endif diff --git a/test/libraries/SPI/keywords.txt b/test/libraries/SPI/keywords.txt deleted file mode 100644 index fa761658..00000000 --- a/test/libraries/SPI/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SPI KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 -transfer KEYWORD2 -setBitOrder KEYWORD2 -setDataMode KEYWORD2 -setClockDivider KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -SPI_CLOCK_DIV4 LITERAL1 -SPI_CLOCK_DIV16 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_CLOCK_DIV128 LITERAL1 -SPI_CLOCK_DIV2 LITERAL1 -SPI_CLOCK_DIV8 LITERAL1 -SPI_CLOCK_DIV32 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_MODE0 LITERAL1 -SPI_MODE1 LITERAL1 -SPI_MODE2 LITERAL1 -SPI_MODE3 LITERAL1 \ No newline at end of file diff --git a/test/libraries/SPI/library.properties b/test/libraries/SPI/library.properties deleted file mode 100644 index 7e55b100..00000000 --- a/test/libraries/SPI/library.properties +++ /dev/null @@ -1,11 +0,0 @@ -name=SPI -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE. -paragraph= -url=http://arduino.cc/en/Reference/SPI -architectures=avr -types=Arduino -category=Other - diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.h b/test/libraries/ShouldNotRecurseWithOldLibs/ShouldNotRecurseWithOldLibs.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp deleted file mode 100644 index 28fe130c..00000000 --- a/test/libraries/ShouldNotRecurseWithOldLibs/doc/error.cpp +++ /dev/null @@ -1 +0,0 @@ - #error "This file is never supposed to be compiled" diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.cpp b/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.cpp deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.h b/test/libraries/ShouldNotRecurseWithOldLibs/utility/utils.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/USBHost/keywords.txt b/test/libraries/USBHost/keywords.txt deleted file mode 100644 index dded4dcf..00000000 --- a/test/libraries/USBHost/keywords.txt +++ /dev/null @@ -1,35 +0,0 @@ -####################################### -# Syntax Coloring Map For USBHost -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -MouseController KEYWORD1 -USBHost KEYWORD1 -KeyboardController KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -Task KEYWORD2 -mouseMoved KEYWORD2 -mouseDragged KEYWORD2 -mousePressed KEYWORD2 -mouseReleased KEYWORD2 -getXChange KEYWORD2 -getYChange KEYWORD2 -getButton KEYWORD2 -keyPressed KEYWORD2 -keyReleased KEYWORD2 -getModifiers KEYWORD2 -getKey KEYWORD2 -getOemKey KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/test/libraries/USBHost/library.properties b/test/libraries/USBHost/library.properties deleted file mode 100644 index b6bdce97..00000000 --- a/test/libraries/USBHost/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=USBHost -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Allows the communication with USB peripherals like mice, keyboards, and thumbdrives. For Arduino Due and Zero. -paragraph=The USBHost library allows the board to appear as a USB host, enabling it to communicate with peripherals like USB mice and keyboards. USBHost does not support devices that are connected through USB hubs. This includes some keyboards that have an internal hub. -url=http://arduino.cc/en/Reference/USBHost -architectures=samd -category=Other diff --git a/test/libraries/USBHost/src/KeyboardController.cpp b/test/libraries/USBHost/src/KeyboardController.cpp deleted file mode 100644 index 70c769f6..00000000 --- a/test/libraries/USBHost/src/KeyboardController.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -extern "C" { -void __keyboardControllerEmptyCallback() { } -} - -void keyPressed() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback"))); -void keyReleased() __attribute__ ((weak, alias("__keyboardControllerEmptyCallback"))); - -void KeyboardController::OnKeyDown(uint8_t _mod, uint8_t _oemKey) { - modifiers = _mod; - keyOem = _oemKey; - key = OemToAscii(_mod, _oemKey); - keyPressed(); -} - -void KeyboardController::OnKeyUp(uint8_t _mod, uint8_t _oemKey) { - modifiers = _mod; - keyOem = _oemKey; - key = OemToAscii(_mod, _oemKey); - keyReleased(); -} diff --git a/test/libraries/USBHost/src/KeyboardController.h b/test/libraries/USBHost/src/KeyboardController.h deleted file mode 100644 index e1b891bf..00000000 --- a/test/libraries/USBHost/src/KeyboardController.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef KEYBOARD_CONTROLLER_H -#define KEYBOARD_CONTROLLER_H - -#include - -enum KeyboardModifiers { - LeftCtrl = 1, - LeftShift = 2, - Alt = 4, - LeftCmd = 8, - RightCtrl = 16, - RightShift = 32, - AltGr = 64, - RightCmd = 128 -}; - -class KeyboardController : public KeyboardReportParser { -public: - KeyboardController(USBHost &usb) : hostKeyboard(&usb), key(0), keyOem(0), modifiers(0) { - hostKeyboard.SetReportParser(0, this); - }; - - uint8_t getKey() { return key; }; - uint8_t getModifiers() { return modifiers; }; - uint8_t getOemKey() { return keyOem; }; - -protected: - virtual void OnKeyDown(uint8_t mod, uint8_t key); - virtual void OnKeyUp(uint8_t mod, uint8_t key); - -private: - HIDBoot hostKeyboard; - uint8_t key, keyOem, modifiers; -}; - -#endif diff --git a/test/libraries/USBHost/src/MouseController.cpp b/test/libraries/USBHost/src/MouseController.cpp deleted file mode 100644 index 3d528bc3..00000000 --- a/test/libraries/USBHost/src/MouseController.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include - -extern "C" { -void __mouseControllerEmptyCallback() { } -} - -void mouseClicked() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseDragged() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseMoved() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mousePressed() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); -void mouseReleased() __attribute__ ((weak, alias("__mouseControllerEmptyCallback"))); - -int MouseController::getXChange() { - int r = dx; - dx = 0; - return r; -} - -int MouseController::getYChange() { - int r = dy; - dy = 0; - return r; -} - -void MouseController::OnMouseMove(MOUSEINFO *mi) { - dx += mi->dX; - dy += mi->dY; - if (buttons != 0) - mouseDragged(); - else - mouseMoved(); -} - -void MouseController::OnLeftButtonUp(MOUSEINFO *mi) { - buttons &= ~LEFT_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnLeftButtonDown(MOUSEINFO *mi) { - buttons |= LEFT_BUTTON; - mousePressed(); -} - -void MouseController::OnMiddleButtonUp(MOUSEINFO *mi) { - buttons &= ~MIDDLE_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnMiddleButtonDown(MOUSEINFO *mi) { - buttons |= MIDDLE_BUTTON; - mousePressed(); -} - -void MouseController::OnRightButtonUp(MOUSEINFO *mi) { - buttons &= ~RIGHT_BUTTON; - mouseReleased(); - mouseClicked(); -} - -void MouseController::OnRightButtonDown(MOUSEINFO *mi) { - buttons |= RIGHT_BUTTON; - mousePressed(); -} diff --git a/test/libraries/USBHost/src/MouseController.h b/test/libraries/USBHost/src/MouseController.h deleted file mode 100644 index 4c8c65e9..00000000 --- a/test/libraries/USBHost/src/MouseController.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - Copyright (c) 2012 Arduino. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef MOUSE_CONTROLLER_H -#define MOUSE_CONTROLLER_H - -#include - -enum MouseButton { - LEFT_BUTTON = 0x01, - MIDDLE_BUTTON = 0x02, - RIGHT_BUTTON = 0x04 -}; - -class MouseController : public MouseReportParser -{ -public: - MouseController(USBHost &usb) : hostMouse(&usb), dx(0), dy(0), buttons(0) { - hostMouse.SetReportParser(0, this); - }; - - bool getButton(MouseButton button) { return (buttons & button) == button; }; - int getXChange(); - int getYChange(); - // int getWheelChange(); // Not implemented - -protected: - virtual void OnMouseMove(MOUSEINFO *mi); - virtual void OnLeftButtonUp(MOUSEINFO *mi); - virtual void OnLeftButtonDown(MOUSEINFO *mi); - virtual void OnMiddleButtonUp(MOUSEINFO *mi); - virtual void OnMiddleButtonDown(MOUSEINFO *mi); - virtual void OnRightButtonUp(MOUSEINFO *mi); - virtual void OnRightButtonDown(MOUSEINFO *mi); - -private: - HIDBoot hostMouse; - int dx, dy; - int buttons; -}; - -#endif diff --git a/test/libraries/USBHost/src/Usb.cpp b/test/libraries/USBHost/src/Usb.cpp deleted file mode 100644 index bc821bb1..00000000 --- a/test/libraries/USBHost/src/Usb.cpp +++ /dev/null @@ -1,857 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -/* USB functions */ - -#include -#include "Arduino.h" -#include "Usb.h" - - -#ifdef ARDUINO_SAMD_ZERO - -static uint32_t usb_error = 0; -static uint32_t usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; - -/* constructor */ -USBHost::USBHost() : bmHubPre(0) { - // Set up state machine - usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; //set up state machine -} - -/* Initialize data structures */ -uint32_t USBHost::Init() { - //devConfigIndex = 0; - // Init host stack - init(); - bmHubPre = 0; - UHD_Init(); - return 0; -} - -uint32_t USBHost::getUsbTaskState(void) { - return (usb_task_state); -} - -void USBHost::setUsbTaskState(uint32_t state) { - usb_task_state = state; -} - -EpInfo* USBHost::getEpInfoEntry(uint32_t addr, uint32_t ep) { - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p || !p->epinfo) - return NULL; - - EpInfo *pep = p->epinfo; - - for (uint32_t i = 0; i < p->epcount; i++) { - if(pep->epAddr == ep) - return pep; - - pep++; - } - return NULL; -} - -/* set device table entry */ - -/* each device is different and has different number of endpoints. This function plugs endpoint record structure, defined in application, to devtable */ -uint32_t USBHost::setEpInfoEntry(uint32_t addr, uint32_t epcount, EpInfo* eprecord_ptr) { - if (!eprecord_ptr) - return USB_ERROR_INVALID_ARGUMENT; - - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->address.devAddress = addr; - p->epinfo = eprecord_ptr; - p->epcount = epcount; - - return 0; -} - -uint32_t USBHost::SetPipeAddress(uint32_t addr, uint32_t ep, EpInfo **ppep, uint32_t &nak_limit) { - UsbDeviceDefinition *p = addrPool.GetUsbDevicePtr(addr); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - *ppep = getEpInfoEntry(addr, ep); - - if(!*ppep) - return USB_ERROR_EP_NOT_FOUND_IN_TBL; - - nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER ) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower)); - nak_limit--; - TRACE_USBHOST(printf(" => SetPipeAddress deviceEP=%lu configued as hostPIPE=%lu sending to address=%lu\r\n", ep, (*ppep)->epAddr, addr);) - /* - USBTRACE2("\r\nAddress: ", addr); - USBTRACE2(" EP: ", ep); - USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower); - USBTRACE2(" NAK Limit: ", nak_limit); - USBTRACE("\r\n"); - */ - - // CTRL_PIPE.PDADDR: usb_pipe_table[pipe_num].HostDescBank[0].CTRL_PIPE.bit.PDADDR = addr - uhd_configure_address((*ppep)->epAddr, addr); // Set peripheral address - - return 0; -} - -/* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */ -/* depending on request. Actual requests are defined as inlines */ -/* return codes: */ -/* 00 = success */ -/* 01-0f = non-zero HRSLT */ -uint32_t USBHost::ctrlReq(uint32_t addr, uint32_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, - uint16_t wInd, uint16_t total, uint32_t nbytes, uint8_t* dataptr, USBReadParser *p) { - - uint32_t direction = 0; // Request direction, IN or OUT - uint32_t rcode; - SETUP_PKT setup_pkt; - - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - TRACE_USBHOST(printf(" => ctrlReq\r\n");) - - rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - if(rcode) - return rcode; - - // Allocate Pipe0 with default 64 bytes size if not already initialized - rcode = UHD_Pipe0_Alloc(0, 64); - if (rcode) - { - TRACE_USBHOST(printf("/!\\ USBHost::ctrlReq : EP0 allocation error: %lu\r\n", rcode);) - //USBTRACE2("\n\rUSBHost::ctrlReq : EP0 allocation error: ", rcode"); - return rcode; - } - - // Determine request direction - direction = ((bmReqType & 0x80 ) > 0); - - /* fill in setup packet */ - setup_pkt.ReqType_u.bmRequestType = bmReqType; - setup_pkt.bRequest = bRequest; - setup_pkt.wVal_u.wValueLo = wValLo; - setup_pkt.wVal_u.wValueHi = wValHi; - setup_pkt.wIndex = wInd; - setup_pkt.wLength = total; - - UHD_Pipe_Write(pep->epAddr, sizeof(setup_pkt), (uint8_t *)&setup_pkt); //transfer to setup packet FIFO - - rcode = dispatchPkt(tokSETUP, ep, nak_limit); // Dispatch packet - - if (rcode) //return HRSLT if not zero - return ( rcode); - - if (dataptr != NULL) //data stage, if present - { - if (direction) // IN transfer - { - uint32_t left = total; - TRACE_USBHOST(printf(" => ctrlData IN\r\n");) - - pep->bmRcvToggle = 1; //bmRCVTOG1; - - // Bytes read into buffer - uint32_t read = nbytes; - - rcode = InTransfer(pep, nak_limit, (uint8_t*)&read, dataptr); - - if((rcode&USB_ERROR_DATATOGGLE) == USB_ERROR_DATATOGGLE) { - // yes, we flip it wrong here so that next time it is actually correct! - //pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //continue; - } - - if(rcode) { - //USBTRACE2("\n\rUSBHost::ctrlReq : in transfer: ", rcode"); - return rcode; - } - // Invoke callback function if inTransfer completed successfully and callback function pointer is specified - if(!rcode && p) - ((USBReadParser*)p)->Parse(read, dataptr, total - left); - } - else // OUT transfer - { - pep->bmSndToggle = 1; //bmSNDTOG1; - rcode = OutTransfer(pep, nak_limit, nbytes, dataptr); - } - if(rcode) //return error - return (rcode); - } - - // Status stage - UHD_Pipe_CountZero(pep->epAddr); - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - return dispatchPkt((direction) ? tokOUTHS : tokINHS, pep->epAddr, nak_limit); //GET if direction -} - -/* IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */ -/* Keep sending INs and writes data to memory area pointed by 'data' */ - -/* rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error, - fe USB xfer timeout */ -uint32_t USBHost::inTransfer(uint32_t addr, uint32_t ep, uint8_t *nbytesptr, uint8_t* data) { - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - uint32_t rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - - if(rcode) { - USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81); - USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81); - USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81); - return rcode; - } - return InTransfer(pep, nak_limit, nbytesptr, data); -} - -uint32_t USBHost::InTransfer(EpInfo *pep, uint32_t nak_limit, uint8_t *nbytesptr, uint8_t* data) { - uint32_t rcode = 0; - uint32_t pktsize = 0; - - uint32_t nbytes = *nbytesptr; - uint32_t maxpktsize = pep->maxPktSize; - - *nbytesptr = 0; - //set toggle value - if(pep->bmRcvToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - - usb_pipe_table[pep->epAddr].HostDescBank[0].ADDR.reg = (uint32_t)data; - - // use a 'break' to exit this loop - while (1) { - /* get pipe config from setting register */ - usb_pipe_table[pep->epAddr].HostDescBank[0].ADDR.reg += pktsize; - - rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); //IN packet to EP-'endpoint'. Function takes care of NAKS. - if(rcode == USB_ERROR_DATATOGGLE) { - // yes, we flip it wrong here so that next time it is actually correct! - //pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1; - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //set toggle value - if(pep->bmRcvToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - continue; - } - if(rcode) { - //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode); - return(rcode);// break; //should be 0, indicating ACK. Else return error code. - } - /* check for RCVDAVIRQ and generate error if not present */ - /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */ - - pktsize = uhd_byte_count(pep->epAddr); // Number of received bytes - - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_BK0RDY; - - //printf("Got %i bytes \r\n", pktsize); - // This would be OK, but... - //assert(pktsize <= nbytes); - if(pktsize > nbytes) { - // This can happen. Use of assert on Arduino locks up the Arduino. - // So I will trim the value, and hope for the best. - //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize); - pktsize = nbytes; - } - - int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr); - - if(mem_left < 0) - mem_left = 0; - - //data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data); - - //regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer - *nbytesptr += pktsize;// add this packet's byte count to total transfer length - - /* The transfer is complete under two conditions: */ - /* 1. The device sent a short packet (L.T. maxPacketSize) */ - /* 2. 'nbytes' have been transferred. */ - if((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) // have we transferred 'nbytes' bytes? - { - // Save toggle value - pep->bmRcvToggle = USB_HOST_DTGL(pep->epAddr); - //printf("\r\n"); - rcode = 0; - break; - } // if - } //while( 1 ) - return ( rcode); -} - -/* OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */ -/* Handles NAK bug per Maxim Application Note 4000 for single buffer transfer */ - -/* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */ -uint32_t USBHost::outTransfer(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* data) { - EpInfo *pep = NULL; - uint32_t nak_limit = 0; - - uint32_t rcode = SetPipeAddress(addr, ep, &pep, nak_limit); - - if(rcode) - return rcode; - - return OutTransfer(pep, nak_limit, nbytes, data); -} - -uint32_t USBHost::OutTransfer(EpInfo *pep, uint32_t nak_limit, uint32_t nbytes, uint8_t *data) { - uint32_t rcode = 0, retry_count; - uint8_t *data_p = data; //local copy of the data pointer - uint32_t bytes_tosend, nak_count; - uint32_t bytes_left = nbytes; - uint8_t buf[64]; - uint8_t i; - - uint32_t maxpktsize = pep->maxPktSize; - - if(maxpktsize < 1 || maxpktsize > 64) - return USB_ERROR_INVALID_MAX_PKT_SIZE; - - for( i=0; ibmSndToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - - while(bytes_left) { - retry_count = 0; - nak_count = 0; - bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left; - UHD_Pipe_Write(pep->epAddr, bytes_tosend, buf); //filling output FIFO - - //set number of bytes - //dispatch packet - //wait for the completion IRQ - //clear IRQ - - rcode = dispatchPkt(tokOUT, pep->epAddr, nak_limit); - if (rcode) - { - switch(rcode) { - case USB_ERRORFLOW: - nak_count++; - if(nak_limit && (nak_count == nak_limit)) - goto breakout; - return ( rcode); - break; - case USB_ERRORTIMEOUT: - retry_count++; - if(retry_count == USB_RETRY_LIMIT) - goto breakout; - return ( rcode); - break; - case USB_ERROR_DATATOGGLE: - // yes, we flip it wrong here so that next time it is actually correct! - pep->bmSndToggle = USB_HOST_DTGL(pep->epAddr); - //set toggle value - if(pep->bmSndToggle) - USB->HOST.HostPipe[pep->epAddr].PSTATUSSET.reg = USB_HOST_PSTATUSSET_DTGL; - else - USB->HOST.HostPipe[pep->epAddr].PSTATUSCLR.reg = USB_HOST_PSTATUSCLR_DTGL; - break; - default: - goto breakout; - }//switch( rcode - } - - bytes_left -= bytes_tosend; - data_p += bytes_tosend; - }//while( bytes_left... -breakout: - - pep->bmSndToggle = USB_HOST_DTGL(pep->epAddr); - return ( rcode); //should be 0 in all cases -} - -/* dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty */ -/* If NAK, tries to re-send up to nak_limit times */ -/* If nak_limit == 0, do not count NAKs, exit after timeout */ -/* If bus timeout, re-sends up to USB_RETRY_LIMIT times */ - -/* return codes 0x00-0x0f are HRSLT( 0x00 being success ), 0xff means timeout */ -uint32_t USBHost::dispatchPkt(uint32_t token, uint32_t epAddr, uint32_t nak_limit) { - uint32_t timeout = millis() + USB_XFER_TIMEOUT; - uint32_t nak_count = 0, retry_count=0; - uint32_t rcode = USB_ERROR_TRANSFER_TIMEOUT; - - TRACE_USBHOST(printf(" => dispatchPkt token=%lu pipe=%lu nak_limit=%lu\r\n", token, epAddr, nak_limit);) - - UHD_Pipe_Send(epAddr, token); //launch the transfer - - // Check timeout but don't hold timeout if VBUS is lost - while ((timeout > millis()) && (UHD_GetVBUSState() == UHD_STATE_CONNECTED)) - { - // Wait for transfer completion - if (UHD_Pipe_Is_Transfer_Complete(epAddr, token)) - { - return 0; - } - - //case hrNAK: - if( (usb_pipe_table[epAddr].HostDescBank[0].STATUS_BK.reg & USB_ERRORFLOW ) ) { - nak_count++; - if(nak_limit && (nak_count == nak_limit)) { - rcode = USB_ERRORFLOW; - return (rcode); - } - } - - //case hrTIMEOUT: - if(usb_pipe_table[epAddr].HostDescBank[0].STATUS_PIPE.reg & USB_ERRORTIMEOUT) { - retry_count++; - if(retry_count == USB_RETRY_LIMIT) { - rcode = USB_ERRORTIMEOUT; - return (rcode); - } - } - - if( (usb_pipe_table[epAddr].HostDescBank[0].STATUS_PIPE.reg & USB_ERROR_DATATOGGLE ) ) { - rcode = USB_ERROR_DATATOGGLE; - return (rcode); - } - } - - return rcode; -} - -/* USB main task. Performs enumeration/cleanup */ -void USBHost::Task(void) //USB state machine -{ - uint32_t rcode = 0; - volatile uint32_t tmpdata = 0; - static uint32_t delay = 0; - //USB_DEVICE_DESCRIPTOR buf; - uint32_t lowspeed = 0; - - // Update USB task state on Vbus change - tmpdata = UHD_GetVBUSState(); - - /* modify USB task state if Vbus changed */ - switch (tmpdata) - { - case UHD_STATE_ERROR: //illegal state - usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL; - lowspeed = 0; - break; - - case UHD_STATE_DISCONNECTED: // Disconnected state - if ((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED) - usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; - lowspeed = 0; - break; - - case UHD_STATE_CONNECTED: // Attached state - if ((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) { - delay = millis() + USB_SETTLE_DELAY; - usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE; - } - break; - }// switch( tmpdata - - // Poll connected devices (if required) - for (uint32_t i = 0; i < USB_NUMDEVICES; ++i) - if (devConfig[i]) - rcode = devConfig[i]->Poll(); - - // Perform USB enumeration stage and clean up - switch (usb_task_state) { - case USB_DETACHED_SUBSTATE_INITIALIZE: - TRACE_USBHOST(printf(" + USB_DETACHED_SUBSTATE_INITIALIZE\r\n");) - - // Init USB stack and driver - UHD_Init(); - init(); - - // Free all USB resources - for (uint32_t i = 0; i < USB_NUMDEVICES; ++i) - if (devConfig[i]) - rcode = devConfig[i]->Release(); - - usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE; - break; - case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: //just sit here - // Nothing to do - break; - case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here - // Nothing to do - break; - case USB_ATTACHED_SUBSTATE_SETTLE: // Settle time for just attached device - if((long)(millis() - delay) >= 0L) - usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE; - break; - case USB_ATTACHED_SUBSTATE_RESET_DEVICE: - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_RESET_DEVICE\r\n");) - UHD_BusReset(); //issue bus reset - usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE; - break; - case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE: - if (Is_uhd_reset_sent()) - { - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE\r\n");) - - // Clear Bus Reset flag - uhd_ack_reset_sent(); - - // Enable Start Of Frame generation - uhd_enable_sof(); - - usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF; - - // Wait 20ms after Bus Reset (USB spec) - delay = millis() + 20; - } - break; - case USB_ATTACHED_SUBSTATE_WAIT_SOF: - // Wait for SOF received first - if (Is_uhd_sof()) - { - if (delay < millis()) - { - TRACE_USBHOST(printf(" + USB_ATTACHED_SUBSTATE_WAIT_SOF\r\n");) - - // 20ms waiting elapsed - usb_task_state = USB_STATE_CONFIGURING; - } - } - break; - case USB_STATE_CONFIGURING: - TRACE_USBHOST(printf(" + USB_STATE_CONFIGURING\r\n");) - rcode = Configuring(0, 0, lowspeed); - - if (rcode) { - TRACE_USBHOST(printf("/!\\ USBHost::Task : USB_STATE_CONFIGURING failed with code: %lu\r\n", rcode);) - if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) { - usb_error = rcode; - usb_task_state = USB_STATE_ERROR; - } - } - else { - usb_task_state = USB_STATE_RUNNING; - TRACE_USBHOST(printf(" + USB_STATE_RUNNING\r\n");) - } - break; - case USB_STATE_RUNNING: - break; - case USB_STATE_ERROR: - break; - } // switch( usb_task_state ) -} - -uint32_t USBHost::DefaultAddressing(uint32_t parent, uint32_t port, uint32_t lowspeed) { - //uint8_t buf[12]; - uint32_t rcode = 0; - UsbDeviceDefinition *p0 = NULL, *p = NULL; - - // Get pointer to pseudo device with address 0 assigned - p0 = addrPool.GetUsbDevicePtr(0); - - if(!p0) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p0->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - p0->lowspeed = (lowspeed) ? 1 : 0; - - // Allocate new address according to device class - uint32_t bAddress = addrPool.AllocAddress(parent, 0, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - // Assign new address to the device - rcode = setAddr(0, 0, bAddress); - - if(rcode) { - TRACE_USBHOST(printf("/!\\ USBHost::DefaultAddressing : Set address failed with code: %lu\r\n", rcode);) - addrPool.FreeAddress(bAddress); - bAddress = 0; - return rcode; - } - return 0; -} - -uint32_t USBHost::AttemptConfig(uint32_t driver, uint32_t parent, uint32_t port, uint32_t lowspeed) { - //printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port); - uint8_t retries = 0; - -again: - uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed); - if(rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) { - if(parent == 0) { - // Send a bus reset on the root interface. - //regWr(rHCTL, bmBUSRST); //issue bus reset - UHD_BusReset(); - delay(102); // delay 102ms, compensate for clock inaccuracy. - } else { - // reset parent port - devConfig[parent]->ResetHubPort(port); - } - } else if(rcode != 0x00/*hrJERR*/ && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works - delay(100); - retries++; - goto again; - } else if(rcode) - return rcode; - - rcode = devConfig[driver]->Init(parent, port, lowspeed); - if(rcode != 0x00/*hrJERR*/ && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works - delay(100); - retries++; - goto again; - } - if(rcode) { - // Issue a bus reset, because the device may be in a limbo state - if(parent == 0) { - // Send a bus reset on the root interface. - //regWr(rHCTL, bmBUSRST); //issue bus reset - UHD_BusReset(); - delay(102); // delay 102ms, compensate for clock inaccuracy. - } else { - // reset parent port - devConfig[parent]->ResetHubPort(port); - } - } - return rcode; -} - -/* - * This is broken. We need to enumerate differently. - * It causes major problems with several devices if detected in an unexpected order. - * - * - * Oleg - I wouldn't do anything before the newly connected device is considered sane. - * i.e.(delays are not indicated for brevity): - * 1. reset - * 2. GetDevDescr(); - * 3a. If ACK, continue with allocating address, addressing, etc. - * 3b. Else reset again, count resets, stop at some number (5?). - * 4. When max.number of resets is reached, toggle power/fail - * If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD() - * it doesn't need to be reset again - * New steps proposal: - * 1: get address pool instance. exit on fail - * 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail. - * 3: bus reset, 100ms delay - * 4: set address - * 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail - * 6: while (configurations) { - * for(each configuration) { - * for (each driver) { - * 6a: Ask device if it likes configuration. Returns 0 on OK. - * If successful, the driver configured device. - * The driver now owns the endpoints, and takes over managing them. - * The following will need codes: - * Everything went well, instance consumed, exit with success. - * Instance already in use, ignore it, try next driver. - * Not a supported device, ignore it, try next driver. - * Not a supported configuration for this device, ignore it, try next driver. - * Could not configure device, fatal, exit with fail. - * } - * } - * } - * 7: for(each driver) { - * 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID - * 8: if we get here, no driver likes the device plugged in, so exit failure. - * - */ -uint32_t USBHost::Configuring(uint32_t parent, uint32_t port, uint32_t lowspeed) { - //uint32_t bAddress = 0; - //printf("Configuring: parent = %i, port = %i\r\n", parent, port); - uint32_t devConfigIndex; - uint32_t rcode = 0; - uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; - USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast(buf); - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - EpInfo epInfo; - - epInfo.epAddr = 0; - epInfo.maxPktSize = 8; - epInfo.epAttribs = 0; - epInfo.bmNakPower = USB_NAK_MAX_POWER; - - //delay(2000); - AddressPool &addrPool = GetAddressPool(); - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - if(!p) { - //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n"); - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to - // avoid toggle inconsistence - - p->epinfo = &epInfo; - - p->lowspeed = lowspeed; - // Get device descriptor - rcode = getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // The first GetDescriptor give us the endpoint 0 max packet size. - epInfo.maxPktSize = buf[7]; - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(rcode) { - //printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n"); - return rcode; - } - - // to-do? - // Allocate new address according to device class - //bAddress = addrPool.AllocAddress(parent, false, port); - - //if (!bAddress) - // return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - uint16_t vid = udd->idVendor; - uint16_t pid = udd->idProduct; - uint8_t klass = udd->bDeviceClass; - - // Attempt to configure if VID/PID or device class matches with a driver - for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if(!devConfig[devConfigIndex]) continue; // no driver - if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) { - rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); - if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED) - break; - } - } - - if(devConfigIndex < USB_NUMDEVICES) { - return rcode; - } - - - // blindly attempt to configure - for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) { - if(!devConfig[devConfigIndex]) continue; - if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed - if(devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass)) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above - rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed); - - //printf("ERROR ENUMERATING %2.2x\r\n", rcode); - if(!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) { - // in case of an error dev_index should be reset to 0 - // in order to start from the very beginning the - // next time the program gets here - //if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) - // devConfigIndex = 0; - return rcode; - } - } - // if we get here that means that the device class is not supported by any of registered classes - rcode = DefaultAddressing(parent, port, lowspeed); - - return rcode; -} - -uint32_t USBHost::ReleaseDevice(uint32_t addr) { - if(!addr) - return 0; - - for(uint32_t i = 0; i < USB_NUMDEVICES; i++) { - if(!devConfig[i]) continue; - if(devConfig[i]->GetAddress() == addr) - return devConfig[i]->Release(); - } - return 0; -} - -//get device descriptor - -uint32_t USBHost::getDevDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, 0)); -} -//get configuration descriptor - -uint32_t USBHost::getConfDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t conf, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, 0)); -} - -/* Requests Configuration Descriptor. Sends two Get Conf Descr requests. The first one gets the total length of all descriptors, then the second one requests this - total length. The length of the first request can be shorter ( 4 bytes ), however, there are devices which won't work unless this length is set to 9 */ -uint32_t USBHost::getConfDescr(uint32_t addr, uint32_t ep, uint32_t conf, USBReadParser *p) { - const uint32_t bufSize = 64; - uint8_t buf[bufSize]; - USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast(buf); - - uint32_t ret = getConfDescr(addr, ep, 9, conf, buf); - - if(ret) - return ret; - - uint32_t total = ucd->wTotalLength; - - //USBTRACE2("\r\ntotal conf.size:", total); - - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p)); -} - -//get string descriptor - -uint32_t USBHost::getStrDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t index, uint32_t langid, uint8_t* dataptr) { - return (ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nbytes, nbytes, dataptr, 0)); -} -//set address - -uint32_t USBHost::setAddr(uint32_t oldaddr, uint32_t ep, uint32_t newaddr) { - uint32_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL); - //delay(2); //per USB 2.0 sect.9.2.6.3 - delay(300); // Older spec says you should wait at least 200ms - return rcode; - //return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); -} -//set configuration - -uint32_t USBHost::setConf(uint32_t addr, uint32_t ep, uint32_t conf_value) { - return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL)); -} - -#endif //ARDUINO_SAMD_ZERO diff --git a/test/libraries/USBHost/src/Usb.h b/test/libraries/USBHost/src/Usb.h deleted file mode 100644 index e95ebc05..00000000 --- a/test/libraries/USBHost/src/Usb.h +++ /dev/null @@ -1,48 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -/* USB functions */ - -#ifndef USB_H_INCLUDED -#define USB_H_INCLUDED -#define _usb_h_ - -#include - -#define ARDUINO 101 - -//#include "Arduino.h" -#include "macros.h" -// None of these should ever be included by a driver, or a user's sketch. - -#include "variant.h" -#define USB_HOST_SERIAL SERIAL_PORT_MONITOR -#include "Print.h" -#include "printhex.h" -#include "message.h" -#include "hexdump.h" -#include "sink_parser.h" - -#include "address.h" - -#include "usb_ch9.h" -//#include "usbhost.h" -#include "UsbCore.h" -#include "parsetools.h" - -#include "confdescparser.h" - -#endif /* USB_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/UsbCore.h b/test/libraries/USBHost/src/UsbCore.h deleted file mode 100644 index fdb14c1c..00000000 --- a/test/libraries/USBHost/src/UsbCore.h +++ /dev/null @@ -1,291 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(USBCORE_H) -#error "Never include UsbCore.h directly; include Usb.h instead" -#else -#define USBCORE_H - -// Not used anymore? If anyone uses this, please let us know so that this may be -// moved to the proper place, settings.h. -//#define USB_METHODS_INLINE - -/* shield pins. First parameter - SS pin, second parameter - INT pin */ -#ifdef BOARD_BLACK_WIDDOW -typedef MAX3421e MAX3421E; // Black Widow -#elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)) -#if EXT_RAM -typedef MAX3421e MAX3421E; // Teensy++ 2.0 with XMEM2 -#else -typedef MAX3421e MAX3421E; // Teensy++ 1.0 and 2.0 -#endif -#elif defined(BOARD_MEGA_ADK) -typedef MAX3421e MAX3421E; // Arduino Mega ADK -#elif defined(ARDUINO_AVR_BALANDUINO) -typedef MAX3421e MAX3421E; // Balanduino -#else -//typedef MAX3421e MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.) or Teensy 2.0 and 3.0 -#endif - -/* Common setup data constant combinations */ -#define bmREQ_GET_DESCR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //get descriptor request type -#define bmREQ_SET USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //set request type for all but 'set feature' and 'set interface' -#define bmREQ_CL_GET_INTF USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE //get interface request type - -// D7 data transfer direction (0 - host-to-device, 1 - device-to-host) -// D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved) -// D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved) - -// USB Device Classes -#define USB_CLASS_USE_CLASS_INFO 0x00 // Use Class Info in the Interface Descriptors -#define USB_CLASS_AUDIO 0x01 // Audio -#define USB_CLASS_COM_AND_CDC_CTRL 0x02 // Communications and CDC Control -#define USB_CLASS_HID 0x03 // HID -#define USB_CLASS_PHYSICAL 0x05 // Physical -#define USB_CLASS_IMAGE 0x06 // Image -#define USB_CLASS_PRINTER 0x07 // Printer -#define USB_CLASS_MASS_STORAGE 0x08 // Mass Storage -#define USB_CLASS_HUB 0x09 // Hub -#define USB_CLASS_CDC_DATA 0x0a // CDC-Data -#define USB_CLASS_SMART_CARD 0x0b // Smart-Card -#define USB_CLASS_CONTENT_SECURITY 0x0d // Content Security -#define USB_CLASS_VIDEO 0x0e // Video -#define USB_CLASS_PERSONAL_HEALTH 0x0f // Personal Healthcare -#define USB_CLASS_DIAGNOSTIC_DEVICE 0xdc // Diagnostic Device -#define USB_CLASS_WIRELESS_CTRL 0xe0 // Wireless Controller -#define USB_CLASS_MISC 0xef // Miscellaneous -#define USB_CLASS_APP_SPECIFIC 0xfe // Application Specific -#define USB_CLASS_VENDOR_SPECIFIC 0xff // Vendor Specific - -// Additional Error Codes -#define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED 0xD1 -#define USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE 0xD2 -#define USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS 0xD3 -#define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL 0xD4 -#define USB_ERROR_HUB_ADDRESS_OVERFLOW 0xD5 -#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL 0xD6 -#define USB_ERROR_EPINFO_IS_NULL 0xD7 -#define USB_ERROR_INVALID_ARGUMENT 0xD8 -#define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE 0xD9 -#define USB_ERROR_INVALID_MAX_PKT_SIZE 0xDA -#define USB_ERROR_EP_NOT_FOUND_IN_TBL 0xDB -#define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET 0xE0 -#define USB_ERROR_FailGetDevDescr 0xE1 -#define USB_ERROR_FailSetDevTblEntry 0xE2 -#define USB_ERROR_FailGetConfDescr 0xE3 -#define USB_ERROR_TRANSFER_TIMEOUT 0xFF - -#define USB_XFER_TIMEOUT 10000 //30000 // (5000) USB transfer timeout in milliseconds, per section 9.2.6.1 of USB 2.0 spec -//#define USB_NAK_LIMIT 32000 //NAK limit for a transfer. 0 means NAKs are not counted -#define USB_RETRY_LIMIT 3 // 3 retry limit for a transfer -#define USB_SETTLE_DELAY 200 //settle delay in milliseconds - -#define USB_NUMDEVICES 16 //number of USB devices -//#define HUB_MAX_HUBS 7 // maximum number of hubs that can be attached to the host controller -#define HUB_PORT_RESET_DELAY 20 // hub port reset delay 10 ms recomended, can be up to 20 ms - -/* USB state machine states */ -#define USB_STATE_MASK 0xf0 - -#define USB_STATE_DETACHED 0x10 -#define USB_DETACHED_SUBSTATE_INITIALIZE 0x11 -#define USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE 0x12 -#define USB_DETACHED_SUBSTATE_ILLEGAL 0x13 -#define USB_ATTACHED_SUBSTATE_SETTLE 0x20 -#define USB_ATTACHED_SUBSTATE_RESET_DEVICE 0x30 -#define USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE 0x40 -#define USB_ATTACHED_SUBSTATE_WAIT_SOF 0x50 -#define USB_ATTACHED_SUBSTATE_WAIT_RESET 0x51 -#define USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE 0x60 -#define USB_STATE_ADDRESSING 0x70 -#define USB_STATE_CONFIGURING 0x80 -#define USB_STATE_RUNNING 0x90 -#define USB_STATE_ERROR 0xa0 - -class USBDeviceConfig { -public: - - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return 0; - } - - virtual uint32_t ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return 0; - } - - virtual uint32_t Release() { - return 0; - } - - virtual uint32_t Poll() { - return 0; - } - - virtual uint32_t GetAddress() { - return 0; - } - - virtual void ResetHubPort(uint32_t port) { - return; - } // Note used for hubs only! - - virtual uint32_t VIDPIDOK(uint32_t vid, uint32_t pid) { - return false; - } - - virtual uint32_t DEVCLASSOK(uint32_t klass) { - return false; - } -}; - -/* USB Setup Packet Structure */ -typedef struct { - - union { // offset description - uint8_t bmRequestType; // 0 Bit-map of request type - - struct { - uint8_t recipient : 5; // Recipient of the request - uint8_t type : 2; // Type of request - uint8_t direction : 1; // Direction of data X-fer - }; - } ReqType_u; - uint8_t bRequest; // 1 Request - - union { - uint16_t wValue; // 2 Depends on bRequest - - struct { - uint8_t wValueLo; - uint8_t wValueHi; - }; - } wVal_u; - uint16_t wIndex; // 4 Depends on bRequest - uint16_t wLength; // 6 Depends on bRequest -} SETUP_PKT, *PSETUP_PKT; - - - -// Base class for incoming data parser - -class USBReadParser { -public: - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) = 0; -}; - -class USBHost { - AddressPoolImpl addrPool; - USBDeviceConfig* devConfig[USB_NUMDEVICES]; - uint8_t bmHubPre; - -public: - USBHost(void); - - void SetHubPreMask() { - //bmHubPre |= bmHUBPRE; - }; - - void ResetHubPreMask() { - //bmHubPre &= (~bmHUBPRE); - }; - - AddressPool& GetAddressPool() { - return (AddressPool&)addrPool; - }; - - uint32_t RegisterDeviceClass(USBDeviceConfig *pdev) { - for(uint8_t i = 0; i < USB_NUMDEVICES; i++) { - if(!devConfig[i]) { - devConfig[i] = pdev; - return 0; - } - } - return USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS; - }; - - void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { - addrPool.ForEachUsbDevice(pfunc); - }; - uint32_t getUsbTaskState(void); - void setUsbTaskState(uint32_t state); - - EpInfo* getEpInfoEntry(uint32_t addr, uint32_t ep); - uint32_t setEpInfoEntry(uint32_t addr, uint32_t epcount, EpInfo* eprecord_ptr); - - /* Control requests */ - uint32_t getDevDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr); - uint32_t getConfDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t conf, uint8_t* dataptr); - - uint32_t getConfDescr(uint32_t addr, uint32_t ep, uint32_t conf, USBReadParser *p); - - uint32_t getStrDescr(uint32_t addr, uint32_t ep, uint32_t nbytes, uint32_t index, uint32_t langid, uint8_t* dataptr); - uint32_t setAddr(uint32_t oldaddr, uint32_t ep, uint32_t newaddr); - uint32_t setConf(uint32_t addr, uint32_t ep, uint32_t conf_value); - /**/ - uint32_t ctrlData(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* dataptr, uint32_t direction); - uint32_t ctrlStatus(uint32_t ep, uint32_t direction, uint32_t nak_limit); - uint32_t inTransfer(uint32_t addr, uint32_t ep, uint8_t *nbytesptr, uint8_t* data); - uint32_t outTransfer(uint32_t addr, uint32_t ep, uint32_t nbytes, uint8_t* data); - uint32_t dispatchPkt(uint32_t token, uint32_t ep, uint32_t nak_limit); - - void Task(void); - - uint32_t DefaultAddressing(uint32_t parent, uint32_t port, uint32_t lowspeed); - uint32_t Configuring(uint32_t parent, uint32_t port, uint32_t lowspeed); - uint32_t ReleaseDevice(uint32_t addr); - - uint32_t ctrlReq(uint32_t addr, uint32_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi, - uint16_t wInd, uint16_t total, uint32_t nbytes, uint8_t* dataptr, USBReadParser *p); - - uint32_t Init(); -private: - uint32_t SetPipeAddress(uint32_t addr, uint32_t ep, EpInfo **ppep, uint32_t &nak_limit); - uint32_t OutTransfer(EpInfo *pep, uint32_t nak_limit, uint32_t nbytes, uint8_t *data); - uint32_t InTransfer(EpInfo *pep, uint32_t nak_limit, uint8_t *nbytesptr, uint8_t *data); - uint32_t AttemptConfig(uint32_t driver, uint32_t parent, uint32_t port, uint32_t lowspeed); -}; - -#if 0 //defined(USB_METHODS_INLINE) -//get device descriptor - -inline uint8_t USBHost::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr)); -} -//get configuration descriptor - -inline uint8_t USBHost::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr)); -} -//get string descriptor - -inline uint8_t USBHost::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t* dataptr) { - return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr)); -} -//set address - -inline uint8_t USBHost::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) { - return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL)); -} -//set configuration - -inline uint8_t USBHost::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) { - return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL)); -} - -#endif // defined(USB_METHODS_INLINE) - -#endif /* USBCORE_H */ diff --git a/test/libraries/USBHost/src/address.h b/test/libraries/USBHost/src/address.h deleted file mode 100644 index a9610822..00000000 --- a/test/libraries/USBHost/src/address.h +++ /dev/null @@ -1,280 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(ADDRESS_H_INCLUDED) -#error "Never include address.h directly; include Usb.h instead" -#else -#define ADDRESS_H_INCLUDED - -#include -#include - -/* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */ -/* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */ -#define USB_NAK_MAX_POWER 15 //NAK binary order maximum value -#define USB_NAK_DEFAULT 14 //default 32K-1 NAKs before giving up -#define USB_NAK_NOWAIT 1 //Single NAK stops transfer -#define USB_NAK_NONAK 0 //Do not count NAKs, stop retrying after USB Timeout - -struct EpInfo { - uint32_t epAddr; // Endpoint address - uint32_t maxPktSize; // Maximum packet size - union { - uint8_t epAttribs; - - struct { - uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise - uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise - uint8_t bmNakPower : 6; // Binary order for NAK_LIMIT value - }; - }; -}; - -// 7 6 5 4 3 2 1 0 -// --------------------------------- -// | | H | P | P | P | A | A | A | -// --------------------------------- -// -// H - if 1 the address is a hub address -// P - parent hub address -// A - device address / port number in case of hub -// - -struct UsbDeviceAddress { - union { - struct { - uint32_t bmAddress : 3; // device address/port number - uint32_t bmParent : 3; // parent hub address - uint32_t bmHub : 1; // hub flag - uint32_t bmReserved : 25; // reserved, must be zerro - }; - uint32_t devAddress; - }; -}; - -#define bmUSB_DEV_ADDR_ADDRESS 0x07 -#define bmUSB_DEV_ADDR_PARENT 0x38 -#define bmUSB_DEV_ADDR_HUB 0x40 - -struct UsbDeviceDefinition { - EpInfo *epinfo; // endpoint info pointer - UsbDeviceAddress address; - uint32_t epcount; // number of endpoints - uint32_t lowspeed; // indicates if a device is the low speed one - // uint8_t devclass; // device class -}; - -class AddressPool { -public: - virtual UsbDeviceDefinition* GetUsbDevicePtr(uint32_t addr) = 0; - virtual uint32_t AllocAddress(uint32_t parent, uint32_t is_hub = 0, uint32_t port = 0) = 0; - virtual void FreeAddress(uint32_t addr) = 0; -}; - -typedef void (*UsbDeviceHandleFunc)(UsbDeviceDefinition *pdev); - -#define ADDR_ERROR_INVALID_INDEX 0xFF -#define ADDR_ERROR_INVALID_ADDRESS 0xFF - -template -class AddressPoolImpl : public AddressPool { - EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device - - uint32_t hubCounter; // hub counter is kept - // in order to avoid hub address duplication - - UsbDeviceDefinition thePool[MAX_DEVICES_ALLOWED]; - - // Initializes address pool entry - - void InitEntry(uint32_t index) { - thePool[index].address.devAddress = 0; - thePool[index].epcount = 1; - thePool[index].lowspeed = 0; - thePool[index].epinfo = &dev0ep; - }; - - // Returns thePool index for a given address - - uint32_t FindAddressIndex(uint32_t address = 0) { - for (uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) { - if(thePool[i].address.devAddress == address) - return i; - } - return 0; - }; - - // Returns thePool child index for a given parent - - uint32_t FindChildIndex(UsbDeviceAddress addr, uint32_t start = 1) { - for (uint32_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) { - if(thePool[i].address.bmParent == addr.bmAddress) - return i; - } - return 0; - }; - - // Frees address entry specified by index parameter - - void FreeAddressByIndex(uint32_t index) { - // Zero field is reserved and should not be affected - if(index == 0) - return; - - UsbDeviceAddress uda = thePool[index].address; - // If a hub was switched off all port addresses should be freed - if(uda.bmHub == 1) { - for (uint32_t i = 1; (i = FindChildIndex(uda, i));) - FreeAddressByIndex(i); - - // If the hub had the last allocated address, hubCounter should be decremented - if(hubCounter == uda.bmAddress) - hubCounter--; - } - InitEntry(index); - } - - // Initializes the whole address pool at once - - void InitAllAddresses() { - for (uint32_t i = 1; i < MAX_DEVICES_ALLOWED; i++) - InitEntry(i); - - hubCounter = 0; - }; - -public: - - AddressPoolImpl() : hubCounter(0) { - // Zero address is reserved - InitEntry(0); - - thePool[0].address.devAddress = 0; - thePool[0].epinfo = &dev0ep; - dev0ep.epAddr = 0; - dev0ep.maxPktSize = 8; - dev0ep.epAttribs = 0; //set DATA0/1 toggles to 0 - dev0ep.bmNakPower = USB_NAK_MAX_POWER; - - InitAllAddresses(); - }; - - // Returns a pointer to a specified address entry - - virtual UsbDeviceDefinition* GetUsbDevicePtr(uint32_t addr) { - if(!addr) - return thePool; - - uint32_t index = FindAddressIndex(addr); - - return (!index) ? NULL : thePool + index; - }; - - // Performs an operation specified by pfunc for each addressed device - - void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) { - if(!pfunc) - return; - - for (uint32_t i = 1; i < MAX_DEVICES_ALLOWED; i++) - if(thePool[i].address.devAddress) - pfunc(thePool + i); - }; - - // Allocates new address - - virtual uint32_t AllocAddress(uint32_t parent, uint32_t is_hub = 0, uint32_t port = 0) { - /* if (parent != 0 && port == 0) - USB_HOST_SERIAL.println("PRT:0"); */ - UsbDeviceAddress _parent; - _parent.devAddress = parent; - if(_parent.bmReserved || port > 7) - //if(parent > 127 || port > 7) - return 0; - - if(is_hub && hubCounter == 7) - return 0; - - // finds first empty address entry starting from one - uint32_t index = FindAddressIndex(0); - - if(!index) // if empty entry is not found - return 0; - - if(_parent.devAddress == 0) { - if(is_hub) { - thePool[index].address.devAddress = 0x41; - hubCounter++; - } else - thePool[index].address.devAddress = 1; - - return thePool[index].address.devAddress; - } - - UsbDeviceAddress addr; - addr.devAddress = 0; // Ensure all bits are zero - addr.bmParent = _parent.bmAddress; - if(is_hub) { - addr.bmHub = 1; - addr.bmAddress = ++hubCounter; - } else { - addr.bmHub = 0; - addr.bmAddress = port; - } - thePool[index].address = addr; - /* - USB_HOST_SERIAL.print("Addr:"); - USB_HOST_SERIAL.print(addr.bmHub, HEX); - USB_HOST_SERIAL.print("."); - USB_HOST_SERIAL.print(addr.bmParent, HEX); - USB_HOST_SERIAL.print("."); - USB_HOST_SERIAL.println(addr.bmAddress, HEX); - */ - return thePool[index].address.devAddress; - }; - - // Empties pool entry - - virtual void FreeAddress(uint32_t addr) { - // if the root hub is disconnected all the addresses should be initialized - if(addr == 0x41) { - InitAllAddresses(); - return; - } - uint32_t index = FindAddressIndex(addr); - FreeAddressByIndex(index); - }; - - // Returns number of hubs attached - // It can be rather helpfull to find out if there are hubs attached than getting the exact number of hubs. - //uint32_t GetNumHubs() - //{ - // return hubCounter; - //}; - //uint32_t GetNumDevices() - //{ - // uint32_t counter = 0; - - // for (uint32_t i=1; iRegisterDeviceClass(this); //set devConfig[] entry - } -} - -uint32_t ADK::ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed) { - return Init(parent, port, lowspeed); // Just call Init. Yes, really! -} - -/* Connection initialization of an Android phone */ -uint32_t ADK::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - uint32_t rcode; - uint32_t num_of_conf; // number of configurations - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - - // get memory address of USB device address pool - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("\r\nADK Init"); - - // check if address has already been assigned to an instance - if(bAddress) { - USBTRACE("\r\nAddress in use"); - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - } - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) { - USBTRACE("\r\nAddress not found"); - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - if(!p->epinfo) { - USBTRACE("epinfo is null\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(0, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(rcode) { - USBTRACE("\r\nGetDevDesc1 Error "); - goto FailGetDevDescr; - } - - // Reset - UHD_BusReset(); - while( Is_uhd_starting_reset() ) {} - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - if (!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - - // Extract Max Packet Size from device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device SET_ADDRESS - rcode = pUsb->setAddr(0, 0, bAddress); - if(rcode) { - USBTRACE("\r\nsetAddr Error "); - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - TRACE_USBHOST(printf("ADK::Init : setAddr failed with rcode %lu\r\n", rcode);) - return rcode; - }//if (rcode... - - USBTRACE2("\r\nAddr:", bAddress); - // Spec says you should wait at least 200ms. - //delay(300); - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(bAddress, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // Restore p->epinfo - p->epinfo = oldep_ptr; - if (rcode) - { - USBTRACE("\r\nGetDevDesc2 Error "); - goto FailGetDevDescr; - } - - TRACE_USBHOST(printf("ADK::Init : device address is now %lu\r\n", bAddress);) - - p->lowspeed = false; - - //get pointer to assigned address record - p = addrPool.GetUsbDevicePtr(bAddress); - if(!p) { - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - } - - p->lowspeed = lowspeed; - - // Assign epInfo to epinfo pointer - only EP0 is known - rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - if(rcode) { - goto FailSetDevTblEntry; - } - - //check if ADK device is already in accessory mode; if yes, configure and exit - if(udd->idVendor == ADK_VID && - (udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) { - USBTRACE("\r\nAcc.mode device detected"); - /* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */ - num_of_conf = udd->bNumConfigurations; - - USBTRACE2("\r\nNC:",num_of_conf); - for (uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser<0, 0, 0, 0> confDescrParser(this); - - delay(1); - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - -#if defined(XOOM) - //added by Jaylen Scott Vanorden - if(rcode) { - TRACE_USBHOST(printf("ADK::Init : Got 1st bad code for config: %lu\r\n", rcode);) - - // Try once more - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - } -#endif - if(rcode) { - goto FailGetConfDescr; - } - if(bNumEP > 2) { - break; - } - } // for (uint32_t i=0; isetEpInfoEntry(bAddress, 3, epInfo); - if(rcode) { - goto FailSetDevTblEntry; - } - } - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - if(rcode) { - goto FailSetConfDescr; - } - /* print endpoint structure */ - - USBTRACE("\r\nEndpoint Structure:"); - USBTRACE("\r\nEP0:"); - USBTRACE2("\r\nAddr: ", epInfo[0].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[0].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[0].epAttribs); - USBTRACE("\r\nEpout:"); - USBTRACE2("\r\nAddr: ", epInfo[epDataOutIndex].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataOutIndex].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[epDataOutIndex].epAttribs); - USBTRACE("\r\nEpin:"); - USBTRACE2("\r\nAddr: ", epInfo[epDataInIndex].epAddr); - USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataInIndex].maxPktSize); - USBTRACE2("\r\nAttr: ", epInfo[epDataInIndex].epAttribs); - - - USBTRACE("\r\nConfiguration successful"); - ready = true; - return 0; //successful configuration - }//if( buf->idVendor == ADK_VID... - - //probe device - get accessory protocol revision - { - uint32_t adkproto = 0; - delay(1); - //rcode = getProto((uint8_t*) & adkproto); // ADK_GETPROTO 0x33 - rcode = getProto((uint8_t*)buf); - -#if defined(XOOM) - //added by Jaylen Scott Vanorden - if(rcode) { - USBTRACE2("\r\nGot 1st bad code for proto: ", rcode); - // Try once more - rcode = getProto((uint8_t*) & adkproto); - } -#endif - if(rcode) { - goto FailGetProto; //init fails - } - adkproto = buf[0] | (buf[1]<<8); - USBTRACE2("\r\nADK protocol rev. ", adkproto); - } - - delay(100); - - //sending ID strings - // ADK_SENDSTR 0x34 - if( sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_MANUFACTURER"); } - delay(10); - if( sendStr(ACCESSORY_STRING_MODEL, model) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_MODEL"); } - delay(10); - if( sendStr(ACCESSORY_STRING_DESCRIPTION, description) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_DESCRIPTION"); } - delay(10); - if( sendStr(ACCESSORY_STRING_VERSION, version) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_VERSION"); } - delay(10); - if( sendStr(ACCESSORY_STRING_URI, uri) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_URI"); } - delay(10); - if( sendStr(ACCESSORY_STRING_SERIAL, serial) ) { - USBTRACE("\r\nPb ACCESSORY_STRING_SERIAL"); } - - delay(100); - - USBTRACE("\r\nSwitch to accessory mode"); - //switch to accessory mode - //the Android phone will reset - rcode = switchAcc(); - if(rcode) { - goto FailSwAcc; //init fails - } - rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET; - delay(100); // Give Android a chance to do its reset. This is a guess, and possibly could be lower. - goto SwAttempt; //switch to accessory mode attempted - - /* diagnostic messages */ -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(rcode); - goto Fail; -#endif - -FailSetDevTblEntry: -#ifdef DEBUG_USB_HOST - NotifyFailSetDevTblEntry(rcode); - goto Fail; -#endif - -FailGetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetConfDescr(rcode); - goto Fail; -#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(rcode); - goto Fail; -#endif - -FailGetProto: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\ngetProto:"); - goto Fail; -#endif - -FailSwAcc: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\nswAcc:"); - goto Fail; -#endif - - //FailOnInit: - // USBTRACE("OnInit:"); - // goto Fail; - // -SwAttempt: -#ifdef DEBUG_USB_HOST - USBTRACE("\r\nAccessory mode switch attempt"); -Fail: -#endif - USBTRACE2("\r\nADK Init Failed, error code: ", rcode); - //NotifyFail(rcode); - Release(); - return rcode; -} - -/* Extracts bulk-IN and bulk-OUT endpoint information from config descriptor */ -void ADK::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - //ErrorMessage(PSTR("Conf.Val"), conf); - //ErrorMessage(PSTR("Iface Num"), iface); - //ErrorMessage(PSTR("Alt.Set"), alt); - - //added by Yuuichi Akagawa - if(bNumEP == 3) { - return; - } - - bConfNum = conf; - - if((pep->bmAttributes & 0x02) == 2) { - uint32_t index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex; - // Fill in the endpoint info structure - epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize; - - bNumEP++; - - //PrintEndpointDescriptor(pep); - } -} - -/* Performs a cleanup after failed Init() attempt */ -uint32_t ADK::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bNumEP = 1; //must have to be reset to 1 - - bAddress = 0; - ready = false; - return 0; -} - -uint32_t ADK::RcvData(uint8_t *bytes_rcvd, uint8_t *dataptr) { - USBTRACE2("\r\nAddr: ", bAddress ); - USBTRACE2("\r\nEP: ",epInfo[epDataInIndex].epAddr); - return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr); -} - -uint32_t ADK::SndData(uint32_t nbytes, uint8_t *dataptr) { - return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr); -} - -void ADK::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) { - Notify(PSTR("Endpoint descriptor:"), 0x80); - Notify(PSTR("\r\nLength:\t\t"), 0x80); - PrintHex (ep_ptr->bLength, 0x80); - Notify(PSTR("\r\nType:\t\t"), 0x80); - PrintHex (ep_ptr->bDescriptorType, 0x80); - Notify(PSTR("\r\nAddress:\t"), 0x80); - PrintHex (ep_ptr->bEndpointAddress, 0x80); - Notify(PSTR("\r\nAttributes:\t"), 0x80); - PrintHex (ep_ptr->bmAttributes, 0x80); - Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); - PrintHex (ep_ptr->wMaxPacketSize, 0x80); - Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); - PrintHex (ep_ptr->bInterval, 0x80); - Notify(PSTR("\r\n"), 0x80); -} diff --git a/test/libraries/USBHost/src/adk.h b/test/libraries/USBHost/src/adk.h deleted file mode 100644 index ffd22cf3..00000000 --- a/test/libraries/USBHost/src/adk.h +++ /dev/null @@ -1,148 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -/* Google ADK interface support header */ - -#ifndef ADK_H_INCLUDED -#define ADK_H_INCLUDED - -#include -#include "Usb.h" -#include "hid.h" -#include "Arduino.h" - -// #define ADK_VID 0x18D1 -// #define ADK_PID 0x2D00 -// #define ADB_PID 0x2D01 - -// JCB -#define ADK_VID 0x04E8 -#define ADK_PID 0x685C -#define ADB_PID 0x685D - -#define XOOM //enables repeating getProto() and getConf() attempts - //necessary for slow devices such as Motorola XOOM - //defined by default, can be commented out to save memory - -/* requests */ - -#define ADK_GETPROTO 51 //check USB accessory protocol version 0x33 -#define ADK_SENDSTR 52 //send identifying string 0x34 -#define ADK_ACCSTART 53 //start device in accessory mode 0x35 - -#define bmREQ_ADK_GET USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_ADK_SEND USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE - -#define ACCESSORY_STRING_MANUFACTURER 0 -#define ACCESSORY_STRING_MODEL 1 -#define ACCESSORY_STRING_DESCRIPTION 2 -#define ACCESSORY_STRING_VERSION 3 -#define ACCESSORY_STRING_URI 4 -#define ACCESSORY_STRING_SERIAL 5 - -#define ADK_MAX_ENDPOINTS 3 //endpoint 0, bulk_IN, bulk_OUT - -class ADK; - -class ADK : public USBDeviceConfig, public UsbConfigXtracter { -private: - /* ID strings */ - const char* manufacturer; - const char* model; - const char* description; - const char* version; - const char* uri; - const char* serial; - - /* ADK proprietary requests */ - uint32_t getProto(uint8_t* adkproto); - uint32_t sendStr(uint32_t index, const char* str); - uint32_t switchAcc(void); - -protected: - static const uint32_t epDataInIndex; // DataIn endpoint index - static const uint32_t epDataOutIndex; // DataOUT endpoint index - - /* Mandatory members */ - USBHost *pUsb; - uint32_t bAddress; // Device USB address - uint32_t bConfNum; // configuration number - - uint32_t bNumEP; // total number of EP in the configuration - uint32_t ready; - - /* Endpoint data structure */ - EpInfo epInfo[ADK_MAX_ENDPOINTS]; - - void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr); - -public: - ADK(USBHost *pUsb, const char* manufacturer, - const char* model, - const char* description, - const char* version, - const char* uri, - const char* serial); - - // Methods for receiving and sending data - uint32_t RcvData(uint8_t *nbytesptr, uint8_t *dataptr); - uint32_t SndData(uint32_t nbytes, uint8_t *dataptr); - - - // USBDeviceConfig implementation - virtual uint32_t ConfigureDevice(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - - virtual uint32_t Poll() { - return 0; - }; - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t isReady() { - return ready; - }; - - virtual uint32_t VIDPIDOK(uint32_t vid, uint32_t pid) { - return (vid == ADK_VID && (pid == ADK_PID || pid == ADB_PID)); - }; - - //UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; //class ADK : public USBDeviceConfig ... - -/* get ADK protocol version */ - -/* returns 2 bytes in *adkproto */ -inline uint32_t ADK::getProto(uint8_t* adkproto) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL)); -} - -/* send ADK string */ -inline uint32_t ADK::sendStr(uint32_t index, const char* str) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*)str, NULL)); -} - -/* switch to accessory mode */ -inline uint32_t ADK::switchAcc(void) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL)); -} - -#endif /* ADK_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/confdescparser.h b/test/libraries/USBHost/src/confdescparser.h deleted file mode 100644 index 6ee6a1ee..00000000 --- a/test/libraries/USBHost/src/confdescparser.h +++ /dev/null @@ -1,223 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(__CONFDESCPARSER_H__) -#error "Never include confdescparser.h directly; include Usb.h instead" -#else - -#define __CONFDESCPARSER_H__ - -#include - -//#define TRACE_USBHOST(x) x -#define TRACE_USBHOST(x) - -class UsbConfigXtracter { -public: - //virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0; - //virtual void InterfaceXtract(uint32_t conf, const USB_INTERFACE_DESCRIPTOR *iface) = 0; - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep) = 0; -}; - -#define CP_MASK_COMPARE_CLASS 1 -#define CP_MASK_COMPARE_SUBCLASS 2 -#define CP_MASK_COMPARE_PROTOCOL 4 -#define CP_MASK_COMPARE_ALL 7 - -// Configuration Descriptor Parser Class Template - -template -class ConfigDescParser : public USBReadParser { - UsbConfigXtracter *theXtractor; - MultiValueBuffer theBuffer; - MultiByteValueParser valParser; - ByteSkipper theSkipper; - uint8_t varBuffer[16 /*sizeof(USB_CONFIGURATION_DESCRIPTOR)*/]; - - uint32_t stateParseDescr; // ParseDescriptor state - - uint32_t dscrLen; // Descriptor length - uint32_t dscrType; // Descriptor type - - bool isGoodInterface; // Apropriate interface flag - uint32_t confValue; // Configuration value - uint32_t protoValue; // Protocol value - uint32_t ifaceNumber; // Interface number - uint32_t ifaceAltSet; // Interface alternate settings - - bool UseOr; - bool ParseDescriptor(uint8_t **pp, uint32_t *pcntdn); - void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); - -public: - - void SetOR(void) { - UseOr = true; - } - ConfigDescParser(UsbConfigXtracter *xtractor); - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset); -}; - -template -ConfigDescParser::ConfigDescParser(UsbConfigXtracter *xtractor) : - theXtractor(xtractor), - stateParseDescr(0), - dscrLen(0), - dscrType(0), -UseOr(false) { - theBuffer.pValue = varBuffer; - valParser.Initialize(&theBuffer); - theSkipper.Initialize(&theBuffer); -}; - -template -void ConfigDescParser::Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) { - uint32_t cntdn = len; - uint8_t *p = (uint8_t*)pbuf; - - while (cntdn) - if(!ParseDescriptor(&p, &cntdn)) - return; -} - -/* Parser for the configuration descriptor. Takes values for class, subclass, protocol fields in interface descriptor and - compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */ -template -bool ConfigDescParser::ParseDescriptor(uint8_t **pp, uint32_t *pcntdn) { - USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast(varBuffer); - USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast(varBuffer); - switch(stateParseDescr) { - case 0: - theBuffer.valueSize = 2; - valParser.Initialize(&theBuffer); - stateParseDescr = 1; - case 1: - if(!valParser.Parse(pp, pcntdn)) - return false; - dscrLen = *((uint8_t*)theBuffer.pValue); - dscrType = *((uint8_t*)theBuffer.pValue + 1); - stateParseDescr = 2; - case 2: - // This is a sort of hack. Assuming that two bytes are all ready in the buffer - // the pointer is positioned two bytes ahead in order for the rest of descriptor - // to be read right after the size and the type fields. - // This should be used carefully. varBuffer should be used directly to handle data - // in the buffer. - theBuffer.pValue = varBuffer + 2; - stateParseDescr = 3; - case 3: - switch(dscrType) { - case USB_DESCRIPTOR_INTERFACE: - isGoodInterface = false; - case USB_DESCRIPTOR_CONFIGURATION: - theBuffer.valueSize = sizeof (USB_CONFIGURATION_DESCRIPTOR) - 2; - break; - case USB_DESCRIPTOR_ENDPOINT: - theBuffer.valueSize = sizeof (USB_ENDPOINT_DESCRIPTOR) - 2; - break; - case HID_DESCRIPTOR_HID: - theBuffer.valueSize = dscrLen - 2; - break; - } - valParser.Initialize(&theBuffer); - stateParseDescr = 4; - case 4: - switch(dscrType) { - case USB_DESCRIPTOR_CONFIGURATION: - if(!valParser.Parse(pp, pcntdn)) - return false; - confValue = ucd->bConfigurationValue; - break; - case USB_DESCRIPTOR_INTERFACE: - if(!valParser.Parse(pp, pcntdn)) - return false; - if((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID) - break; - if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID) - break; - if(UseOr) { - if((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol))) - break; - } else { - if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID) - break; - } - isGoodInterface = true; - ifaceNumber = uid->bInterfaceNumber; - ifaceAltSet = uid->bAlternateSetting; - protoValue = uid->bInterfaceProtocol; - break; - case USB_DESCRIPTOR_ENDPOINT: - if(!valParser.Parse(pp, pcntdn)) - return false; - if(isGoodInterface) - if(theXtractor) - theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*)varBuffer); - break; - //case HID_DESCRIPTOR_HID: - // if (!valParser.Parse(pp, pcntdn)) - // return false; - // PrintHidDescriptor((const USB_HID_DESCRIPTOR*)varBuffer); - // break; - default: - if(!theSkipper.Skip(pp, pcntdn, dscrLen - 2)) - return false; - } - theBuffer.pValue = varBuffer; - stateParseDescr = 0; - } - return true; -} - -template -void ConfigDescParser::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) { - Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80); - Notify(PSTR("bDescLength:\t\t"), 0x80); - PrintHex (pDesc->bLength, 0x80); - - Notify(PSTR("\r\nbDescriptorType:\t"), 0x80); - PrintHex (pDesc->bDescriptorType, 0x80); - - Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80); - PrintHex (pDesc->bcdHID, 0x80); - - Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80); - PrintHex (pDesc->bCountryCode, 0x80); - - Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80); - PrintHex (pDesc->bNumDescriptors, 0x80); - - //Notify(PSTR("\r\nbDescrType:\t\t")); - //PrintHex(pDesc->bDescrType); - // - //Notify(PSTR("\r\nwDescriptorLength:\t")); - //PrintHex(pDesc->wDescriptorLength); - - for (uint32_t i = 0; i < pDesc->bNumDescriptors; i++) { - HID_CLASS_DESCRIPTOR_LEN_AND_TYPE *pLT = (HID_CLASS_DESCRIPTOR_LEN_AND_TYPE*)&(pDesc->bDescrType); - - Notify(PSTR("\r\nbDescrType:\t\t"), 0x80); - PrintHex (pLT[i].bDescrType, 0x80); - - Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80); - PrintHex (pLT[i].wDescriptorLength, 0x80); - } - Notify(PSTR("\r\n"), 0x80); -} - - -#endif // __CONFDESCPARSER_H__ diff --git a/test/libraries/USBHost/src/hexdump.h b/test/libraries/USBHost/src/hexdump.h deleted file mode 100644 index 3818d850..00000000 --- a/test/libraries/USBHost/src/hexdump.h +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__HEXDUMP_H__) -#error "Never include hexdump.h directly; include Usb.h instead" -#else -#define __HEXDUMP_H__ - -extern int UsbDEBUGlvl; - -template -class HexDumper : public BASE_CLASS { - uint8_t byteCount; - OFFSET_TYPE byteTotal; - -public: - - HexDumper() : byteCount(0), byteTotal(0) { - }; - - void Initialize() { - byteCount = 0; - byteTotal = 0; - }; - - virtual void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset); -}; - -template -void HexDumper::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { - if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug. - for(LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) { - if(!byteCount) { - PrintHex (byteTotal, 0x80); - E_Notify(PSTR(": "), 0x80); - } - PrintHex (pbuf[j], 0x80); - E_Notify(PSTR(" "), 0x80); - - if(byteCount == 15) { - E_Notify(PSTR("\r\n"), 0x80); - byteCount = 0xFF; - } - } - } -} - -#endif // __HEXDUMP_H__ diff --git a/test/libraries/USBHost/src/hid.cpp b/test/libraries/USBHost/src/hid.cpp deleted file mode 100644 index 70c785b3..00000000 --- a/test/libraries/USBHost/src/hid.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "hid.h" - -//get HID report descriptor - -/* WRONG! Endpoint is _ALWAYS_ ZERO for HID! We want the _INTERFACE_ value here! -uint32_t HID::GetReportDescr(uint32_t ep, USBReadParser *parser) { - const uint8_t constBufLen = 64; - uint8_t buf[constBufLen]; - - uint8_t rcode = pUsb->ctrlReq(bAddress, ep, bmREQ_HIDREPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00, - HID_DESCRIPTOR_REPORT, 0x0000, 128, constBufLen, buf, (USBReadParser*)parser); - - //return ((rcode != hrSTALL) ? rcode : 0); - return rcode; -} - */ -uint32_t HID::GetReportDescr(uint32_t wIndex, USBReadParser *parser) { - const uint8_t constBufLen = 64; - uint8_t buf[constBufLen]; - - uint8_t rcode = pUsb->ctrlReq(bAddress, 0x00, bmREQ_HIDREPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00, - HID_DESCRIPTOR_REPORT, wIndex, 128, constBufLen, buf, (USBReadParser*)parser); - - //return ((rcode != hrSTALL) ? rcode : 0); - return rcode; -} - -//uint32_t HID::getHidDescr( uint8_t ep, uint16_t nbytes, uint8_t* dataptr ) -//{ -// return( pUsb->ctrlReq( bAddress, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, HID_DESCRIPTOR_HID, 0x0000, nbytes, dataptr )); -//} - -uint32_t HID::SetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HIDOUT, HID_REQUEST_SET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL)); -} - -uint32_t HID::GetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HIDIN, HID_REQUEST_GET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL)); -} - -uint32_t HID::GetIdle(uint32_t iface, uint32_t reportID, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDIN, HID_REQUEST_GET_IDLE, reportID, 0, iface, 0x0001, 0x0001, dataptr, NULL)); -} - -uint32_t HID::SetIdle(uint32_t iface, uint32_t reportID, uint32_t duration) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDOUT, HID_REQUEST_SET_IDLE, reportID, duration, iface, 0x0000, 0x0000, NULL, NULL)); -} - -uint32_t HID::SetProtocol(uint32_t iface, uint32_t protocol) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDOUT, HID_REQUEST_SET_PROTOCOL, protocol, 0x00, iface, 0x0000, 0x0000, NULL, NULL)); -} - -uint32_t HID::GetProtocol(uint32_t iface, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HIDIN, HID_REQUEST_GET_PROTOCOL, 0x00, 0x00, iface, 0x0001, 0x0001, dataptr, NULL)); -} - -void HID::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) { - Notify(PSTR("Endpoint descriptor:"), 0x80); - Notify(PSTR("\r\nLength:\t\t"), 0x80); - D_PrintHex (ep_ptr->bLength, 0x80); - Notify(PSTR("\r\nType:\t\t"), 0x80); - D_PrintHex (ep_ptr->bDescriptorType, 0x80); - Notify(PSTR("\r\nAddress:\t"), 0x80); - D_PrintHex (ep_ptr->bEndpointAddress, 0x80); - Notify(PSTR("\r\nAttributes:\t"), 0x80); - D_PrintHex (ep_ptr->bmAttributes, 0x80); - Notify(PSTR("\r\nMaxPktSize:\t"), 0x80); - D_PrintHex (ep_ptr->wMaxPacketSize, 0x80); - Notify(PSTR("\r\nPoll Intrv:\t"), 0x80); - D_PrintHex (ep_ptr->bInterval, 0x80); -} - -void HID::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) { - Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80); - Notify(PSTR("bDescLength:\t\t"), 0x80); - D_PrintHex (pDesc->bLength, 0x80); - - Notify(PSTR("\r\nbDescriptorType:\t"), 0x80); - D_PrintHex (pDesc->bDescriptorType, 0x80); - - Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80); - D_PrintHex (pDesc->bcdHID, 0x80); - - Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80); - D_PrintHex (pDesc->bCountryCode, 0x80); - - Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80); - D_PrintHex (pDesc->bNumDescriptors, 0x80); - - Notify(PSTR("\r\nbDescrType:\t\t"), 0x80); - D_PrintHex (pDesc->bDescrType, 0x80); - - Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80); - D_PrintHex (pDesc->wDescriptorLength, 0x80); -} diff --git a/test/libraries/USBHost/src/hid.h b/test/libraries/USBHost/src/hid.h deleted file mode 100644 index ca697a56..00000000 --- a/test/libraries/USBHost/src/hid.h +++ /dev/null @@ -1,183 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#if !defined(__HID_H__) -#define __HID_H__ - -#include "Usb.h" -#include "hidusagestr.h" - -#define MAX_REPORT_PARSERS 2 -#define HID_MAX_HID_CLASS_DESCRIPTORS 5 - -#define DATA_SIZE_MASK 0x03 -#define TYPE_MASK 0x0C -#define TAG_MASK 0xF0 - -#define DATA_SIZE_0 0x00 -#define DATA_SIZE_1 0x01 -#define DATA_SIZE_2 0x02 -#define DATA_SIZE_4 0x03 - -#define TYPE_MAIN 0x00 -#define TYPE_GLOBAL 0x04 -#define TYPE_LOCAL 0x08 - -#define TAG_MAIN_INPUT 0x80 -#define TAG_MAIN_OUTPUT 0x90 -#define TAG_MAIN_COLLECTION 0xA0 -#define TAG_MAIN_FEATURE 0xB0 -#define TAG_MAIN_ENDCOLLECTION 0xC0 - -#define TAG_GLOBAL_USAGEPAGE 0x00 -#define TAG_GLOBAL_LOGICALMIN 0x10 -#define TAG_GLOBAL_LOGICALMAX 0x20 -#define TAG_GLOBAL_PHYSMIN 0x30 -#define TAG_GLOBAL_PHYSMAX 0x40 -#define TAG_GLOBAL_UNITEXP 0x50 -#define TAG_GLOBAL_UNIT 0x60 -#define TAG_GLOBAL_REPORTSIZE 0x70 -#define TAG_GLOBAL_REPORTID 0x80 -#define TAG_GLOBAL_REPORTCOUNT 0x90 -#define TAG_GLOBAL_PUSH 0xA0 -#define TAG_GLOBAL_POP 0xB0 - -#define TAG_LOCAL_USAGE 0x00 -#define TAG_LOCAL_USAGEMIN 0x10 -#define TAG_LOCAL_USAGEMAX 0x20 - -/* HID requests */ -#define bmREQ_HIDOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE -#define bmREQ_HIDREPORT USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE - -/* HID constants. Not part of chapter 9 */ -/* Class-Specific Requests */ -#define HID_REQUEST_GET_REPORT 0x01 -#define HID_REQUEST_GET_IDLE 0x02 -#define HID_REQUEST_GET_PROTOCOL 0x03 -#define HID_REQUEST_SET_REPORT 0x09 -#define HID_REQUEST_SET_IDLE 0x0A -#define HID_REQUEST_SET_PROTOCOL 0x0B - -/* Class Descriptor Types */ -#define HID_DESCRIPTOR_HID 0x21 -#define HID_DESCRIPTOR_REPORT 0x22 -#define HID_DESRIPTOR_PHY 0x23 - -/* Protocol Selection */ -#define HID_BOOT_PROTOCOL 0x00 -#define HID_RPT_PROTOCOL 0x01 - -/* HID Interface Class Code */ -#define HID_INTF 0x03 - -/* HID Interface Class SubClass Codes */ -#define HID_BOOT_INTF_SUBCLASS 0x01 - -/* HID Interface Class Protocol Codes */ -#define HID_PROTOCOL_NONE 0x00 -#define HID_PROTOCOL_KEYBOARD 0x01 -#define HID_PROTOCOL_MOUSE 0x02 - -#define HID_ITEM_TYPE_MAIN 0 -#define HID_ITEM_TYPE_GLOBAL 1 -#define HID_ITEM_TYPE_LOCAL 2 -#define HID_ITEM_TYPE_RESERVED 3 - -#define HID_LONG_ITEM_PREFIX 0xfe // Long item prefix value - -#define bmHID_MAIN_ITEM_TAG 0xfc // Main item tag mask - -#define bmHID_MAIN_ITEM_INPUT 0x80 // Main item Input tag value -#define bmHID_MAIN_ITEM_OUTPUT 0x90 // Main item Output tag value -#define bmHID_MAIN_ITEM_FEATURE 0xb0 // Main item Feature tag value -#define bmHID_MAIN_ITEM_COLLECTION 0xa0 // Main item Collection tag value -#define bmHID_MAIN_ITEM_END_COLLECTION 0xce // Main item End Collection tag value - -#define HID_MAIN_ITEM_COLLECTION_PHYSICAL 0 -#define HID_MAIN_ITEM_COLLECTION_APPLICATION 1 -#define HID_MAIN_ITEM_COLLECTION_LOGICAL 2 -#define HID_MAIN_ITEM_COLLECTION_REPORT 3 -#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY 4 -#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH 5 -#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6 - -struct HidItemPrefix { - uint8_t bSize : 2; - uint8_t bType : 2; - uint8_t bTag : 4; -}; - -struct MainItemIOFeature { - uint8_t bmIsConstantOrData : 1; - uint8_t bmIsArrayOrVariable : 1; - uint8_t bmIsRelativeOrAbsolute : 1; - uint8_t bmIsWrapOrNoWrap : 1; - uint8_t bmIsNonLonearOrLinear : 1; - uint8_t bmIsNoPreferedOrPrefered : 1; - uint8_t bmIsNullOrNoNull : 1; - uint8_t bmIsVolatileOrNonVolatile : 1; -}; - -class HID; - -class HIDReportParser { -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf)= 0; -}; - -class HID : public USBDeviceConfig, public UsbConfigXtracter { -protected: - USBHost *pUsb; // USB class instance pointer - uint32_t bAddress; // address - -protected: - static const uint32_t epInterruptInIndex = 1; // InterruptIN endpoint index - static const uint32_t epInterruptOutIndex = 2; // InterruptOUT endpoint index - - static const uint32_t maxHidInterfaces = 3; - static const uint32_t maxEpPerInterface = 2; - static const uint32_t totalEndpoints = (maxHidInterfaces * maxEpPerInterface + 1); - - void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr); - void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc); - - virtual HIDReportParser* GetReportParser(uint32_t id); - -public: - - HID(USBHost *pusb) : pUsb(pusb) { - }; - - const USBHost* GetUsb() { - return pUsb; - }; - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs); - - uint32_t SetProtocol(uint32_t iface, uint32_t protocol); - uint32_t GetProtocol(uint32_t iface, uint8_t* dataptr); - uint32_t GetIdle(uint32_t iface, uint32_t reportID, uint8_t* dataptr); - uint32_t SetIdle(uint32_t iface, uint32_t reportID, uint32_t duration); - - uint32_t GetReportDescr(uint32_t ep, USBReadParser *parser = NULL); - - uint32_t GetHidDescr(uint32_t ep, uint32_t nbytes, uint8_t* dataptr); - uint32_t GetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetReport(uint32_t ep, uint32_t iface, uint32_t report_type, uint32_t report_id, uint32_t nbytes, uint8_t* dataptr); -}; - -#endif // __HID_H__ diff --git a/test/libraries/USBHost/src/hidboot.cpp b/test/libraries/USBHost/src/hidboot.cpp deleted file mode 100644 index 9f6b8743..00000000 --- a/test/libraries/USBHost/src/hidboot.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#include "hidboot.h" - -void MouseReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - MOUSEINFO *pmi = (MOUSEINFO*)buf; - // Future: - // bool event; - -#if 0 - if (prevState.mouseInfo.bmLeftButton == 0 && pmi->bmLeftButton == 1) - OnLeftButtonDown(pmi); - - if (prevState.mouseInfo.bmLeftButton == 1 && pmi->bmLeftButton == 0) - OnLeftButtonUp(pmi); - - if (prevState.mouseInfo.bmRightButton == 0 && pmi->bmRightButton == 1) - OnRightButtonDown(pmi); - - if (prevState.mouseInfo.bmRightButton == 1 && pmi->bmRightButton == 0) - OnRightButtonUp(pmi); - - if (prevState.mouseInfo.bmMiddleButton == 0 && pmi->bmMiddleButton == 1) - OnMiddleButtonDown(pmi); - - if (prevState.mouseInfo.bmMiddleButton == 1 && pmi->bmMiddleButton == 0) - OnMiddleButtonUp(pmi); - - if (prevState.mouseInfo.dX != pmi->dX || prevState.mouseInfo.dY != pmi->dY) - OnMouseMove(pmi); - - if (len > sizeof (MOUSEINFO)) - for (uint32_t i = 0; ibmLeftButton ) { - if(pmi->bmLeftButton) { - OnLeftButtonDown(pmi); - } else { - OnLeftButtonUp(pmi); - } - // Future: - // event = true; - } - - if(prevState.mouseInfo.bmRightButton != pmi->bmRightButton) { - if(pmi->bmRightButton) { - OnRightButtonDown(pmi); - } else { - OnRightButtonUp(pmi); - } - // Future: - // event = true; - } - - if(prevState.mouseInfo.bmMiddleButton != pmi->bmMiddleButton) { - if(pmi->bmMiddleButton) { - OnMiddleButtonDown(pmi); - } else { - OnMiddleButtonUp(pmi); - } - // Future: - // event = true; - } - - // - // Scroll wheel(s), are not part of the spec, but we could support it. - // Logitech wireless keyboard and mouse combo reports scroll wheel in byte 4 - // We wouldn't even need to save this information. - //if(len > 3) { - //} - // - - // Mice only report motion when they actually move! - // Why not just pass the x/y values to simplify things?? - if(pmi->dX || pmi->dY) { - OnMouseMove(pmi); - // Future: - // event = true; - } - - // - // Future: - // Provide a callback that operates on the gathered events from above. - // - // if(event) OnMouse(); - // - - // Only the first byte matters (buttons). We do NOT need to save position info. - prevState.bInfo[0] = buf[0]; -#endif - -}; - -void KeyboardReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - // On error - return - if (buf[2] == 1) - return; - - //KBDINFO *pki = (KBDINFO*)buf; - - // provide event for changed control key state - if (prevState.bInfo[0x00] != buf[0x00]) { - OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]); - } - - for (uint32_t i = 2; i < 8; i++) { - bool down = false; - bool up = false; - - for (uint8_t j = 2; j < 8; j++) { - if (buf[i] == prevState.bInfo[j] && buf[i] != 1) - down = true; - if (buf[j] == prevState.bInfo[i] && prevState.bInfo[i] != 1) - up = true; - } - if (!down) { - HandleLockingKeys(hid, buf[i]); - OnKeyDown(*buf, buf[i]); - } - if (!up) - OnKeyUp(prevState.bInfo[0], prevState.bInfo[i]); - } - for(uint32_t i = 0; i < 8; i++) - prevState.bInfo[i] = buf[i]; -}; - -uint8_t KeyboardReportParser::HandleLockingKeys(HID *hid, uint8_t key) { - uint8_t old_keys = kbdLockingKeys.bLeds; - - switch (key) { - case UHS_HID_BOOT_KEY_NUM_LOCK: - kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock; - break; - case UHS_HID_BOOT_KEY_CAPS_LOCK: - kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock; - break; - case UHS_HID_BOOT_KEY_SCROLL_LOCK: - kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock; - break; - } - - if (old_keys != kbdLockingKeys.bLeds && hid) - return (hid->SetReport(0, 0/*hid->GetIface()*/, 2, 0, 1, &kbdLockingKeys.bLeds)); - - return 0; -} - -const uint8_t KeyboardReportParser::numKeys[10] = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; -const uint8_t KeyboardReportParser::symKeysUp[12] = { '_', '+', '{', '}', '|', '~', ':', '"', '~', '<', '>', '?'}; -const uint8_t KeyboardReportParser::symKeysLo[12] = { '-', '=', '[', ']', '\\', ' ', ';', '\'', '`', ',', '.', '/'}; -const uint8_t KeyboardReportParser::padKeys[5] = { '/', '*', '-', '+', 0x13}; -#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) -uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) { - uint8_t shift = (mod & 0x22); - - // [a-z] - if (VALUE_WITHIN(key, 0x04, 0x1d)) { - // Upper case letters - if ((kbdLockingKeys.kbdLeds.bmCapsLock == 0 && (mod & 2)) || - (kbdLockingKeys.kbdLeds.bmCapsLock == 1 && (mod & 2) == 0)) - return (key - 4 + 'A'); - - // Lower case letters - else - return (key - 4 + 'a'); - }// Numbers - else if (VALUE_WITHIN(key, 0x1e, 0x27)) { - if (shift) - return ((uint8_t)pgm_read_byte(&getNumKeys()[key - 0x1e])); - else - return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1'); - }// Keypad Numbers - else if(VALUE_WITHIN(key, 0x59, 0x61)) { - if(kbdLockingKeys.kbdLeds.bmNumLock == 1) - return (key - 0x59 + '1'); - } else if(VALUE_WITHIN(key, 0x2d, 0x38)) - return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d])); - else if(VALUE_WITHIN(key, 0x54, 0x58)) - return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]); - else { - switch(key) { - case UHS_HID_BOOT_KEY_SPACE: return (0x20); - case UHS_HID_BOOT_KEY_ENTER: return (0x13); - case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0); - case UHS_HID_BOOT_KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0); - } - } - return ( 0); -} - diff --git a/test/libraries/USBHost/src/hidboot.h b/test/libraries/USBHost/src/hidboot.h deleted file mode 100644 index 621ce57a..00000000 --- a/test/libraries/USBHost/src/hidboot.h +++ /dev/null @@ -1,609 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#ifndef HIDBOOT_H_INCLUDED -#define HIDBOOT_H_INCLUDED - -#include -#include "Usb.h" -#include "hid.h" -#include "Arduino.h" - -#define UHS_HID_BOOT_KEY_ZERO 0x27 -#define UHS_HID_BOOT_KEY_ENTER 0x28 -#define UHS_HID_BOOT_KEY_SPACE 0x2c -#define UHS_HID_BOOT_KEY_CAPS_LOCK 0x39 -#define UHS_HID_BOOT_KEY_SCROLL_LOCK 0x47 -#define UHS_HID_BOOT_KEY_NUM_LOCK 0x53 -#define UHS_HID_BOOT_KEY_ZERO2 0x62 -#define UHS_HID_BOOT_KEY_PERIOD 0x63 - -// Don't worry, GCC will optimize the result to a final value. -#define bitsEndpoints(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 2 : 0) | (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) -#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2) -#define epMUL(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 1 : 0) + (((p) & HID_PROTOCOL_MOUSE)? 1 : 0)) - -// Already defined in hid.h -// #define HID_MAX_HID_CLASS_DESCRIPTORS 5 - -struct MOUSEINFO { - - struct { - uint8_t bmLeftButton : 1; - uint8_t bmRightButton : 1; - uint8_t bmMiddleButton : 1; - uint8_t bmDummy : 5; - }; - int8_t dX; - int8_t dY; -}; - -class MouseReportParser : public HIDReportParser { - - union { - MOUSEINFO mouseInfo; - uint8_t bInfo[sizeof (MOUSEINFO)]; - } prevState; - -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); - -protected: - - virtual void OnMouseMove(MOUSEINFO *mi) { - }; - - virtual void OnLeftButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnLeftButtonDown(MOUSEINFO *mi) { - }; - - virtual void OnRightButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnRightButtonDown(MOUSEINFO *mi) { - }; - - virtual void OnMiddleButtonUp(MOUSEINFO *mi) { - }; - - virtual void OnMiddleButtonDown(MOUSEINFO *mi) { - }; -}; - -struct MODIFIERKEYS { - uint8_t bmLeftCtrl : 1; - uint8_t bmLeftShift : 1; - uint8_t bmLeftAlt : 1; - uint8_t bmLeftGUI : 1; - uint8_t bmRightCtrl : 1; - uint8_t bmRightShift : 1; - uint8_t bmRightAlt : 1; - uint8_t bmRightGUI : 1; -}; - -struct KBDINFO { - - struct { - uint8_t bmLeftCtrl : 1; - uint8_t bmLeftShift : 1; - uint8_t bmLeftAlt : 1; - uint8_t bmLeftGUI : 1; - uint8_t bmRightCtrl : 1; - uint8_t bmRightShift : 1; - uint8_t bmRightAlt : 1; - uint8_t bmRightGUI : 1; - }; - uint8_t bReserved; - uint8_t Keys[6]; -}; - -struct KBDLEDS { - uint8_t bmNumLock : 1; - uint8_t bmCapsLock : 1; - uint8_t bmScrollLock : 1; - uint8_t bmCompose : 1; - uint8_t bmKana : 1; - uint8_t bmReserved : 3; -}; - -class KeyboardReportParser : public HIDReportParser { - static const uint8_t numKeys[10]; - static const uint8_t symKeysUp[12]; - static const uint8_t symKeysLo[12]; - static const uint8_t padKeys[5]; - -protected: - - union { - KBDINFO kbdInfo; - uint8_t bInfo[sizeof (KBDINFO)]; - } prevState; - - union { - KBDLEDS kbdLeds; - uint8_t bLeds; - } kbdLockingKeys; - - uint8_t OemToAscii(uint8_t mod, uint8_t key); - -public: - - KeyboardReportParser() { - kbdLockingKeys.bLeds = 0; - }; - - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); - -protected: - virtual uint8_t HandleLockingKeys(HID* hid, uint8_t key); - - virtual void OnControlKeysChanged(uint8_t before, uint8_t after) { - }; - - virtual void OnKeyDown(uint8_t mod, uint8_t key) { - }; - - virtual void OnKeyUp(uint8_t mod, uint8_t key) { - }; - - virtual const uint8_t *getNumKeys() { - return numKeys; - }; - - virtual const uint8_t *getSymKeysUp() { - return symKeysUp; - }; - - virtual const uint8_t *getSymKeysLo() { - return symKeysLo; - }; - - virtual const uint8_t *getPadKeys() { - return padKeys; - }; -}; - -template -class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter -{ - EpInfo epInfo[totalEndpoints(BOOT_PROTOCOL)]; - HIDReportParser *pRptParser[epMUL(BOOT_PROTOCOL)]; - - uint32_t bConfNum; // configuration number - uint32_t bIfaceNum; // Interface Number - uint32_t bNumIface; // number of interfaces in the configuration - uint32_t bNumEP; // total number of EP in the configuration - - uint32_t qNextPollTime; // next poll time - uint32_t bPollEnable; // poll enable flag - uint32_t bInterval; // largest interval - - void Initialize(); - - virtual HIDReportParser* GetReportParser(uint32_t id) { - return pRptParser[id]; - }; - -public: - HIDBoot(USBHost *p); - - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs) { - pRptParser[id] = prs; - return true; - }; - - // USBDeviceConfig implementation - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - // UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; - -template -HIDBoot::HIDBoot(USBHost *p) : - HID(p), - qNextPollTime(0), - bPollEnable(false) { - Initialize(); - - for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - pRptParser[i] = NULL; - } - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -template -void HIDBoot::Initialize() { - for(int i = 0; i < totalEndpoints(BOOT_PROTOCOL); i++) { - epInfo[i].epAddr = 0; - epInfo[i].maxPktSize = (i) ? 0 : 8; - epInfo[i].epAttribs = 0; - epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; - } - bNumEP = 1; - bNumIface = 0; - bConfNum = 0; -} - -template -uint32_t HIDBoot::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); - - uint8_t buf[constBufSize]; - uint32_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint32_t len = 0; - //uint16_t cd_len = 0; - - uint32_t num_of_conf; // number of configurations - //uint32_t num_of_intf; // number of interfaces - - // Get memory address of USB device address pool - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("BM Init\r\n"); - //USBTRACE2("totalEndpoints:", (uint8_t) (totalEndpoints(BOOT_PROTOCOL))); - //USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL)); - - // Check if address has already been assigned to an instance - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - bInterval = 0; - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) { - USBTRACE("epinfo\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(0, 0, /*8*/sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - - if(!rcode) - len = (buf[0] > constBufSize) ? constBufSize : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - - goto FailGetDevDescr; - } - - - // Reset - UHD_BusReset(); - while( Is_uhd_starting_reset() ) {} - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0; - - // Assign new address to the device SET_ADDRESS - - rcode = pUsb->setAddr(0, 0, bAddress); - if(rcode) { - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - USBTRACE2("setAddr:", rcode); - return rcode; - } - //delay(2); //per USB 2.0 sect.9.2.6.3 - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - // Get device descriptor GET_DESCRIPTOR - rcode = pUsb->getDevDescr(bAddress, 0, sizeof(USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); - // Restore p->epinfo - p->epinfo = oldep_ptr; - if (rcode) - { - goto FailGetDevDescr; - } - - TRACE_USBHOST(printf("HIDBoot::Init : device address is now %lu\r\n", bAddress);) - - p->lowspeed = false; - - //get pointer to assigned address record - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations; - - USBTRACE2("NC:", num_of_conf); - - // GCC will optimize unused stuff away. - if((BOOT_PROTOCOL & (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) == (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) { - USBTRACE("HID_PROTOCOL_KEYBOARD AND MOUSE\r\n"); - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE, - CP_MASK_COMPARE_ALL > confDescrParser(this); - confDescrParser.SetOR(); // Use the OR variant. - for(uint32_t i = 0; i < num_of_conf; i++) { - pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) - break; - } - } else { - // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - USBTRACE("HID_PROTOCOL_KEYBOARD\r\n"); - for(uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_KEYBOARD, - CP_MASK_COMPARE_ALL> confDescrParserA(this); - - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA); - if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) - break; - } - } - - // GCC will optimize unused stuff away. - if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) { - USBTRACE("HID_PROTOCOL_MOUSE\r\n"); - for(uint32_t i = 0; i < num_of_conf; i++) { - ConfigDescParser< - USB_CLASS_HID, - HID_BOOT_INTF_SUBCLASS, - HID_PROTOCOL_MOUSE, - CP_MASK_COMPARE_ALL> confDescrParserB(this); - - pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB); - if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL)))) - break; - - } - } - } - USBTRACE2("bNumEP:", bNumEP); - - if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) { - rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - goto Fail; - } - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - //USBTRACE2("setEpInfoEntry returned ", rcode); - USBTRACE2("Cnf:", bConfNum); - - delay(1000); - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - - if(rcode) - goto FailSetConfDescr; - - delay(1000); - - USBTRACE2("bIfaceNum:", bIfaceNum); - USBTRACE2("bNumIface:", bNumIface); - - // Yes, mouse wants SetProtocol and SetIdle too! - for(uint32_t i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - USBTRACE2("\r\nInterface:", i); - rcode = SetProtocol(i, HID_BOOT_PROTOCOL); - if(rcode) goto FailSetProtocol; - USBTRACE2("PROTOCOL SET HID_BOOT rcode:", rcode); - rcode = SetIdle(i, 0, 0); - USBTRACE2("SET_IDLE rcode:", rcode); - // if(rcode) goto FailSetIdle; This can fail. - // Get the RPIPE and just throw it away. - SinkParser sink; - rcode = GetReportDescr(i, (USBReadParser *)&sink); - USBTRACE2("RPIPE rcode:", rcode); - } - - // Get RPIPE and throw it away. - - if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) { - // Wake keyboard interface by twinkling up to 5 LEDs that are in the spec. - // kana, compose, scroll, caps, num - rcode = 0x20; // Reuse rcode. - while(rcode) { - rcode >>= 1; - // Ignore any error returned, we don't care if LED is not supported - SetReport(0, 0, 2, 0, 1, (uint8_t*)&rcode); // Eventually becomes zero (All off) - delay(25); - } - } - USBTRACE("BM configured\r\n"); - - bPollEnable = true; - return 0; - -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(); - goto Fail; -#endif - - //FailSetDevTblEntry: - //#ifdef DEBUG_USB_HOST - // NotifyFailSetDevTblEntry(); - // goto Fail; - //#endif - - //FailGetConfDescr: - //#ifdef DEBUG_USB_HOST - // NotifyFailGetConfDescr(); - // goto Fail; - //#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(); - goto Fail; -#endif - -FailSetProtocol: -#ifdef DEBUG_USB_HOST - USBTRACE("SetProto:"); - goto Fail; -#endif - - //FailSetIdle: - //#ifdef DEBUG_USB_HOST - // USBTRACE("SetIdle:"); - //#endif - -Fail: -#ifdef DEBUG_USB_HOST - NotifyFail(rcode); -#endif - Release(); - - return rcode; -} - -template -void HIDBoot::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - // If the first configuration satisfies, the others are not considered. - //if(bNumEP > 1 && conf != bConfNum) - if(bNumEP == totalEndpoints(BOOT_PROTOCOL)) - return; - - bConfNum = conf; - bIfaceNum = iface; - - if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { - if(pep->bInterval > bInterval) bInterval = pep->bInterval; - - // Fill in the endpoint info structure - epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; - epInfo[bNumEP].epAttribs = 0; - epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; - bNumEP++; - - } -} - -template -uint32_t HIDBoot::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bConfNum = 0; - bIfaceNum = 0; - bNumEP = 1; - bAddress = 0; - qNextPollTime = 0; - bPollEnable = false; - - return 0; -} - -template -uint32_t HIDBoot::Poll() { - uint32_t rcode = 0; - - if(bPollEnable && ((long)(millis() - qNextPollTime) >= 0L)) { - - // To-do: optimize manually, using the for loop only if needed. - for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) { - const uint16_t const_buff_len = 16; - uint8_t buf[const_buff_len]; - - USBTRACE3("(hidboot.h) i=", i, 0x81); - USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].epAddr=", epInfo[epInterruptInIndex + i].epAddr, 0x81); - USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].maxPktSize=", epInfo[epInterruptInIndex + i].maxPktSize, 0x81); - uint16_t read = (uint16_t)epInfo[epInterruptInIndex + i].maxPktSize; - UHD_Pipe_Alloc(bAddress, epInfo[epInterruptInIndex + i].epAddr, USB_HOST_PTYPE_BULK, USB_EP_DIR_IN, epInfo[epInterruptInIndex + i].maxPktSize, 0, USB_HOST_NB_BK_1); - rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, (uint8_t*)&read, buf); - // SOME buggy dongles report extra keys (like sleep) using a 2 byte packet on the wrong endpoint. - // Since keyboard and mice must report at least 3 bytes, we ignore the extra data. - if(!rcode && read > 2) { - if(pRptParser[i]) - pRptParser[i]->Parse((HID*)this, 0, (uint8_t)read, buf); -#ifdef DEBUG_USB_HOST - // We really don't care about errors and anomalies unless we are debugging. - } else { - if(rcode != USB_ERRORFLOW) { - USBTRACE3("(hidboot.h) Poll:", rcode, 0x81); - } - if(!rcode && read) { - USBTRACE3("(hidboot.h) Strange read count: ", read, 0x80); - USBTRACE3("(hidboot.h) Interface:", i, 0x80); - } - } - - if(!rcode && read && (UsbDEBUGlvl > 0x7f)) { - for(uint8_t i = 0; i < read; i++) { - PrintHex (buf[i], 0x80); - USBTRACE1(" ", 0x80); - } - if(read) - USBTRACE1("\r\n", 0x80); -#endif - } - - } - qNextPollTime = millis() + bInterval; - } - return rcode; -} - -#endif /* HIDBOOT_H_INCLUDED */ diff --git a/test/libraries/USBHost/src/hidescriptorparser.cpp b/test/libraries/USBHost/src/hidescriptorparser.cpp deleted file mode 100644 index 17e1e35a..00000000 --- a/test/libraries/USBHost/src/hidescriptorparser.cpp +++ /dev/null @@ -1,1599 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "hidescriptorparser.h" - -const char * const ReportDescParserBase::usagePageTitles0[] PROGMEM = { - pstrUsagePageGenericDesktopControls, - pstrUsagePageSimulationControls, - pstrUsagePageVRControls, - pstrUsagePageSportControls, - pstrUsagePageGameControls, - pstrUsagePageGenericDeviceControls, - pstrUsagePageKeyboardKeypad, - pstrUsagePageLEDs, - pstrUsagePageButton, - pstrUsagePageOrdinal, - pstrUsagePageTelephone, - pstrUsagePageConsumer, - pstrUsagePageDigitizer, - pstrUsagePagePID, - pstrUsagePageUnicode -}; - -const char * const ReportDescParserBase::usagePageTitles1[] PROGMEM = { - pstrUsagePageBarCodeScanner, - pstrUsagePageScale, - pstrUsagePageMSRDevices, - pstrUsagePagePointOfSale, - pstrUsagePageCameraControl, - pstrUsagePageArcade -}; -const char * const ReportDescParserBase::genDesktopTitles0[] PROGMEM = { - pstrUsagePointer, - pstrUsageMouse, - pstrUsageJoystick, - pstrUsageGamePad, - pstrUsageKeyboard, - pstrUsageKeypad, - pstrUsageMultiAxisController, - pstrUsageTabletPCSystemControls - -}; -const char * const ReportDescParserBase::genDesktopTitles1[] PROGMEM = { - pstrUsageX, - pstrUsageY, - pstrUsageZ, - pstrUsageRx, - pstrUsageRy, - pstrUsageRz, - pstrUsageSlider, - pstrUsageDial, - pstrUsageWheel, - pstrUsageHatSwitch, - pstrUsageCountedBuffer, - pstrUsageByteCount, - pstrUsageMotionWakeup, - pstrUsageStart, - pstrUsageSelect, - pstrUsagePageReserved, - pstrUsageVx, - pstrUsageVy, - pstrUsageVz, - pstrUsageVbrx, - pstrUsageVbry, - pstrUsageVbrz, - pstrUsageVno, - pstrUsageFeatureNotification, - pstrUsageResolutionMultiplier -}; -const char * const ReportDescParserBase::genDesktopTitles2[] PROGMEM = { - pstrUsageSystemControl, - pstrUsageSystemPowerDown, - pstrUsageSystemSleep, - pstrUsageSystemWakeup, - pstrUsageSystemContextMenu, - pstrUsageSystemMainMenu, - pstrUsageSystemAppMenu, - pstrUsageSystemMenuHelp, - pstrUsageSystemMenuExit, - pstrUsageSystemMenuSelect, - pstrUsageSystemMenuRight, - pstrUsageSystemMenuLeft, - pstrUsageSystemMenuUp, - pstrUsageSystemMenuDown, - pstrUsageSystemColdRestart, - pstrUsageSystemWarmRestart, - pstrUsageDPadUp, - pstrUsageDPadDown, - pstrUsageDPadRight, - pstrUsageDPadLeft -}; -const char * const ReportDescParserBase::genDesktopTitles3[] PROGMEM = { - pstrUsageSystemDock, - pstrUsageSystemUndock, - pstrUsageSystemSetup, - pstrUsageSystemBreak, - pstrUsageSystemDebuggerBreak, - pstrUsageApplicationBreak, - pstrUsageApplicationDebuggerBreak, - pstrUsageSystemSpeakerMute, - pstrUsageSystemHibernate -}; -const char * const ReportDescParserBase::genDesktopTitles4[] PROGMEM = { - pstrUsageSystemDisplayInvert, - pstrUsageSystemDisplayInternal, - pstrUsageSystemDisplayExternal, - pstrUsageSystemDisplayBoth, - pstrUsageSystemDisplayDual, - pstrUsageSystemDisplayToggleIntExt, - pstrUsageSystemDisplaySwapPriSec, - pstrUsageSystemDisplayLCDAutoscale -}; -const char * const ReportDescParserBase::simuTitles0[] PROGMEM = { - pstrUsageFlightSimulationDevice, - pstrUsageAutomobileSimulationDevice, - pstrUsageTankSimulationDevice, - pstrUsageSpaceshipSimulationDevice, - pstrUsageSubmarineSimulationDevice, - pstrUsageSailingSimulationDevice, - pstrUsageMotocicleSimulationDevice, - pstrUsageSportsSimulationDevice, - pstrUsageAirplaneSimulationDevice, - pstrUsageHelicopterSimulationDevice, - pstrUsageMagicCarpetSimulationDevice, - pstrUsageBicycleSimulationDevice -}; -const char * const ReportDescParserBase::simuTitles1[] PROGMEM = { - pstrUsageFlightControlStick, - pstrUsageFlightStick, - pstrUsageCyclicControl, - pstrUsageCyclicTrim, - pstrUsageFlightYoke, - pstrUsageTrackControl -}; -const char * const ReportDescParserBase::simuTitles2[] PROGMEM = { - pstrUsageAileron, - pstrUsageAileronTrim, - pstrUsageAntiTorqueControl, - pstrUsageAutopilotEnable, - pstrUsageChaffRelease, - pstrUsageCollectiveControl, - pstrUsageDiveBrake, - pstrUsageElectronicCountermeasures, - pstrUsageElevator, - pstrUsageElevatorTrim, - pstrUsageRudder, - pstrUsageThrottle, - pstrUsageFlightCommunications, - pstrUsageFlareRelease, - pstrUsageLandingGear, - pstrUsageToeBrake, - pstrUsageTrigger, - pstrUsageWeaponsArm, - pstrUsageWeaponsSelect, - pstrUsageWingFlaps, - pstrUsageAccelerator, - pstrUsageBrake, - pstrUsageClutch, - pstrUsageShifter, - pstrUsageSteering, - pstrUsageTurretDirection, - pstrUsageBarrelElevation, - pstrUsageDivePlane, - pstrUsageBallast, - pstrUsageBicycleCrank, - pstrUsageHandleBars, - pstrUsageFrontBrake, - pstrUsageRearBrake -}; -const char * const ReportDescParserBase::vrTitles0[] PROGMEM = { - pstrUsageBelt, - pstrUsageBodySuit, - pstrUsageFlexor, - pstrUsageGlove, - pstrUsageHeadTracker, - pstrUsageHeadMountedDisplay, - pstrUsageHandTracker, - pstrUsageOculometer, - pstrUsageVest, - pstrUsageAnimatronicDevice -}; -const char * const ReportDescParserBase::vrTitles1[] PROGMEM = { - pstrUsageStereoEnable, - pstrUsageDisplayEnable -}; -const char * const ReportDescParserBase::sportsCtrlTitles0[] PROGMEM = { - pstrUsageBaseballBat, - pstrUsageGolfClub, - pstrUsageRowingMachine, - pstrUsageTreadmill -}; -const char * const ReportDescParserBase::sportsCtrlTitles1[] PROGMEM = { - pstrUsageOar, - pstrUsageSlope, - pstrUsageRate, - pstrUsageStickSpeed, - pstrUsageStickFaceAngle, - pstrUsageStickHeelToe, - pstrUsageStickFollowThough, - pstrUsageStickTempo, - pstrUsageStickType, - pstrUsageStickHeight -}; -const char * const ReportDescParserBase::sportsCtrlTitles2[] PROGMEM = { - pstrUsagePutter, - pstrUsage1Iron, - pstrUsage2Iron, - pstrUsage3Iron, - pstrUsage4Iron, - pstrUsage5Iron, - pstrUsage6Iron, - pstrUsage7Iron, - pstrUsage8Iron, - pstrUsage9Iron, - pstrUsage10Iron, - pstrUsage11Iron, - pstrUsageSandWedge, - pstrUsageLoftWedge, - pstrUsagePowerWedge, - pstrUsage1Wood, - pstrUsage3Wood, - pstrUsage5Wood, - pstrUsage7Wood, - pstrUsage9Wood -}; -const char * const ReportDescParserBase::gameTitles0[] PROGMEM = { - pstrUsage3DGameController, - pstrUsagePinballDevice, - pstrUsageGunDevice -}; -const char * const ReportDescParserBase::gameTitles1[] PROGMEM = { - pstrUsagePointOfView, - pstrUsageTurnRightLeft, - pstrUsagePitchForwardBackward, - pstrUsageRollRightLeft, - pstrUsageMoveRightLeft, - pstrUsageMoveForwardBackward, - pstrUsageMoveUpDown, - pstrUsageLeanRightLeft, - pstrUsageLeanForwardBackward, - pstrUsageHeightOfPOV, - pstrUsageFlipper, - pstrUsageSecondaryFlipper, - pstrUsageBump, - pstrUsageNewGame, - pstrUsageShootBall, - pstrUsagePlayer, - pstrUsageGunBolt, - pstrUsageGunClip, - pstrUsageGunSelector, - pstrUsageGunSingleShot, - pstrUsageGunBurst, - pstrUsageGunAutomatic, - pstrUsageGunSafety, - pstrUsageGamepadFireJump, - pstrUsageGamepadTrigger -}; -const char * const ReportDescParserBase::genDevCtrlTitles[] PROGMEM = { - pstrUsageBatteryStrength, - pstrUsageWirelessChannel, - pstrUsageWirelessID, - pstrUsageDiscoverWirelessControl, - pstrUsageSecurityCodeCharEntered, - pstrUsageSecurityCodeCharErased, - pstrUsageSecurityCodeCleared -}; -const char * const ReportDescParserBase::ledTitles[] PROGMEM = { - pstrUsageNumLock, - pstrUsageCapsLock, - pstrUsageScrollLock, - pstrUsageCompose, - pstrUsageKana, - pstrUsagePower, - pstrUsageShift, - pstrUsageDoNotDisturb, - pstrUsageMute, - pstrUsageToneEnable, - pstrUsageHighCutFilter, - pstrUsageLowCutFilter, - pstrUsageEqualizerEnable, - pstrUsageSoundFieldOn, - pstrUsageSurroundOn, - pstrUsageRepeat, - pstrUsageStereo, - pstrUsageSamplingRateDetect, - pstrUsageSpinning, - pstrUsageCAV, - pstrUsageCLV, - pstrUsageRecordingFormatDetect, - pstrUsageOffHook, - pstrUsageRing, - pstrUsageMessageWaiting, - pstrUsageDataMode, - pstrUsageBatteryOperation, - pstrUsageBatteryOK, - pstrUsageBatteryLow, - pstrUsageSpeaker, - pstrUsageHeadSet, - pstrUsageHold, - pstrUsageMicrophone, - pstrUsageCoverage, - pstrUsageNightMode, - pstrUsageSendCalls, - pstrUsageCallPickup, - pstrUsageConference, - pstrUsageStandBy, - pstrUsageCameraOn, - pstrUsageCameraOff, - pstrUsageOnLine, - pstrUsageOffLine, - pstrUsageBusy, - pstrUsageReady, - pstrUsagePaperOut, - pstrUsagePaperJam, - pstrUsageRemote, - pstrUsageForward, - pstrUsageReverse, - pstrUsageStop, - pstrUsageRewind, - pstrUsageFastForward, - pstrUsagePlay, - pstrUsagePause, - pstrUsageRecord, - pstrUsageError, - pstrUsageSelectedIndicator, - pstrUsageInUseIndicator, - pstrUsageMultiModeIndicator, - pstrUsageIndicatorOn, - pstrUsageIndicatorFlash, - pstrUsageIndicatorSlowBlink, - pstrUsageIndicatorFastBlink, - pstrUsageIndicatorOff, - pstrUsageFlashOnTime, - pstrUsageSlowBlinkOnTime, - pstrUsageSlowBlinkOffTime, - pstrUsageFastBlinkOnTime, - pstrUsageFastBlinkOffTime, - pstrUsageIndicatorColor, - pstrUsageIndicatorRed, - pstrUsageIndicatorGreen, - pstrUsageIndicatorAmber, - pstrUsageGenericIndicator, - pstrUsageSystemSuspend, - pstrUsageExternalPowerConnected -}; -const char * const ReportDescParserBase::telTitles0 [] PROGMEM = { - pstrUsagePhone, - pstrUsageAnsweringMachine, - pstrUsageMessageControls, - pstrUsageHandset, - pstrUsageHeadset, - pstrUsageTelephonyKeyPad, - pstrUsageProgrammableButton -}; -const char * const ReportDescParserBase::telTitles1 [] PROGMEM = { - pstrUsageHookSwitch, - pstrUsageFlash, - pstrUsageFeature, - pstrUsageHold, - pstrUsageRedial, - pstrUsageTransfer, - pstrUsageDrop, - pstrUsagePark, - pstrUsageForwardCalls, - pstrUsageAlternateFunction, - pstrUsageLine, - pstrUsageSpeakerPhone, - pstrUsageConference, - pstrUsageRingEnable, - pstrUsageRingSelect, - pstrUsagePhoneMute, - pstrUsageCallerID, - pstrUsageSend -}; -const char * const ReportDescParserBase::telTitles2 [] PROGMEM = { - pstrUsageSpeedDial, - pstrUsageStoreNumber, - pstrUsageRecallNumber, - pstrUsagePhoneDirectory -}; -const char * const ReportDescParserBase::telTitles3 [] PROGMEM = { - pstrUsageVoiceMail, - pstrUsageScreenCalls, - pstrUsageDoNotDisturb, - pstrUsageMessage, - pstrUsageAnswerOnOff -}; -const char * const ReportDescParserBase::telTitles4 [] PROGMEM = { - pstrUsageInsideDialTone, - pstrUsageOutsideDialTone, - pstrUsageInsideRingTone, - pstrUsageOutsideRingTone, - pstrUsagePriorityRingTone, - pstrUsageInsideRingback, - pstrUsagePriorityRingback, - pstrUsageLineBusyTone, - pstrUsageReorderTone, - pstrUsageCallWaitingTone, - pstrUsageConfirmationTone1, - pstrUsageConfirmationTone2, - pstrUsageTonesOff, - pstrUsageOutsideRingback, - pstrUsageRinger -}; -const char * const ReportDescParserBase::telTitles5 [] PROGMEM = { - pstrUsagePhoneKey0, - pstrUsagePhoneKey1, - pstrUsagePhoneKey2, - pstrUsagePhoneKey3, - pstrUsagePhoneKey4, - pstrUsagePhoneKey5, - pstrUsagePhoneKey6, - pstrUsagePhoneKey7, - pstrUsagePhoneKey8, - pstrUsagePhoneKey9, - pstrUsagePhoneKeyStar, - pstrUsagePhoneKeyPound, - pstrUsagePhoneKeyA, - pstrUsagePhoneKeyB, - pstrUsagePhoneKeyC, - pstrUsagePhoneKeyD -}; -const char * const ReportDescParserBase::consTitles0[] PROGMEM = { - pstrUsageConsumerControl, - pstrUsageNumericKeyPad, - pstrUsageProgrammableButton, - pstrUsageMicrophone, - pstrUsageHeadphone, - pstrUsageGraphicEqualizer -}; -const char * const ReportDescParserBase::consTitles1[] PROGMEM = { - pstrUsagePlus10, - pstrUsagePlus100, - pstrUsageAMPM -}; -const char * const ReportDescParserBase::consTitles2[] PROGMEM = { - pstrUsagePower, - pstrUsageReset, - pstrUsageSleep, - pstrUsageSleepAfter, - pstrUsageSleepMode, - pstrUsageIllumination, - pstrUsageFunctionButtons - -}; -const char * const ReportDescParserBase::consTitles3[] PROGMEM = { - pstrUsageMenu, - pstrUsageMenuPick, - pstrUsageMenuUp, - pstrUsageMenuDown, - pstrUsageMenuLeft, - pstrUsageMenuRight, - pstrUsageMenuEscape, - pstrUsageMenuValueIncrease, - pstrUsageMenuValueDecrease -}; -const char * const ReportDescParserBase::consTitles4[] PROGMEM = { - pstrUsageDataOnScreen, - pstrUsageClosedCaption, - pstrUsageClosedCaptionSelect, - pstrUsageVCRTV, - pstrUsageBroadcastMode, - pstrUsageSnapshot, - pstrUsageStill -}; -const char * const ReportDescParserBase::consTitles5[] PROGMEM = { - pstrUsageSelection, - pstrUsageAssignSelection, - pstrUsageModeStep, - pstrUsageRecallLast, - pstrUsageEnterChannel, - pstrUsageOrderMovie, - pstrUsageChannel, - pstrUsageMediaSelection, - pstrUsageMediaSelectComputer, - pstrUsageMediaSelectTV, - pstrUsageMediaSelectWWW, - pstrUsageMediaSelectDVD, - pstrUsageMediaSelectTelephone, - pstrUsageMediaSelectProgramGuide, - pstrUsageMediaSelectVideoPhone, - pstrUsageMediaSelectGames, - pstrUsageMediaSelectMessages, - pstrUsageMediaSelectCD, - pstrUsageMediaSelectVCR, - pstrUsageMediaSelectTuner, - pstrUsageQuit, - pstrUsageHelp, - pstrUsageMediaSelectTape, - pstrUsageMediaSelectCable, - pstrUsageMediaSelectSatellite, - pstrUsageMediaSelectSecurity, - pstrUsageMediaSelectHome, - pstrUsageMediaSelectCall, - pstrUsageChannelIncrement, - pstrUsageChannelDecrement, - pstrUsageMediaSelectSAP, - pstrUsagePageReserved, - pstrUsageVCRPlus, - pstrUsageOnce, - pstrUsageDaily, - pstrUsageWeekly, - pstrUsageMonthly -}; -const char * const ReportDescParserBase::consTitles6[] PROGMEM = { - pstrUsagePlay, - pstrUsagePause, - pstrUsageRecord, - pstrUsageFastForward, - pstrUsageRewind, - pstrUsageScanNextTrack, - pstrUsageScanPreviousTrack, - pstrUsageStop, - pstrUsageEject, - pstrUsageRandomPlay, - pstrUsageSelectDisk, - pstrUsageEnterDisk, - pstrUsageRepeat, - pstrUsageTracking, - pstrUsageTrackNormal, - pstrUsageSlowTracking, - pstrUsageFrameForward, - pstrUsageFrameBackwards, - pstrUsageMark, - pstrUsageClearMark, - pstrUsageRepeatFromMark, - pstrUsageReturnToMark, - pstrUsageSearchMarkForward, - pstrUsageSearchMarkBackwards, - pstrUsageCounterReset, - pstrUsageShowCounter, - pstrUsageTrackingIncrement, - pstrUsageTrackingDecrement, - pstrUsageStopEject, - pstrUsagePlayPause, - pstrUsagePlaySkip -}; -const char * const ReportDescParserBase::consTitles7[] PROGMEM = { - pstrUsageVolume, - pstrUsageBalance, - pstrUsageMute, - pstrUsageBass, - pstrUsageTreble, - pstrUsageBassBoost, - pstrUsageSurroundMode, - pstrUsageLoudness, - pstrUsageMPX, - pstrUsageVolumeIncrement, - pstrUsageVolumeDecrement -}; -const char * const ReportDescParserBase::consTitles8[] PROGMEM = { - pstrUsageSpeedSelect, - pstrUsagePlaybackSpeed, - pstrUsageStandardPlay, - pstrUsageLongPlay, - pstrUsageExtendedPlay, - pstrUsageSlow -}; -const char * const ReportDescParserBase::consTitles9[] PROGMEM = { - pstrUsageFanEnable, - pstrUsageFanSpeed, - pstrUsageLightEnable, - pstrUsageLightIlluminationLevel, - pstrUsageClimateControlEnable, - pstrUsageRoomTemperature, - pstrUsageSecurityEnable, - pstrUsageFireAlarm, - pstrUsagePoliceAlarm, - pstrUsageProximity, - pstrUsageMotion, - pstrUsageDuresAlarm, - pstrUsageHoldupAlarm, - pstrUsageMedicalAlarm -}; -const char * const ReportDescParserBase::consTitlesA[] PROGMEM = { - pstrUsageBalanceRight, - pstrUsageBalanceLeft, - pstrUsageBassIncrement, - pstrUsageBassDecrement, - pstrUsageTrebleIncrement, - pstrUsageTrebleDecrement -}; -const char * const ReportDescParserBase::consTitlesB[] PROGMEM = { - pstrUsageSpeakerSystem, - pstrUsageChannelLeft, - pstrUsageChannelRight, - pstrUsageChannelCenter, - pstrUsageChannelFront, - pstrUsageChannelCenterFront, - pstrUsageChannelSide, - pstrUsageChannelSurround, - pstrUsageChannelLowFreqEnhancement, - pstrUsageChannelTop, - pstrUsageChannelUnknown -}; -const char * const ReportDescParserBase::consTitlesC[] PROGMEM = { - pstrUsageSubChannel, - pstrUsageSubChannelIncrement, - pstrUsageSubChannelDecrement, - pstrUsageAlternateAudioIncrement, - pstrUsageAlternateAudioDecrement -}; -const char * const ReportDescParserBase::consTitlesD[] PROGMEM = { - pstrUsageApplicationLaunchButtons, - pstrUsageALLaunchButtonConfigTool, - pstrUsageALProgrammableButton, - pstrUsageALConsumerControlConfig, - pstrUsageALWordProcessor, - pstrUsageALTextEditor, - pstrUsageALSpreadsheet, - pstrUsageALGraphicsEditor, - pstrUsageALPresentationApp, - pstrUsageALDatabaseApp, - pstrUsageALEmailReader, - pstrUsageALNewsreader, - pstrUsageALVoicemail, - pstrUsageALContactsAddressBook, - pstrUsageALCalendarSchedule, - pstrUsageALTaskProjectManager, - pstrUsageALLogJournalTimecard, - pstrUsageALCheckbookFinance, - pstrUsageALCalculator, - pstrUsageALAVCapturePlayback, - pstrUsageALLocalMachineBrowser, - pstrUsageALLANWANBrow, - pstrUsageALInternetBrowser, - pstrUsageALRemoteNetISPConnect, - pstrUsageALNetworkConference, - pstrUsageALNetworkChat, - pstrUsageALTelephonyDialer, - pstrUsageALLogon, - pstrUsageALLogoff, - pstrUsageALLogonLogoff, - pstrUsageALTermLockScrSav, - pstrUsageALControlPannel, - pstrUsageALCommandLineProcessorRun, - pstrUsageALProcessTaskManager, - pstrUsageALSelectTaskApplication, - pstrUsageALNextTaskApplication, - pstrUsageALPreviousTaskApplication, - pstrUsageALPreemptiveHaltTaskApp, - pstrUsageALIntegratedHelpCenter, - pstrUsageALDocuments, - pstrUsageALThesaurus, - pstrUsageALDictionary, - pstrUsageALDesktop, - pstrUsageALSpellCheck, - pstrUsageALGrammarCheck, - pstrUsageALWirelessStatus, - pstrUsageALKeyboardLayout, - pstrUsageALVirusProtection, - pstrUsageALEncryption, - pstrUsageALScreenSaver, - pstrUsageALAlarms, - pstrUsageALClock, - pstrUsageALFileBrowser, - pstrUsageALPowerStatus, - pstrUsageALImageBrowser, - pstrUsageALAudioBrowser, - pstrUsageALMovieBrowser, - pstrUsageALDigitalRightsManager, - pstrUsageALDigitalWallet, - pstrUsagePageReserved, - pstrUsageALInstantMessaging, - pstrUsageALOEMFeaturesBrowser, - pstrUsageALOEMHelp, - pstrUsageALOnlineCommunity, - pstrUsageALEntertainmentContentBrow, - pstrUsageALOnlineShoppingBrowser, - pstrUsageALSmartCardInfoHelp, - pstrUsageALMarketMonitorFinBrowser, - pstrUsageALCustomCorpNewsBrowser, - pstrUsageALOnlineActivityBrowser, - pstrUsageALResearchSearchBrowser, - pstrUsageALAudioPlayer -}; -const char * const ReportDescParserBase::consTitlesE[] PROGMEM = { - pstrUsageGenericGUIAppControls, - pstrUsageACNew, - pstrUsageACOpen, - pstrUsageACClose, - pstrUsageACExit, - pstrUsageACMaximize, - pstrUsageACMinimize, - pstrUsageACSave, - pstrUsageACPrint, - pstrUsageACProperties, - pstrUsageACUndo, - pstrUsageACCopy, - pstrUsageACCut, - pstrUsageACPaste, - pstrUsageACSelectAll, - pstrUsageACFind, - pstrUsageACFindAndReplace, - pstrUsageACSearch, - pstrUsageACGoto, - pstrUsageACHome, - pstrUsageACBack, - pstrUsageACForward, - pstrUsageACStop, - pstrUsageACRefresh, - pstrUsageACPreviousLink, - pstrUsageACNextLink, - pstrUsageACBookmarks, - pstrUsageACHistory, - pstrUsageACSubscriptions, - pstrUsageACZoomIn, - pstrUsageACZoomOut, - pstrUsageACZoom, - pstrUsageACFullScreenView, - pstrUsageACNormalView, - pstrUsageACViewToggle, - pstrUsageACScrollUp, - pstrUsageACScrollDown, - pstrUsageACScroll, - pstrUsageACPanLeft, - pstrUsageACPanRight, - pstrUsageACPan, - pstrUsageACNewWindow, - pstrUsageACTileHoriz, - pstrUsageACTileVert, - pstrUsageACFormat, - pstrUsageACEdit, - pstrUsageACBold, - pstrUsageACItalics, - pstrUsageACUnderline, - pstrUsageACStrikethrough, - pstrUsageACSubscript, - pstrUsageACSuperscript, - pstrUsageACAllCaps, - pstrUsageACRotate, - pstrUsageACResize, - pstrUsageACFlipHorizontal, - pstrUsageACFlipVertical, - pstrUsageACMirrorHorizontal, - pstrUsageACMirrorVertical, - pstrUsageACFontSelect, - pstrUsageACFontColor, - pstrUsageACFontSize, - pstrUsageACJustifyLeft, - pstrUsageACJustifyCenterH, - pstrUsageACJustifyRight, - pstrUsageACJustifyBlockH, - pstrUsageACJustifyTop, - pstrUsageACJustifyCenterV, - pstrUsageACJustifyBottom, - pstrUsageACJustifyBlockV, - pstrUsageACIndentDecrease, - pstrUsageACIndentIncrease, - pstrUsageACNumberedList, - pstrUsageACRestartNumbering, - pstrUsageACBulletedList, - pstrUsageACPromote, - pstrUsageACDemote, - pstrUsageACYes, - pstrUsageACNo, - pstrUsageACCancel, - pstrUsageACCatalog, - pstrUsageACBuyChkout, - pstrUsageACAddToCart, - pstrUsageACExpand, - pstrUsageACExpandAll, - pstrUsageACCollapse, - pstrUsageACCollapseAll, - pstrUsageACPrintPreview, - pstrUsageACPasteSpecial, - pstrUsageACInsertMode, - pstrUsageACDelete, - pstrUsageACLock, - pstrUsageACUnlock, - pstrUsageACProtect, - pstrUsageACUnprotect, - pstrUsageACAttachComment, - pstrUsageACDeleteComment, - pstrUsageACViewComment, - pstrUsageACSelectWord, - pstrUsageACSelectSentence, - pstrUsageACSelectParagraph, - pstrUsageACSelectColumn, - pstrUsageACSelectRow, - pstrUsageACSelectTable, - pstrUsageACSelectObject, - pstrUsageACRedoRepeat, - pstrUsageACSort, - pstrUsageACSortAscending, - pstrUsageACSortDescending, - pstrUsageACFilter, - pstrUsageACSetClock, - pstrUsageACViewClock, - pstrUsageACSelectTimeZone, - pstrUsageACEditTimeZone, - pstrUsageACSetAlarm, - pstrUsageACClearAlarm, - pstrUsageACSnoozeAlarm, - pstrUsageACResetAlarm, - pstrUsageACSyncronize, - pstrUsageACSendReceive, - pstrUsageACSendTo, - pstrUsageACReply, - pstrUsageACReplyAll, - pstrUsageACForwardMessage, - pstrUsageACSend, - pstrUsageACAttachFile, - pstrUsageACUpload, - pstrUsageACDownload, - pstrUsageACSetBorders, - pstrUsageACInsertRow, - pstrUsageACInsertColumn, - pstrUsageACInsertFile, - pstrUsageACInsertPicture, - pstrUsageACInsertObject, - pstrUsageACInsertSymbol, - pstrUsageACSaveAndClose, - pstrUsageACRename, - pstrUsageACMerge, - pstrUsageACSplit, - pstrUsageACDistributeHorizontaly, - pstrUsageACDistributeVerticaly -}; -const char * const ReportDescParserBase::digitTitles0[] PROGMEM = { - pstrUsageDigitizer, - pstrUsagePen, - pstrUsageLightPen, - pstrUsageTouchScreen, - pstrUsageTouchPad, - pstrUsageWhiteBoard, - pstrUsageCoordinateMeasuringMachine, - pstrUsage3DDigitizer, - pstrUsageStereoPlotter, - pstrUsageArticulatedArm, - pstrUsageArmature, - pstrUsageMultiplePointDigitizer, - pstrUsageFreeSpaceWand -}; -const char * const ReportDescParserBase::digitTitles1[] PROGMEM = { - pstrUsageStylus, - pstrUsagePuck, - pstrUsageFinger - -}; -const char * const ReportDescParserBase::digitTitles2[] PROGMEM = { - pstrUsageTipPressure, - pstrUsageBarrelPressure, - pstrUsageInRange, - pstrUsageTouch, - pstrUsageUntouch, - pstrUsageTap, - pstrUsageQuality, - pstrUsageDataValid, - pstrUsageTransducerIndex, - pstrUsageTabletFunctionKeys, - pstrUsageProgramChangeKeys, - pstrUsageBatteryStrength, - pstrUsageInvert, - pstrUsageXTilt, - pstrUsageYTilt, - pstrUsageAzimuth, - pstrUsageAltitude, - pstrUsageTwist, - pstrUsageTipSwitch, - pstrUsageSecondaryTipSwitch, - pstrUsageBarrelSwitch, - pstrUsageEraser, - pstrUsageTabletPick -}; -const char * const ReportDescParserBase::aplphanumTitles0[] PROGMEM = { - pstrUsageAlphanumericDisplay, - pstrUsageBitmappedDisplay -}; -const char * const ReportDescParserBase::aplphanumTitles1[] PROGMEM = { - pstrUsageDisplayAttributesReport, - pstrUsageASCIICharacterSet, - pstrUsageDataReadBack, - pstrUsageFontReadBack, - pstrUsageDisplayControlReport, - pstrUsageClearDisplay, - pstrUsageDisplayEnable, - pstrUsageScreenSaverDelay, - pstrUsageScreenSaverEnable, - pstrUsageVerticalScroll, - pstrUsageHorizontalScroll, - pstrUsageCharacterReport, - pstrUsageDisplayData, - pstrUsageDisplayStatus, - pstrUsageStatusNotReady, - pstrUsageStatusReady, - pstrUsageErrorNotALoadableCharacter, - pstrUsageErrorFotDataCanNotBeRead, - pstrUsageCursorPositionReport, - pstrUsageRow, - pstrUsageColumn, - pstrUsageRows, - pstrUsageColumns, - pstrUsageCursorPixelPosition, - pstrUsageCursorMode, - pstrUsageCursorEnable, - pstrUsageCursorBlink, - pstrUsageFontReport, - pstrUsageFontData, - pstrUsageCharacterWidth, - pstrUsageCharacterHeight, - pstrUsageCharacterSpacingHorizontal, - pstrUsageCharacterSpacingVertical, - pstrUsageUnicodeCharset, - pstrUsageFont7Segment, - pstrUsage7SegmentDirectMap, - pstrUsageFont14Segment, - pstrUsage14SegmentDirectMap, - pstrUsageDisplayBrightness, - pstrUsageDisplayContrast, - pstrUsageCharacterAttribute, - pstrUsageAttributeReadback, - pstrUsageAttributeData, - pstrUsageCharAttributeEnhance, - pstrUsageCharAttributeUnderline, - pstrUsageCharAttributeBlink -}; -const char * const ReportDescParserBase::aplphanumTitles2[] PROGMEM = { - pstrUsageBitmapSizeX, - pstrUsageBitmapSizeY, - pstrUsagePageReserved, - pstrUsageBitDepthFormat, - pstrUsageDisplayOrientation, - pstrUsagePaletteReport, - pstrUsagePaletteDataSize, - pstrUsagePaletteDataOffset, - pstrUsagePaletteData, - pstrUsageBlitReport, - pstrUsageBlitRectangleX1, - pstrUsageBlitRectangleY1, - pstrUsageBlitRectangleX2, - pstrUsageBlitRectangleY2, - pstrUsageBlitData, - pstrUsageSoftButton, - pstrUsageSoftButtonID, - pstrUsageSoftButtonSide, - pstrUsageSoftButtonOffset1, - pstrUsageSoftButtonOffset2, - pstrUsageSoftButtonReport -}; -const char * const ReportDescParserBase::medInstrTitles0[] PROGMEM = { - pstrUsageVCRAcquisition, - pstrUsageFreezeThaw, - pstrUsageClipStore, - pstrUsageUpdate, - pstrUsageNext, - pstrUsageSave, - pstrUsagePrint, - pstrUsageMicrophoneEnable -}; -const char * const ReportDescParserBase::medInstrTitles1[] PROGMEM = { - pstrUsageCine, - pstrUsageTransmitPower, - pstrUsageVolume, - pstrUsageFocus, - pstrUsageDepth -}; -const char * const ReportDescParserBase::medInstrTitles2[] PROGMEM = { - pstrUsageSoftStepPrimary, - pstrUsageSoftStepSecondary -}; -const char * const ReportDescParserBase::medInstrTitles3[] PROGMEM = { - pstrUsageZoomSelect, - pstrUsageZoomAdjust, - pstrUsageSpectralDopplerModeSelect, - pstrUsageSpectralDopplerModeAdjust, - pstrUsageColorDopplerModeSelect, - pstrUsageColorDopplerModeAdjust, - pstrUsageMotionModeSelect, - pstrUsageMotionModeAdjust, - pstrUsage2DModeSelect, - pstrUsage2DModeAdjust -}; -const char * const ReportDescParserBase::medInstrTitles4[] PROGMEM = { - pstrUsageSoftControlSelect, - pstrUsageSoftControlAdjust -}; - -void ReportDescParserBase::Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset) { - uint32_t cntdn = (uint32_t)len; - uint8_t *p = (uint8_t*)pbuf; - - - totalSize = 0; - - while(cntdn) { - //USB_HOST_SERIAL.println(""); - //PrintHex(offset + len - cntdn); - //USB_HOST_SERIAL.print(":"); - - ParseItem(&p, &cntdn); - - //if (ParseItem(&p, &cntdn)) - // return; - } - //USBTRACE2("Total:", totalSize); -} - -void ReportDescParserBase::PrintValue(uint8_t *p, uint8_t len) { - E_Notify(PSTR("("), 0x80); - for(; len; p++, len--) - PrintHex (*p, 0x80); - E_Notify(PSTR(")"), 0x80); -} - -void ReportDescParserBase::PrintByteValue(uint8_t data) { - E_Notify(PSTR("("), 0x80); - PrintHex (data, 0x80); - E_Notify(PSTR(")"), 0x80); -} - -void ReportDescParserBase::PrintItemTitle(uint8_t prefix) { - switch(prefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_GLOBAL | TAG_GLOBAL_PUSH): - E_Notify(PSTR("\r\nPush"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_POP): - E_Notify(PSTR("\r\nPop"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - E_Notify(PSTR("\r\nUsage Page"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN): - E_Notify(PSTR("\r\nLogical Min"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX): - E_Notify(PSTR("\r\nLogical Max"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN): - E_Notify(PSTR("\r\nPhysical Min"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX): - E_Notify(PSTR("\r\nPhysical Max"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP): - E_Notify(PSTR("\r\nUnit Exp"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_UNIT): - E_Notify(PSTR("\r\nUnit"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - E_Notify(PSTR("\r\nReport Size"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - E_Notify(PSTR("\r\nReport Count"), 0x80); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - E_Notify(PSTR("\r\nReport Id"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - E_Notify(PSTR("\r\nUsage"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - E_Notify(PSTR("\r\nUsage Min"), 0x80); - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - E_Notify(PSTR("\r\nUsage Max"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_COLLECTION): - E_Notify(PSTR("\r\nCollection"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION): - E_Notify(PSTR("\r\nEnd Collection"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - E_Notify(PSTR("\r\nInput"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - E_Notify(PSTR("\r\nOutput"), 0x80); - break; - case (TYPE_MAIN | TAG_MAIN_FEATURE): - E_Notify(PSTR("\r\nFeature"), 0x80); - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) -} - -uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint32_t *pcntdn) { - //uint8_t ret = enErrorSuccess; - //reinterpret_cast<>(varBuffer); - switch(itemParseState) { - case 0: - if(**pp == HID_LONG_ITEM_PREFIX) - USBTRACE("\r\nLONG\r\n"); - else { - uint8_t size = ((**pp) & DATA_SIZE_MASK); - - itemPrefix = (**pp); - itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size); - - PrintItemTitle(itemPrefix); - } - (*pp)++; - (*pcntdn)--; - itemSize--; - itemParseState = 1; - - if(!itemSize) - break; - - if(!pcntdn) - return enErrorIncomplete; - case 1: - //USBTRACE2("\r\niSz:",itemSize); - - theBuffer.valueSize = itemSize; - valParser.Initialize(&theBuffer); - itemParseState = 2; - case 2: - if(!valParser.Parse(pp, pcntdn)) - return enErrorIncomplete; - itemParseState = 3; - case 3: - { - uint8_t data = *((uint8_t*)varBuffer); - - switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if(pfUsage) { - if(theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); - pfUsage(*ui16); - } else - pfUsage(data); - } - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - rptSize = data; - PrintByteValue(data); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - rptCount = data; - PrintByteValue(data); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN): - case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN): - case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP): - case (TYPE_GLOBAL | TAG_GLOBAL_UNIT): - PrintValue(varBuffer, theBuffer.valueSize); - break; - case (TYPE_GLOBAL | TAG_GLOBAL_PUSH): - case (TYPE_GLOBAL | TAG_GLOBAL_POP): - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - SetUsagePage(data); - PrintUsagePage(data); - PrintByteValue(data); - break; - case (TYPE_MAIN | TAG_MAIN_COLLECTION): - case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION): - switch(data) { - case 0x00: - E_Notify(PSTR(" Physical"), 0x80); - break; - case 0x01: - E_Notify(PSTR(" Application"), 0x80); - break; - case 0x02: - E_Notify(PSTR(" Logical"), 0x80); - break; - case 0x03: - E_Notify(PSTR(" Report"), 0x80); - break; - case 0x04: - E_Notify(PSTR(" Named Array"), 0x80); - break; - case 0x05: - E_Notify(PSTR(" Usage Switch"), 0x80); - break; - case 0x06: - E_Notify(PSTR(" Usage Modifier"), 0x80); - break; - default: - E_Notify(PSTR(" Vendor Defined("), 0x80); - PrintHex (data, 0x80); - E_Notify(PSTR(")"), 0x80); - } - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - case (TYPE_MAIN | TAG_MAIN_FEATURE): - totalSize += (uint16_t)rptSize * (uint16_t)rptCount; - rptSize = 0; - rptCount = 0; - E_Notify(PSTR("("), 0x80); - PrintBin (data, 0x80); - E_Notify(PSTR(")"), 0x80); - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) - } - } // switch (itemParseState) - itemParseState = 0; - return enErrorSuccess; -} - -ReportDescParserBase::UsagePageFunc ReportDescParserBase::usagePageFunctions[] /*PROGMEM*/ = { - &ReportDescParserBase::PrintGenericDesktopPageUsage, - &ReportDescParserBase::PrintSimulationControlsPageUsage, - &ReportDescParserBase::PrintVRControlsPageUsage, - &ReportDescParserBase::PrintSportsControlsPageUsage, - &ReportDescParserBase::PrintGameControlsPageUsage, - &ReportDescParserBase::PrintGenericDeviceControlsPageUsage, - NULL, // Keyboard/Keypad - &ReportDescParserBase::PrintLEDPageUsage, - &ReportDescParserBase::PrintButtonPageUsage, - &ReportDescParserBase::PrintOrdinalPageUsage, - &ReportDescParserBase::PrintTelephonyPageUsage, - &ReportDescParserBase::PrintConsumerPageUsage, - &ReportDescParserBase::PrintDigitizerPageUsage, - NULL, // Reserved - NULL, // PID - NULL // Unicode -}; - -void ReportDescParserBase::SetUsagePage(uint16_t page) { - pfUsage = NULL; - - if(VALUE_BETWEEN(page, 0x00, 0x11)) - pfUsage = (usagePageFunctions[page - 1]); - - // Dead code... - // - // pfUsage = (UsagePageFunc)pgm_read_pointer(usagePageFunctions[page - 1]); - //else if (page > 0x7f && page < 0x84) - // E_Notify(pstrUsagePageMonitor); - //else if (page > 0x83 && page < 0x8c) - // E_Notify(pstrUsagePagePower); - //else if (page > 0x8b && page < 0x92) - // E_Notify((char*)pgm_read_pointer(&usagePageTitles1[page - 0x8c])); - //else if (page > 0xfeff && page <= 0xffff) - // E_Notify(pstrUsagePageVendorDefined); - // - else - switch(page) { - case 0x14: - pfUsage = &ReportDescParserBase::PrintAlphanumDisplayPageUsage; - break; - case 0x40: - pfUsage = &ReportDescParserBase::PrintMedicalInstrumentPageUsage; - break; - } -} - -void ReportDescParserBase::PrintUsagePage(uint16_t page) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0, 0x80) - else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1, 0x80) - else if(VALUE_BETWEEN(page, 0x7f, 0x84)) - E_Notify(pstrUsagePageMonitor, 0x80); - else if(VALUE_BETWEEN(page, 0x83, 0x8c)) - E_Notify(pstrUsagePagePower, 0x80); - else if(page > 0xfeff /* && page <= 0xffff */) - E_Notify(pstrUsagePageVendorDefined, 0x80); - else - switch(page) { - case 0x14: - E_Notify(pstrUsagePageAlphaNumericDisplay, 0x80); - break; - case 0x40: - E_Notify(pstrUsagePageMedicalInstruments, 0x80); - break; - default: - E_Notify(pstrUsagePageUndefined, 0x80); - } -} - -void ReportDescParserBase::PrintButtonPageUsage(uint16_t usage) { - E_Notify(pstrSpace, 0x80); - E_Notify(PSTR("Btn"), 0x80); - PrintHex (usage, 0x80); - E_Notify(PSTR("\r\n"), 0x80); - //USB_HOST_SERIAL.print(usage, HEX); -} - -void ReportDescParserBase::PrintOrdinalPageUsage(uint16_t usage) { - E_Notify(pstrSpace, 0x80); - E_Notify(PSTR("Inst"), 0x80); - // Sorry, HEX for now... - PrintHex (usage, 0x80); - E_Notify(PSTR("\r\n"), 0x80); - //USB_HOST_SERIAL.print(usage, DEC); -} - -void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0, 0x80) - else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1, 0x80) - else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2, 0x80) - else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3, 0x80) - else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1, 0x80) - else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0, 0x80) - else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1, 0x80) - else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1, 0x80) - else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2, 0x80) - else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3, 0x80) - else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4, 0x80) - else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1, 0x80) - else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2, 0x80) - else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3, 0x80) - else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4, 0x80) - else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5, 0x80) - else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6, 0x80) - else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7, 0x80) - else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8, 0x80) - else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9, 0x80) - else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA, 0x80) - else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB, 0x80) - else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC, 0x80) - else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD, 0x80) - else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1, 0x80) - else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0, 0x80) - else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1, 0x80) - else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) { - const char * const * w; - E_Notify(pstrSpace, 0x80); - - if(usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80); - else if(usage == 0x70) - E_Notify(pstrUsageDepthGainCompensation, 0x80); - else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0, 0x80) - else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1, 0x80) - else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2, 0x80) - else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3, 0x80) - else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4, 0x80) - else E_Notify(pstrUsagePageUndefined, 0x80); -} - -uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint32_t *pcntdn) { - //uint8_t ret = enErrorSuccess; - - switch(itemParseState) { - case 0: - if(**pp == HID_LONG_ITEM_PREFIX) - USBTRACE("\r\nLONG\r\n"); - else { - uint8_t size = ((**pp) & DATA_SIZE_MASK); - itemPrefix = (**pp); - itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size); - } - (*pp)++; - (*pcntdn)--; - itemSize--; - itemParseState = 1; - - if(!itemSize) - break; - - if(!pcntdn) - return enErrorIncomplete; - case 1: - theBuffer.valueSize = itemSize; - valParser.Initialize(&theBuffer); - itemParseState = 2; - case 2: - if(!valParser.Parse(pp, pcntdn)) - return enErrorIncomplete; - itemParseState = 3; - case 3: - { - uint8_t data = *((uint8_t*)varBuffer); - - switch(itemPrefix & (TYPE_MASK | TAG_MASK)) { - case (TYPE_LOCAL | TAG_LOCAL_USAGE): - if(pfUsage) { - if(theBuffer.valueSize > 1) { - uint16_t* ui16 = reinterpret_cast(varBuffer); - pfUsage(*ui16); - } else - pfUsage(data); - } - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE): - rptSize = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT): - rptCount = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID): - rptId = data; - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN): - useMin = data; - break; - case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX): - useMax = data; - break; - case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE): - SetUsagePage(data); - break; - case (TYPE_MAIN | TAG_MAIN_OUTPUT): - case (TYPE_MAIN | TAG_MAIN_FEATURE): - rptSize = 0; - rptCount = 0; - useMin = 0; - useMax = 0; - break; - case (TYPE_MAIN | TAG_MAIN_INPUT): - OnInputItem(data); - - totalSize += (uint16_t)rptSize * (uint16_t)rptCount; - - rptSize = 0; - rptCount = 0; - useMin = 0; - useMax = 0; - break; - } // switch (**pp & (TYPE_MASK | TAG_MASK)) - } - } // switch (itemParseState) - itemParseState = 0; - return enErrorSuccess; -} - -void ReportDescParser2::OnInputItem(uint8_t itm) { - uint8_t byte_offset = (totalSize >> 3); // calculate offset to the next unhandled byte i = (int)(totalCount / 8); - uint32_t tmp = (byte_offset << 3); - uint8_t bit_offset = totalSize - tmp; // number of bits in the current byte already handled - uint8_t *p = pBuf + byte_offset; // current byte pointer - - if(bit_offset) - *p >>= bit_offset; - - uint8_t usage = useMin; - - bool print_usemin_usemax = ((useMin < useMax) && ((itm & 3) == 2) && pfUsage) ? true : false; - - uint8_t bits_of_byte = 8; - - // for each field in field array defined by rptCount - for(uint8_t field = 0; field < rptCount; field++, usage++) { - - union { - uint8_t bResult[4]; - uint16_t wResult[2]; - uint32_t dwResult; - } result; - - result.dwResult = 0; - uint8_t mask = 0; - - if(print_usemin_usemax) - pfUsage(usage); - - // bits_left - number of bits in the field(array of fields, depending on Report Count) left to process - // bits_of_byte - number of bits in current byte left to process - // bits_to_copy - number of bits to copy to result buffer - - // for each bit in a field - for(uint8_t bits_left = rptSize, bits_to_copy = 0; bits_left; - bits_left -= bits_to_copy) { - bits_to_copy = (bits_left > bits_of_byte) ? bits_of_byte : bits_left; - - result.dwResult <<= bits_to_copy; // Result buffer is shifted by the number of bits to be copied into it - - uint8_t val = *p; - - val >>= (8 - bits_of_byte); // Shift by the number of bits already processed - - mask = 0; - - for(uint8_t j = bits_to_copy; j; j--) { - mask <<= 1; - mask |= 1; - } - - result.bResult[0] = (result.bResult[0] | (val & mask)); - - bits_of_byte -= bits_to_copy; - - if(bits_of_byte < 1) { - bits_of_byte = 8; - p++; - } - } - PrintByteValue(result.dwResult); - } - E_Notify(PSTR("\r\n"), 0x80); -} - -void UniversalReportParser::Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf) { - ReportDescParser2 prs(len, buf); - - uint8_t ret = hid->GetReportDescr(0, &prs); - - if(ret) - ErrorMessage (PSTR("GetReportDescr-2"), ret); -} diff --git a/test/libraries/USBHost/src/hidescriptorparser.h b/test/libraries/USBHost/src/hidescriptorparser.h deleted file mode 100644 index 65803df5..00000000 --- a/test/libraries/USBHost/src/hidescriptorparser.h +++ /dev/null @@ -1,173 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(__HIDDESCRIPTORPARSER_H__) -#define __HIDDESCRIPTORPARSER_H__ - -#include "hid.h" - -class ReportDescParserBase : public USBReadParser { -public: - typedef void (*UsagePageFunc)(uint16_t usage); - - static void PrintGenericDesktopPageUsage(uint16_t usage); - static void PrintSimulationControlsPageUsage(uint16_t usage); - static void PrintVRControlsPageUsage(uint16_t usage); - static void PrintSportsControlsPageUsage(uint16_t usage); - static void PrintGameControlsPageUsage(uint16_t usage); - static void PrintGenericDeviceControlsPageUsage(uint16_t usage); - static void PrintLEDPageUsage(uint16_t usage); - static void PrintButtonPageUsage(uint16_t usage); - static void PrintOrdinalPageUsage(uint16_t usage); - static void PrintTelephonyPageUsage(uint16_t usage); - static void PrintConsumerPageUsage(uint16_t usage); - static void PrintDigitizerPageUsage(uint16_t usage); - static void PrintAlphanumDisplayPageUsage(uint16_t usage); - static void PrintMedicalInstrumentPageUsage(uint16_t usage); - - static void PrintValue(uint8_t *p, uint8_t len); - static void PrintByteValue(uint8_t data); - - static void PrintItemTitle(uint8_t prefix); - - static const char * const usagePageTitles0[]; - static const char * const usagePageTitles1[]; - static const char * const genDesktopTitles0[]; - static const char * const genDesktopTitles1[]; - static const char * const genDesktopTitles2[]; - static const char * const genDesktopTitles3[]; - static const char * const genDesktopTitles4[]; - static const char * const simuTitles0[]; - static const char * const simuTitles1[]; - static const char * const simuTitles2[]; - static const char * const vrTitles0[]; - static const char * const vrTitles1[]; - static const char * const sportsCtrlTitles0[]; - static const char * const sportsCtrlTitles1[]; - static const char * const sportsCtrlTitles2[]; - static const char * const gameTitles0[]; - static const char * const gameTitles1[]; - static const char * const genDevCtrlTitles[]; - static const char * const ledTitles[]; - static const char * const telTitles0[]; - static const char * const telTitles1[]; - static const char * const telTitles2[]; - static const char * const telTitles3[]; - static const char * const telTitles4[]; - static const char * const telTitles5[]; - static const char * const consTitles0[]; - static const char * const consTitles1[]; - static const char * const consTitles2[]; - static const char * const consTitles3[]; - static const char * const consTitles4[]; - static const char * const consTitles5[]; - static const char * const consTitles6[]; - static const char * const consTitles7[]; - static const char * const consTitles8[]; - static const char * const consTitles9[]; - static const char * const consTitlesA[]; - static const char * const consTitlesB[]; - static const char * const consTitlesC[]; - static const char * const consTitlesD[]; - static const char * const consTitlesE[]; - static const char * const digitTitles0[]; - static const char * const digitTitles1[]; - static const char * const digitTitles2[]; - static const char * const aplphanumTitles0[]; - static const char * const aplphanumTitles1[]; - static const char * const aplphanumTitles2[]; - static const char * const medInstrTitles0[]; - static const char * const medInstrTitles1[]; - static const char * const medInstrTitles2[]; - static const char * const medInstrTitles3[]; - static const char * const medInstrTitles4[]; - -protected: - static UsagePageFunc usagePageFunctions[]; - - MultiValueBuffer theBuffer; - MultiByteValueParser valParser; - ByteSkipper theSkipper; - uint8_t varBuffer[sizeof (USB_CONFIGURATION_DESCRIPTOR)]; - - uint8_t itemParseState; // Item parser state variable - uint8_t itemSize; // Item size - uint8_t itemPrefix; // Item prefix (first byte) - uint8_t rptSize; // Report Size - uint8_t rptCount; // Report Count - - uint16_t totalSize; // Report size in bits - - virtual uint8_t ParseItem(uint8_t **pp, uint32_t *pcntdn); - - UsagePageFunc pfUsage; - - static void PrintUsagePage(uint16_t page); - void SetUsagePage(uint16_t page); - -public: - - ReportDescParserBase() : - itemParseState(0), - itemSize(0), - itemPrefix(0), - rptSize(0), - rptCount(0), - pfUsage(NULL) { - theBuffer.pValue = varBuffer; - valParser.Initialize(&theBuffer); - theSkipper.Initialize(&theBuffer); - }; - - virtual void Parse(const uint32_t len, const uint8_t *pbuf, const uint32_t &offset); - - enum { - enErrorSuccess = 0 - , enErrorIncomplete // value or record is partialy read in buffer - , enErrorBufferTooSmall - }; -}; - -class ReportDescParser : public ReportDescParserBase { -}; - -class ReportDescParser2 : public ReportDescParserBase { - uint8_t rptId; // Report ID - uint8_t useMin; // Usage Minimum - uint8_t useMax; // Usage Maximum - uint8_t fieldCount; // Number of field being currently processed - - void OnInputItem(uint8_t itm); // Method which is called every time Input item is found - - uint8_t *pBuf; // Report buffer pointer - uint8_t bLen; // Report length - -protected: - virtual uint8_t ParseItem(uint8_t **pp, uint32_t *pcntdn); - -public: - - ReportDescParser2(uint16_t len, uint8_t *pbuf) : - ReportDescParserBase(), rptId(0), useMin(0), useMax(0), fieldCount(0), pBuf(pbuf), bLen(len) { - }; -}; - -class UniversalReportParser : public HIDReportParser { -public: - virtual void Parse(HID *hid, uint32_t is_rpt_id, uint32_t len, uint8_t *buf); -}; - -#endif // __HIDDESCRIPTORPARSER_H__ diff --git a/test/libraries/USBHost/src/hiduniversal.cpp b/test/libraries/USBHost/src/hiduniversal.cpp deleted file mode 100644 index ac5309b8..00000000 --- a/test/libraries/USBHost/src/hiduniversal.cpp +++ /dev/null @@ -1,421 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "Arduino.h" -#include "hiduniversal.h" - -HIDUniversal::HIDUniversal(USBHost *p) : -HID(p), -qNextPollTime(0), -pollInterval(0), -bPollEnable(false), -bHasReportId(false) { - Initialize(); - - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -uint16_t HIDUniversal::GetHidClassDescrLen(uint8_t type, uint8_t num) { - for(uint8_t i = 0, n = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { - if(descrInfo[i].bDescrType == type) { - if(n == num) - return descrInfo[i].wDescriptorLength; - n++; - } - } - return 0; -} - -void HIDUniversal::Initialize() { - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - rptParsers[i].rptId = 0; - rptParsers[i].rptParser = NULL; - } - for(uint8_t i = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) { - descrInfo[i].bDescrType = 0; - descrInfo[i].wDescriptorLength = 0; - } - for(uint8_t i = 0; i < maxHidInterfaces; i++) { - hidInterfaces[i].bmInterface = 0; - hidInterfaces[i].bmProtocol = 0; - - for(uint8_t j = 0; j < maxEpPerInterface; j++) - hidInterfaces[i].epIndex[j] = 0; - } - for(uint8_t i = 0; i < totalEndpoints; i++) { - epInfo[i].epAddr = 0; - epInfo[i].maxPktSize = (i) ? 0 : 8; - epInfo[i].epAttribs = 0; - epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER; - } - bNumEP = 1; - bNumIface = 0; - bConfNum = 0; - pollInterval = 0; - - ZeroMemory(constBuffLen, prevBuf); -} - -uint32_t HIDUniversal::SetReportParser(uint32_t id, HIDReportParser *prs) { - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if(rptParsers[i].rptId == 0 && rptParsers[i].rptParser == NULL) { - rptParsers[i].rptId = id; - rptParsers[i].rptParser = prs; - return true; - } - } - return false; -} - -HIDReportParser* HIDUniversal::GetReportParser(uint32_t id) { - if(!bHasReportId) - return ((rptParsers[0].rptParser) ? rptParsers[0].rptParser : NULL); - - for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) { - if(rptParsers[i].rptId == id) - return rptParsers[i].rptParser; - } - return NULL; -} - -uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) { - const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR); - - uint8_t buf[constBufSize]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - uint8_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint8_t len = 0; - - uint8_t num_of_conf; // number of configurations - //uint8_t num_of_intf; // number of interfaces - - AddressPool &addrPool = pUsb->GetAddressPool(); - - USBTRACE("HU Init\r\n"); - - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) { - USBTRACE("epinfo\r\n"); - return USB_ERROR_EPINFO_IS_NULL; - } - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - - if(!rcode) - len = (buf[0] > constBufSize) ? constBufSize : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - - goto FailGetDevDescr; - } - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, false, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device - rcode = pUsb->setAddr(0, 0, bAddress); - - if(rcode) { - p->lowspeed = false; - addrPool.FreeAddress(bAddress); - bAddress = 0; - USBTRACE2("setAddr:", rcode); - return rcode; - } - - //delay(2); //per USB 2.0 sect.9.2.6.3 - - USBTRACE2("Addr:", bAddress); - - p->lowspeed = false; - - p = addrPool.GetUsbDevicePtr(bAddress); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - p->lowspeed = lowspeed; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - VID = udd->idVendor; // Can be used by classes that inherits this class to check the VID and PID of the connected device - PID = udd->idProduct; - - num_of_conf = udd->bNumConfigurations; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); - - if(rcode) - goto FailSetDevTblEntry; - - USBTRACE2("NC:", num_of_conf); - - for(uint8_t i = 0; i < num_of_conf; i++) { - //HexDumper HexDump; - ConfigDescParser confDescrParser(this); - - //rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump); - rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser); - - if(rcode) - goto FailGetConfDescr; - - if(bNumEP > 1) - break; - } // for - - if(bNumEP < 2) - return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo); - - USBTRACE2("Cnf:", bConfNum); - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, bConfNum); - - if(rcode) - goto FailSetConfDescr; - - for(uint8_t i = 0; i < bNumIface; i++) { - if(hidInterfaces[i].epIndex[epInterruptInIndex] == 0) - continue; - - rcode = SetIdle(hidInterfaces[i].bmInterface, 0, 0); - - if(rcode)/* && rcode != hrSTALL) */ - goto FailSetIdle; - } - - USBTRACE("HU configured\r\n"); - - OnInitSuccessful(); - - bPollEnable = true; - return 0; - -FailGetDevDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetDevDescr(); - goto Fail; -#endif - -FailSetDevTblEntry: -#ifdef DEBUG_USB_HOST - NotifyFailSetDevTblEntry(); - goto Fail; -#endif - -FailGetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailGetConfDescr(); - goto Fail; -#endif - -FailSetConfDescr: -#ifdef DEBUG_USB_HOST - NotifyFailSetConfDescr(); - goto Fail; -#endif - - -FailSetIdle: -#ifdef DEBUG_USB_HOST - USBTRACE("SetIdle:"); -#endif - -#ifdef DEBUG_USB_HOST -Fail: - NotifyFail(rcode); -#endif - Release(); - return rcode; -} - -HIDUniversal::HIDInterface* HIDUniversal::FindInterface(uint8_t iface, uint8_t alt, uint8_t proto) { - for(uint8_t i = 0; i < bNumIface && i < maxHidInterfaces; i++) - if(hidInterfaces[i].bmInterface == iface && hidInterfaces[i].bmAltSet == alt - && hidInterfaces[i].bmProtocol == proto) - return hidInterfaces + i; - return NULL; -} - -void HIDUniversal::EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) { - // If the first configuration satisfies, the others are not concidered. - if(bNumEP > 1 && conf != bConfNum) - return; - - //ErrorMessage(PSTR("\r\nConf.Val"), conf); - //ErrorMessage(PSTR("Iface Num"), iface); - //ErrorMessage(PSTR("Alt.Set"), alt); - - bConfNum = conf; - - uint8_t index = 0; - HIDInterface *piface = FindInterface(iface, alt, proto); - - // Fill in interface structure in case of new interface - if(!piface) { - piface = hidInterfaces + bNumIface; - piface->bmInterface = iface; - piface->bmAltSet = alt; - piface->bmProtocol = proto; - bNumIface++; - } - - if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) - index = epInterruptInIndex; - else - index = epInterruptOutIndex; - - if(index) { - // Fill in the endpoint info structure - epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F); - epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize; - epInfo[bNumEP].epAttribs = 0; - epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT; - - // Fill in the endpoint index list - piface->epIndex[index] = bNumEP; //(pep->bEndpointAddress & 0x0F); - - if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints - pollInterval = pep->bInterval; - - bNumEP++; - } - //PrintEndpointDescriptor(pep); -} - -uint32_t HIDUniversal::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - bNumEP = 1; - bAddress = 0; - qNextPollTime = 0; - bPollEnable = false; - return 0; -} - -bool HIDUniversal::BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2) { - for(uint8_t i = 0; i < len; i++) - if(buf1[i] != buf2[i]) - return false; - return true; -} - -void HIDUniversal::ZeroMemory(uint8_t len, uint8_t *buf) { - for(uint8_t i = 0; i < len; i++) - buf[i] = 0; -} - -void HIDUniversal::SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest) { - for(uint8_t i = 0; i < len; i++) - dest[i] = src[i]; -} - -uint32_t HIDUniversal::Poll() { - uint32_t rcode = 0; - - if(!bPollEnable) - return 0; - - if((long)(millis() - qNextPollTime) >= 0L) { - qNextPollTime = millis() + pollInterval; - - uint8_t buf[constBuffLen]; - - for(uint8_t i = 0; i < bNumIface; i++) { - uint8_t index = hidInterfaces[i].epIndex[epInterruptInIndex]; - uint16_t read = (uint8_t)epInfo[index].maxPktSize; - - ZeroMemory(constBuffLen, buf); - - uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[index].epAddr, (uint8_t*)&read, buf); - - if(rcode) { - if(rcode != USB_ERRORFLOW/*hrNAK*/) - USBTRACE3("(hiduniversal.h) Poll:", rcode, 0x81); - return rcode; - } - - if(read > constBuffLen) - read = constBuffLen; - - bool identical = BuffersIdentical(read, buf, prevBuf); - - SaveBuffer(read, buf, prevBuf); - - if(identical) - return 0; -#if 0 - Notify(PSTR("\r\nBuf: "), 0x80); - - for(uint8_t i = 0; i < read; i++) { - D_PrintHex (buf[i], 0x80); - Notify(PSTR(" "), 0x80); - } - - Notify(PSTR("\r\n"), 0x80); -#endif - ParseHIDData(this, bHasReportId, (uint8_t)read, buf); - - HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0)); - - if(prs) - prs->Parse(this, bHasReportId, (uint8_t)read, buf); - } - } - return rcode; -} diff --git a/test/libraries/USBHost/src/hiduniversal.h b/test/libraries/USBHost/src/hiduniversal.h deleted file mode 100644 index 9c033f0a..00000000 --- a/test/libraries/USBHost/src/hiduniversal.h +++ /dev/null @@ -1,105 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(__HIDUNIVERSAL_H__) -#define __HIDUNIVERSAL_H__ - -#include "hid.h" -//#include "hidescriptorparser.h" - -class HIDUniversal : public HID { - - struct ReportParser { - uint8_t rptId; - HIDReportParser *rptParser; - } rptParsers[MAX_REPORT_PARSERS]; - - // HID class specific descriptor type and length info obtained from HID descriptor - HID_CLASS_DESCRIPTOR_LEN_AND_TYPE descrInfo[HID_MAX_HID_CLASS_DESCRIPTORS]; - - // Returns HID class specific descriptor length by its type and order number - uint16_t GetHidClassDescrLen(uint8_t type, uint8_t num); - - struct HIDInterface { - struct { - uint8_t bmInterface : 3; - uint8_t bmAltSet : 3; - uint8_t bmProtocol : 2; - }; - uint8_t epIndex[maxEpPerInterface]; - }; - - uint8_t bConfNum; // configuration number - uint8_t bNumIface; // number of interfaces in the configuration - uint8_t bNumEP; // total number of EP in the configuration - uint32_t qNextPollTime; // next poll time - uint8_t pollInterval; - bool bPollEnable; // poll enable flag - - static const uint16_t constBuffLen = 64; // event buffer length - uint8_t prevBuf[constBuffLen]; // previous event buffer - - void Initialize(); - HIDInterface* FindInterface(uint8_t iface, uint8_t alt, uint8_t proto); - - void ZeroMemory(uint8_t len, uint8_t *buf); - bool BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2); - void SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest); - -protected: - EpInfo epInfo[totalEndpoints]; - HIDInterface hidInterfaces[maxHidInterfaces]; - - bool bHasReportId; - - uint16_t PID, VID; // PID and VID of connected device - - // HID implementation - virtual HIDReportParser* GetReportParser(uint32_t id); - - virtual uint32_t OnInitSuccessful() { - return 0; - }; - - virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) { - return; - }; - -public: - HIDUniversal(USBHost *p); - - // HID implementation - virtual uint32_t SetReportParser(uint32_t id, HIDReportParser *prs); - - // USBDeviceConfig implementation - virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t isReady() { - return bPollEnable; - }; - - // UsbConfigXtracter implementation - virtual void EndpointXtract(uint32_t conf, uint32_t iface, uint32_t alt, uint32_t proto, const USB_ENDPOINT_DESCRIPTOR *ep); -}; - -#endif // __HIDUNIVERSAL_H__ diff --git a/test/libraries/USBHost/src/hidusagestr.h b/test/libraries/USBHost/src/hidusagestr.h deleted file mode 100644 index 71e53787..00000000 --- a/test/libraries/USBHost/src/hidusagestr.h +++ /dev/null @@ -1,977 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#if !defined( __HIDUSAGESTR_H__) -#define __HIDUSAGESTR_H__ - -#include "Usb.h" - -const char pstrSpace [] PROGMEM = " "; -const char pstrCRLF [] PROGMEM = "\r\n"; -const char pstrSingleTab [] PROGMEM = "\t"; -const char pstrDoubleTab [] PROGMEM = "\t\t"; -const char pstrTripleTab [] PROGMEM = "\t\t\t"; - -// Usage Page String Titles -const char pstrUsagePageUndefined [] PROGMEM = "Undef"; -const char pstrUsagePageGenericDesktopControls [] PROGMEM = "Gen Desktop Ctrls"; -const char pstrUsagePageSimulationControls [] PROGMEM = "Simu Ctrls"; -const char pstrUsagePageVRControls [] PROGMEM = "VR Ctrls"; -const char pstrUsagePageSportControls [] PROGMEM = "Sport Ctrls"; -const char pstrUsagePageGameControls [] PROGMEM = "Game Ctrls"; -const char pstrUsagePageGenericDeviceControls [] PROGMEM = "Gen Dev Ctrls"; -const char pstrUsagePageKeyboardKeypad [] PROGMEM = "Kbrd/Keypad"; -const char pstrUsagePageLEDs [] PROGMEM = "LEDs"; -const char pstrUsagePageButton [] PROGMEM = "Button"; -const char pstrUsagePageOrdinal [] PROGMEM = "Ordinal"; -const char pstrUsagePageTelephone [] PROGMEM = "Tel"; -const char pstrUsagePageConsumer [] PROGMEM = "Consumer"; -const char pstrUsagePageDigitizer [] PROGMEM = "Digitizer"; -const char pstrUsagePagePID [] PROGMEM = "PID"; -const char pstrUsagePageUnicode [] PROGMEM = "Unicode"; -const char pstrUsagePageAlphaNumericDisplay [] PROGMEM = "Alpha Num Disp"; -const char pstrUsagePageMedicalInstruments [] PROGMEM = "Medical Instr"; -const char pstrUsagePageMonitor [] PROGMEM = "Monitor"; -const char pstrUsagePagePower [] PROGMEM = "Power"; -const char pstrUsagePageBarCodeScanner [] PROGMEM = "Bar Code Scan"; -const char pstrUsagePageScale [] PROGMEM = "Scale"; -const char pstrUsagePageMSRDevices [] PROGMEM = "Magn Stripe Read Dev"; -const char pstrUsagePagePointOfSale [] PROGMEM = "POS"; -const char pstrUsagePageCameraControl [] PROGMEM = "Cam Ctrl"; -const char pstrUsagePageArcade [] PROGMEM = "Arcade"; -const char pstrUsagePageReserved [] PROGMEM = "Reserved"; -const char pstrUsagePageVendorDefined [] PROGMEM = "Vendor Def"; - -// Generic Desktop Controls Page -const char pstrUsagePointer [] PROGMEM = "Pointer"; -const char pstrUsageMouse [] PROGMEM = "Mouse"; -const char pstrUsageJoystick [] PROGMEM = "Joystick"; -const char pstrUsageGamePad [] PROGMEM = "Game Pad"; -const char pstrUsageKeyboard [] PROGMEM = "Kbrd"; -const char pstrUsageKeypad [] PROGMEM = "Keypad"; -const char pstrUsageMultiAxisController [] PROGMEM = "Multi-axis Ctrl"; -const char pstrUsageTabletPCSystemControls [] PROGMEM = "Tablet PC Sys Ctrls"; -const char pstrUsageX [] PROGMEM = "X"; -const char pstrUsageY [] PROGMEM = "Y"; -const char pstrUsageZ [] PROGMEM = "Z"; -const char pstrUsageRx [] PROGMEM = "Rx"; -const char pstrUsageRy [] PROGMEM = "Ry"; -const char pstrUsageRz [] PROGMEM = "Rz"; -const char pstrUsageSlider [] PROGMEM = "Slider"; -const char pstrUsageDial [] PROGMEM = "Dial"; -const char pstrUsageWheel [] PROGMEM = "Wheel"; -const char pstrUsageHatSwitch [] PROGMEM = "Hat Switch"; -const char pstrUsageCountedBuffer [] PROGMEM = "Counted Buf"; -const char pstrUsageByteCount [] PROGMEM = "Byte Count"; -const char pstrUsageMotionWakeup [] PROGMEM = "Motion Wakeup"; -const char pstrUsageStart [] PROGMEM = "Start"; -const char pstrUsageSelect [] PROGMEM = "Sel"; -const char pstrUsageVx [] PROGMEM = "Vx"; -const char pstrUsageVy [] PROGMEM = "Vy"; -const char pstrUsageVz [] PROGMEM = "Vz"; -const char pstrUsageVbrx [] PROGMEM = "Vbrx"; -const char pstrUsageVbry [] PROGMEM = "Vbry"; -const char pstrUsageVbrz [] PROGMEM = "Vbrz"; -const char pstrUsageVno [] PROGMEM = "Vno"; -const char pstrUsageFeatureNotification [] PROGMEM = "Feature Notif"; -const char pstrUsageResolutionMultiplier [] PROGMEM = "Res Mult"; -const char pstrUsageSystemControl [] PROGMEM = "Sys Ctrl"; -const char pstrUsageSystemPowerDown [] PROGMEM = "Sys Pwr Down"; -const char pstrUsageSystemSleep [] PROGMEM = "Sys Sleep"; -const char pstrUsageSystemWakeup [] PROGMEM = "Sys Wakeup"; -const char pstrUsageSystemContextMenu [] PROGMEM = "Sys Context Menu"; -const char pstrUsageSystemMainMenu [] PROGMEM = "Sys Main Menu"; -const char pstrUsageSystemAppMenu [] PROGMEM = "Sys App Menu"; -const char pstrUsageSystemMenuHelp [] PROGMEM = "Sys Menu Help"; -const char pstrUsageSystemMenuExit [] PROGMEM = "Sys Menu Exit"; -const char pstrUsageSystemMenuSelect [] PROGMEM = "Sys Menu Select"; -const char pstrUsageSystemMenuRight [] PROGMEM = "Sys Menu Right"; -const char pstrUsageSystemMenuLeft [] PROGMEM = "Sys Menu Left"; -const char pstrUsageSystemMenuUp [] PROGMEM = "Sys Menu Up"; -const char pstrUsageSystemMenuDown [] PROGMEM = "Sys Menu Down"; -const char pstrUsageSystemColdRestart [] PROGMEM = "Sys Cold Restart"; -const char pstrUsageSystemWarmRestart [] PROGMEM = "Sys Warm Restart"; -const char pstrUsageDPadUp [] PROGMEM = "D-pad Up"; -const char pstrUsageDPadDown [] PROGMEM = "D-pad Down"; -const char pstrUsageDPadRight [] PROGMEM = "D-pad Right"; -const char pstrUsageDPadLeft [] PROGMEM = "D-pad Left"; -const char pstrUsageSystemDock [] PROGMEM = "Sys Dock"; -const char pstrUsageSystemUndock [] PROGMEM = "Sys Undock"; -const char pstrUsageSystemSetup [] PROGMEM = "Sys Setup"; -const char pstrUsageSystemBreak [] PROGMEM = "Sys Break"; -const char pstrUsageSystemDebuggerBreak [] PROGMEM = "Sys Dbg Brk"; -const char pstrUsageApplicationBreak [] PROGMEM = "App Break"; -const char pstrUsageApplicationDebuggerBreak [] PROGMEM = "App Dbg Brk"; -const char pstrUsageSystemSpeakerMute [] PROGMEM = "Sys Spk Mute"; -const char pstrUsageSystemHibernate [] PROGMEM = "Sys Hiber"; -const char pstrUsageSystemDisplayInvert [] PROGMEM = "Sys Disp Inv"; -const char pstrUsageSystemDisplayInternal [] PROGMEM = "Sys Disp Int"; -const char pstrUsageSystemDisplayExternal [] PROGMEM = "Sys Disp Ext"; -const char pstrUsageSystemDisplayBoth [] PROGMEM = "Sys Disp Both"; -const char pstrUsageSystemDisplayDual [] PROGMEM = "Sys Disp Dual"; -const char pstrUsageSystemDisplayToggleIntExt [] PROGMEM = "Sys Disp Tgl Int/Ext"; -const char pstrUsageSystemDisplaySwapPriSec [] PROGMEM = "Sys Disp Swap Pri/Sec"; -const char pstrUsageSystemDisplayLCDAutoscale [] PROGMEM = "Sys Disp LCD Autoscale"; - -// Simulation Controls Page -const char pstrUsageFlightSimulationDevice [] PROGMEM = "Flight Simu Dev"; -const char pstrUsageAutomobileSimulationDevice [] PROGMEM = "Auto Simu Dev"; -const char pstrUsageTankSimulationDevice [] PROGMEM = "Tank Simu Dev"; -const char pstrUsageSpaceshipSimulationDevice [] PROGMEM = "Space Simu Dev"; -const char pstrUsageSubmarineSimulationDevice [] PROGMEM = "Subm Simu Dev"; -const char pstrUsageSailingSimulationDevice [] PROGMEM = "Sail Simu Dev"; -const char pstrUsageMotocicleSimulationDevice [] PROGMEM = "Moto Simu Dev"; -const char pstrUsageSportsSimulationDevice [] PROGMEM = "Sport Simu Dev"; -const char pstrUsageAirplaneSimulationDevice [] PROGMEM = "Airp Simu Dev"; -const char pstrUsageHelicopterSimulationDevice [] PROGMEM = "Heli Simu Dev"; -const char pstrUsageMagicCarpetSimulationDevice [] PROGMEM = "Magic Carpet Simu Dev"; -const char pstrUsageBicycleSimulationDevice [] PROGMEM = "Bike Simu Dev"; -const char pstrUsageFlightControlStick [] PROGMEM = "Flight Ctrl Stick"; -const char pstrUsageFlightStick [] PROGMEM = "Flight Stick"; -const char pstrUsageCyclicControl [] PROGMEM = "Cyclic Ctrl"; -const char pstrUsageCyclicTrim [] PROGMEM = "Cyclic Trim"; -const char pstrUsageFlightYoke [] PROGMEM = "Flight Yoke"; -const char pstrUsageTrackControl [] PROGMEM = "Track Ctrl"; -const char pstrUsageAileron [] PROGMEM = "Aileron"; -const char pstrUsageAileronTrim [] PROGMEM = "Aileron Trim"; -const char pstrUsageAntiTorqueControl [] PROGMEM = "Anti-Torque Ctrl"; -const char pstrUsageAutopilotEnable [] PROGMEM = "Autopilot Enable"; -const char pstrUsageChaffRelease [] PROGMEM = "Chaff Release"; -const char pstrUsageCollectiveControl [] PROGMEM = "Collective Ctrl"; -const char pstrUsageDiveBrake [] PROGMEM = "Dive Brake"; -const char pstrUsageElectronicCountermeasures [] PROGMEM = "El Countermeasures"; -const char pstrUsageElevator [] PROGMEM = "Elevator"; -const char pstrUsageElevatorTrim [] PROGMEM = "Elevator Trim"; -const char pstrUsageRudder [] PROGMEM = "Rudder"; -const char pstrUsageThrottle [] PROGMEM = "Throttle"; -const char pstrUsageFlightCommunications [] PROGMEM = "Flight Comm"; -const char pstrUsageFlareRelease [] PROGMEM = "Flare Release"; -const char pstrUsageLandingGear [] PROGMEM = "Landing Gear"; -const char pstrUsageToeBrake [] PROGMEM = "Toe Brake"; -const char pstrUsageTrigger [] PROGMEM = "Trigger"; -const char pstrUsageWeaponsArm [] PROGMEM = "Weapons Arm"; -const char pstrUsageWeaponsSelect [] PROGMEM = "Weapons Sel"; -const char pstrUsageWingFlaps [] PROGMEM = "Wing Flaps"; -const char pstrUsageAccelerator [] PROGMEM = "Accel"; -const char pstrUsageBrake [] PROGMEM = "Brake"; -const char pstrUsageClutch [] PROGMEM = "Clutch"; -const char pstrUsageShifter [] PROGMEM = "Shifter"; -const char pstrUsageSteering [] PROGMEM = "Steering"; -const char pstrUsageTurretDirection [] PROGMEM = "Turret Dir"; -const char pstrUsageBarrelElevation [] PROGMEM = "Barrel Ele"; -const char pstrUsageDivePlane [] PROGMEM = "Dive Plane"; -const char pstrUsageBallast [] PROGMEM = "Ballast"; -const char pstrUsageBicycleCrank [] PROGMEM = "Bicycle Crank"; -const char pstrUsageHandleBars [] PROGMEM = "Handle Bars"; -const char pstrUsageFrontBrake [] PROGMEM = "Front Brake"; -const char pstrUsageRearBrake [] PROGMEM = "Rear Brake"; - -// VR Controls Page -const char pstrUsageBelt [] PROGMEM = "Belt"; -const char pstrUsageBodySuit [] PROGMEM = "Body Suit"; -const char pstrUsageFlexor [] PROGMEM = "Flexor"; -const char pstrUsageGlove [] PROGMEM = "Glove"; -const char pstrUsageHeadTracker [] PROGMEM = "Head Track"; -const char pstrUsageHeadMountedDisplay [] PROGMEM = "Head Disp"; -const char pstrUsageHandTracker [] PROGMEM = "Hand Track"; -const char pstrUsageOculometer [] PROGMEM = "Oculometer"; -const char pstrUsageVest [] PROGMEM = "Vest"; -const char pstrUsageAnimatronicDevice [] PROGMEM = "Animat Dev"; -const char pstrUsageStereoEnable [] PROGMEM = "Stereo Enbl"; -const char pstrUsageDisplayEnable [] PROGMEM = "Display Enbl"; - -// Sport Controls Page -const char pstrUsageBaseballBat [] PROGMEM = "Baseball Bat"; -const char pstrUsageGolfClub [] PROGMEM = "Golf Club"; -const char pstrUsageRowingMachine [] PROGMEM = "Rowing Mach"; -const char pstrUsageTreadmill [] PROGMEM = "Treadmill"; -const char pstrUsageOar [] PROGMEM = "Oar"; -const char pstrUsageSlope [] PROGMEM = "Slope"; -const char pstrUsageRate [] PROGMEM = "Rate"; -const char pstrUsageStickSpeed [] PROGMEM = "Stick Speed"; -const char pstrUsageStickFaceAngle [] PROGMEM = "Stick Face Ang"; -const char pstrUsageStickHeelToe [] PROGMEM = "Stick Heel/Toe"; -const char pstrUsageStickFollowThough [] PROGMEM = "Stick Flw Thru"; -const char pstrUsageStickTempo [] PROGMEM = "Stick Tempo"; -const char pstrUsageStickType [] PROGMEM = "Stick Type"; -const char pstrUsageStickHeight [] PROGMEM = "Stick Hght"; -const char pstrUsagePutter [] PROGMEM = "Putter"; -const char pstrUsage1Iron [] PROGMEM = "1 Iron"; -const char pstrUsage2Iron [] PROGMEM = "2 Iron"; -const char pstrUsage3Iron [] PROGMEM = "3 Iron"; -const char pstrUsage4Iron [] PROGMEM = "4 Iron"; -const char pstrUsage5Iron [] PROGMEM = "5 Iron"; -const char pstrUsage6Iron [] PROGMEM = "6 Iron"; -const char pstrUsage7Iron [] PROGMEM = "7 Iron"; -const char pstrUsage8Iron [] PROGMEM = "8 Iron"; -const char pstrUsage9Iron [] PROGMEM = "9 Iron"; -const char pstrUsage10Iron [] PROGMEM = "10 Iron"; -const char pstrUsage11Iron [] PROGMEM = "11 Iron"; -const char pstrUsageSandWedge [] PROGMEM = "Sand Wedge"; -const char pstrUsageLoftWedge [] PROGMEM = "Loft Wedge"; -const char pstrUsagePowerWedge [] PROGMEM = "Pwr Wedge"; -const char pstrUsage1Wood [] PROGMEM = "1 Wood"; -const char pstrUsage3Wood [] PROGMEM = "3 Wood"; -const char pstrUsage5Wood [] PROGMEM = "5 Wood"; -const char pstrUsage7Wood [] PROGMEM = "7 Wood"; -const char pstrUsage9Wood [] PROGMEM = "9 Wood"; - -// Game Controls Page -const char pstrUsage3DGameController [] PROGMEM = "3D Game Ctrl"; -const char pstrUsagePinballDevice [] PROGMEM = "Pinball Dev"; -const char pstrUsageGunDevice [] PROGMEM = "Gun Dev"; -const char pstrUsagePointOfView [] PROGMEM = "POV"; -const char pstrUsageTurnRightLeft [] PROGMEM = "Turn Right Left"; -const char pstrUsagePitchForwardBackward [] PROGMEM = "Pitch Fwd/Back"; -const char pstrUsageRollRightLeft [] PROGMEM = "Roll Right/Left"; -const char pstrUsageMoveRightLeft [] PROGMEM = "Move Right/Left"; -const char pstrUsageMoveForwardBackward [] PROGMEM = "Move Fwd/Back"; -const char pstrUsageMoveUpDown [] PROGMEM = "Move Up/Down"; -const char pstrUsageLeanRightLeft [] PROGMEM = "Lean Right/Left"; -const char pstrUsageLeanForwardBackward [] PROGMEM = "Lean Fwd/Back"; -const char pstrUsageHeightOfPOV [] PROGMEM = "Height of POV"; -const char pstrUsageFlipper [] PROGMEM = "Flipper"; -const char pstrUsageSecondaryFlipper [] PROGMEM = "Second Flipper"; -const char pstrUsageBump [] PROGMEM = "Bump"; -const char pstrUsageNewGame [] PROGMEM = "New Game"; -const char pstrUsageShootBall [] PROGMEM = "Shoot Ball"; -const char pstrUsagePlayer [] PROGMEM = "Player"; -const char pstrUsageGunBolt [] PROGMEM = "Gun Bolt"; -const char pstrUsageGunClip [] PROGMEM = "Gun Clip"; -const char pstrUsageGunSelector [] PROGMEM = "Gun Sel"; -const char pstrUsageGunSingleShot [] PROGMEM = "Gun Sngl Shot"; -const char pstrUsageGunBurst [] PROGMEM = "Gun Burst"; -const char pstrUsageGunAutomatic [] PROGMEM = "Gun Auto"; -const char pstrUsageGunSafety [] PROGMEM = "Gun Safety"; -const char pstrUsageGamepadFireJump [] PROGMEM = "Gamepad Fire/Jump"; -const char pstrUsageGamepadTrigger [] PROGMEM = "Gamepad Trig"; - -// Generic Device Controls Page -const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength"; -const char pstrUsageWirelessChannel [] PROGMEM = "Wireless Ch"; -const char pstrUsageWirelessID [] PROGMEM = "Wireless ID"; -const char pstrUsageDiscoverWirelessControl [] PROGMEM = "Discover Wireless Ctrl"; -const char pstrUsageSecurityCodeCharEntered [] PROGMEM = "Sec Code Char Entrd"; -const char pstrUsageSecurityCodeCharErased [] PROGMEM = "Sec Code Char Erased"; -const char pstrUsageSecurityCodeCleared [] PROGMEM = "Sec Code Cleared"; - -// LED Page -const char pstrUsageNumLock [] PROGMEM = "Num Lock"; -const char pstrUsageCapsLock [] PROGMEM = "Caps Lock"; -const char pstrUsageScrollLock [] PROGMEM = "Scroll Lock"; -const char pstrUsageCompose [] PROGMEM = "Compose"; -const char pstrUsageKana [] PROGMEM = "Kana"; -const char pstrUsagePower [] PROGMEM = "Pwr"; -const char pstrUsageShift [] PROGMEM = "Shift"; -const char pstrUsageDoNotDisturb [] PROGMEM = "DND"; -const char pstrUsageMute [] PROGMEM = "Mute"; -const char pstrUsageToneEnable [] PROGMEM = "Tone Enbl"; -const char pstrUsageHighCutFilter [] PROGMEM = "High Cut Fltr"; -const char pstrUsageLowCutFilter [] PROGMEM = "Low Cut Fltr"; -const char pstrUsageEqualizerEnable [] PROGMEM = "Eq Enbl"; -const char pstrUsageSoundFieldOn [] PROGMEM = "Sound Field On"; -const char pstrUsageSurroundOn [] PROGMEM = "Surround On"; -const char pstrUsageRepeat [] PROGMEM = "Repeat"; -const char pstrUsageStereo [] PROGMEM = "Stereo"; -const char pstrUsageSamplingRateDetect [] PROGMEM = "Smpl Rate Detect"; -const char pstrUsageSpinning [] PROGMEM = "Spinning"; -const char pstrUsageCAV [] PROGMEM = "CAV"; -const char pstrUsageCLV [] PROGMEM = "CLV"; -const char pstrUsageRecordingFormatDetect [] PROGMEM = "Rec Format Detect"; -const char pstrUsageOffHook [] PROGMEM = "Off Hook"; -const char pstrUsageRing [] PROGMEM = "Ring"; -const char pstrUsageMessageWaiting [] PROGMEM = "Msg Wait"; -const char pstrUsageDataMode [] PROGMEM = "Data Mode"; -const char pstrUsageBatteryOperation [] PROGMEM = "Bat Op"; -const char pstrUsageBatteryOK [] PROGMEM = "Bat OK"; -const char pstrUsageBatteryLow [] PROGMEM = "Bat Low"; -const char pstrUsageSpeaker [] PROGMEM = "Speaker"; -const char pstrUsageHeadSet [] PROGMEM = "Head Set"; -const char pstrUsageHold [] PROGMEM = "Hold"; -const char pstrUsageMicrophone [] PROGMEM = "Mic"; -const char pstrUsageCoverage [] PROGMEM = "Coverage"; -const char pstrUsageNightMode [] PROGMEM = "Night Mode"; -const char pstrUsageSendCalls [] PROGMEM = "Send Calls"; -const char pstrUsageCallPickup [] PROGMEM = "Call Pickup"; -const char pstrUsageConference [] PROGMEM = "Conf"; -const char pstrUsageStandBy [] PROGMEM = "Stand-by"; -const char pstrUsageCameraOn [] PROGMEM = "Cam On"; -const char pstrUsageCameraOff [] PROGMEM = "Cam Off"; -const char pstrUsageOnLine [] PROGMEM = "On-Line"; -const char pstrUsageOffLine [] PROGMEM = "Off-Line"; -const char pstrUsageBusy [] PROGMEM = "Busy"; -const char pstrUsageReady [] PROGMEM = "Ready"; -const char pstrUsagePaperOut [] PROGMEM = "Paper Out"; -const char pstrUsagePaperJam [] PROGMEM = "Paper Jam"; -const char pstrUsageRemote [] PROGMEM = "Remote"; -const char pstrUsageForward [] PROGMEM = "Fwd"; -const char pstrUsageReverse [] PROGMEM = "Rev"; -const char pstrUsageStop [] PROGMEM = "Stop"; -const char pstrUsageRewind [] PROGMEM = "Rewind"; -const char pstrUsageFastForward [] PROGMEM = "Fast Fwd"; -const char pstrUsagePlay [] PROGMEM = "Play"; -const char pstrUsagePause [] PROGMEM = "Pause"; -const char pstrUsageRecord [] PROGMEM = "Rec"; -const char pstrUsageError [] PROGMEM = "Error"; -const char pstrUsageSelectedIndicator [] PROGMEM = "Usage Sel Ind"; -const char pstrUsageInUseIndicator [] PROGMEM = "Usage In Use Ind"; -const char pstrUsageMultiModeIndicator [] PROGMEM = "Usage Multi Mode Ind"; -const char pstrUsageIndicatorOn [] PROGMEM = "Ind On"; -const char pstrUsageIndicatorFlash [] PROGMEM = "Ind Flash"; -const char pstrUsageIndicatorSlowBlink [] PROGMEM = "Ind Slow Blk"; -const char pstrUsageIndicatorFastBlink [] PROGMEM = "Ind Fast Blk"; -const char pstrUsageIndicatorOff [] PROGMEM = "Ind Off"; -const char pstrUsageFlashOnTime [] PROGMEM = "Flash On Time"; -const char pstrUsageSlowBlinkOnTime [] PROGMEM = "Slow Blk On Time"; -const char pstrUsageSlowBlinkOffTime [] PROGMEM = "Slow Blk Off Time"; -const char pstrUsageFastBlinkOnTime [] PROGMEM = "Fast Blk On Time"; -const char pstrUsageFastBlinkOffTime [] PROGMEM = "Fast Blk Off Time"; -const char pstrUsageIndicatorColor [] PROGMEM = "Usage Ind Color"; -const char pstrUsageIndicatorRed [] PROGMEM = "Ind Red"; -const char pstrUsageIndicatorGreen [] PROGMEM = "Ind Green"; -const char pstrUsageIndicatorAmber [] PROGMEM = "Ind Amber"; -const char pstrUsageGenericIndicator [] PROGMEM = "Gen Ind"; -const char pstrUsageSystemSuspend [] PROGMEM = "Sys Suspend"; -const char pstrUsageExternalPowerConnected [] PROGMEM = "Ext Pwr Conn"; - -// Telephony Usage Page -const char pstrUsagePhone [] PROGMEM = "Phone"; -const char pstrUsageAnsweringMachine [] PROGMEM = "Answ Mach"; -const char pstrUsageMessageControls [] PROGMEM = "Msg Ctrls"; -const char pstrUsageHandset [] PROGMEM = "Handset"; -const char pstrUsageHeadset [] PROGMEM = "Headset"; -const char pstrUsageTelephonyKeyPad [] PROGMEM = "Tel Key Pad"; -const char pstrUsageProgrammableButton [] PROGMEM = "Prog Button"; -const char pstrUsageHookSwitch [] PROGMEM = "Hook Sw"; -const char pstrUsageFlash [] PROGMEM = "Flash"; -const char pstrUsageFeature [] PROGMEM = "Feature"; -//const char pstrUsageHold [] PROGMEM = "Hold"; -const char pstrUsageRedial [] PROGMEM = "Redial"; -const char pstrUsageTransfer [] PROGMEM = "Transfer"; -const char pstrUsageDrop [] PROGMEM = "Drop"; -const char pstrUsagePark [] PROGMEM = "Park"; -const char pstrUsageForwardCalls [] PROGMEM = "Fwd Calls"; -const char pstrUsageAlternateFunction [] PROGMEM = "Alt Func"; -const char pstrUsageLine [] PROGMEM = "Line"; -const char pstrUsageSpeakerPhone [] PROGMEM = "Spk Phone"; -//const char pstrUsageConference [] PROGMEM = "Conference"; -const char pstrUsageRingEnable [] PROGMEM = "Ring Enbl"; -const char pstrUsageRingSelect [] PROGMEM = "Ring Sel"; -const char pstrUsagePhoneMute [] PROGMEM = "Phone Mute"; -const char pstrUsageCallerID [] PROGMEM = "Caller ID"; -const char pstrUsageSend [] PROGMEM = "Send"; -const char pstrUsageSpeedDial [] PROGMEM = "Speed Dial"; -const char pstrUsageStoreNumber [] PROGMEM = "Store Num"; -const char pstrUsageRecallNumber [] PROGMEM = "Recall Num"; -const char pstrUsagePhoneDirectory [] PROGMEM = "Phone Dir"; -const char pstrUsageVoiceMail [] PROGMEM = "Voice Mail"; -const char pstrUsageScreenCalls [] PROGMEM = "Screen Calls"; -//const char pstrUsageDoNotDisturb [] PROGMEM = "Do Not Disturb"; -const char pstrUsageMessage [] PROGMEM = "Msg"; -const char pstrUsageAnswerOnOff [] PROGMEM = "Answer On/Off"; -const char pstrUsageInsideDialTone [] PROGMEM = "Inside Dial Tone"; -const char pstrUsageOutsideDialTone [] PROGMEM = "Outside Dial Tone"; -const char pstrUsageInsideRingTone [] PROGMEM = "Inside Ring Tone"; -const char pstrUsageOutsideRingTone [] PROGMEM = "Outside Ring Tone"; -const char pstrUsagePriorityRingTone [] PROGMEM = "Prior Ring Tone"; -const char pstrUsageInsideRingback [] PROGMEM = "Inside Ringback"; -const char pstrUsagePriorityRingback [] PROGMEM = "Priority Ringback"; -const char pstrUsageLineBusyTone [] PROGMEM = "Ln Busy Tone"; -const char pstrUsageReorderTone [] PROGMEM = "Reorder Tone"; -const char pstrUsageCallWaitingTone [] PROGMEM = "Call Wait Tone"; -const char pstrUsageConfirmationTone1 [] PROGMEM = "Cnfrm Tone1"; -const char pstrUsageConfirmationTone2 [] PROGMEM = "Cnfrm Tone2"; -const char pstrUsageTonesOff [] PROGMEM = "Tones Off"; -const char pstrUsageOutsideRingback [] PROGMEM = "Outside Ringback"; -const char pstrUsageRinger [] PROGMEM = "Ringer"; -const char pstrUsagePhoneKey0 [] PROGMEM = "0"; -const char pstrUsagePhoneKey1 [] PROGMEM = "1"; -const char pstrUsagePhoneKey2 [] PROGMEM = "2"; -const char pstrUsagePhoneKey3 [] PROGMEM = "3"; -const char pstrUsagePhoneKey4 [] PROGMEM = "4"; -const char pstrUsagePhoneKey5 [] PROGMEM = "5"; -const char pstrUsagePhoneKey6 [] PROGMEM = "6"; -const char pstrUsagePhoneKey7 [] PROGMEM = "7"; -const char pstrUsagePhoneKey8 [] PROGMEM = "8"; -const char pstrUsagePhoneKey9 [] PROGMEM = "9"; -const char pstrUsagePhoneKeyStar [] PROGMEM = "*"; -const char pstrUsagePhoneKeyPound [] PROGMEM = "#"; -const char pstrUsagePhoneKeyA [] PROGMEM = "A"; -const char pstrUsagePhoneKeyB [] PROGMEM = "B"; -const char pstrUsagePhoneKeyC [] PROGMEM = "C"; -const char pstrUsagePhoneKeyD [] PROGMEM = "D"; - -// Consumer Usage Page -const char pstrUsageConsumerControl [] PROGMEM = "Consumer Ctrl"; -const char pstrUsageNumericKeyPad [] PROGMEM = "Num Key Pad"; -//const char pstrUsageProgrammableButton [] PROGMEM = "Prog Btn"; -//const char pstrUsageMicrophone [] PROGMEM = "Mic"; -const char pstrUsageHeadphone [] PROGMEM = "Headphone"; -const char pstrUsageGraphicEqualizer [] PROGMEM = "Graph Eq"; -const char pstrUsagePlus10 [] PROGMEM = "+10"; -const char pstrUsagePlus100 [] PROGMEM = "+100"; -const char pstrUsageAMPM [] PROGMEM = "AM/PM"; -//const char pstrUsagePower [] PROGMEM = "Pwr"; -const char pstrUsageReset [] PROGMEM = "Reset"; -const char pstrUsageSleep [] PROGMEM = "Sleep"; -const char pstrUsageSleepAfter [] PROGMEM = "Sleep After"; -const char pstrUsageSleepMode [] PROGMEM = "Sleep Mode"; -const char pstrUsageIllumination [] PROGMEM = "Illumin"; -const char pstrUsageFunctionButtons [] PROGMEM = "Func Btns"; -const char pstrUsageMenu [] PROGMEM = "Menu"; -const char pstrUsageMenuPick [] PROGMEM = "Menu Pick"; -const char pstrUsageMenuUp [] PROGMEM = "Menu Up"; -const char pstrUsageMenuDown [] PROGMEM = "Menu Down"; -const char pstrUsageMenuLeft [] PROGMEM = "Menu Left"; -const char pstrUsageMenuRight [] PROGMEM = "Menu Right"; -const char pstrUsageMenuEscape [] PROGMEM = "Menu Esc"; -const char pstrUsageMenuValueIncrease [] PROGMEM = "Menu Val Inc"; -const char pstrUsageMenuValueDecrease [] PROGMEM = "Menu Val Dec"; -const char pstrUsageDataOnScreen [] PROGMEM = "Data On Scr"; -const char pstrUsageClosedCaption [] PROGMEM = "Closed Cptn"; -const char pstrUsageClosedCaptionSelect [] PROGMEM = "Closed Cptn Sel"; -const char pstrUsageVCRTV [] PROGMEM = "VCR/TV"; -const char pstrUsageBroadcastMode [] PROGMEM = "Brdcast Mode"; -const char pstrUsageSnapshot [] PROGMEM = "Snapshot"; -const char pstrUsageStill [] PROGMEM = "Still"; -const char pstrUsageSelection [] PROGMEM = "Sel"; -const char pstrUsageAssignSelection [] PROGMEM = "Assign Sel"; -const char pstrUsageModeStep [] PROGMEM = "Mode Step"; -const char pstrUsageRecallLast [] PROGMEM = "Recall Last"; -const char pstrUsageEnterChannel [] PROGMEM = "Entr Channel"; -const char pstrUsageOrderMovie [] PROGMEM = "Ord Movie"; -const char pstrUsageChannel [] PROGMEM = "Channel"; -const char pstrUsageMediaSelection [] PROGMEM = "Med Sel"; -const char pstrUsageMediaSelectComputer [] PROGMEM = "Med Sel Comp"; -const char pstrUsageMediaSelectTV [] PROGMEM = "Med Sel TV"; -const char pstrUsageMediaSelectWWW [] PROGMEM = "Med Sel WWW"; -const char pstrUsageMediaSelectDVD [] PROGMEM = "Med Sel DVD"; -const char pstrUsageMediaSelectTelephone [] PROGMEM = "Med Sel Tel"; -const char pstrUsageMediaSelectProgramGuide [] PROGMEM = "Med Sel PG"; -const char pstrUsageMediaSelectVideoPhone [] PROGMEM = "Med Sel Vid"; -const char pstrUsageMediaSelectGames [] PROGMEM = "Med Sel Games"; -const char pstrUsageMediaSelectMessages [] PROGMEM = "Med Sel Msg"; -const char pstrUsageMediaSelectCD [] PROGMEM = "Med Sel CD"; -const char pstrUsageMediaSelectVCR [] PROGMEM = "Med Sel VCR"; -const char pstrUsageMediaSelectTuner [] PROGMEM = "Med Sel Tuner"; -const char pstrUsageQuit [] PROGMEM = "Quit"; -const char pstrUsageHelp [] PROGMEM = "Help"; -const char pstrUsageMediaSelectTape [] PROGMEM = "Med Sel Tape"; -const char pstrUsageMediaSelectCable [] PROGMEM = "Med Sel Cbl"; -const char pstrUsageMediaSelectSatellite [] PROGMEM = "Med Sel Sat"; -const char pstrUsageMediaSelectSecurity [] PROGMEM = "Med Sel Secur"; -const char pstrUsageMediaSelectHome [] PROGMEM = "Med Sel Home"; -const char pstrUsageMediaSelectCall [] PROGMEM = "Med Sel Call"; -const char pstrUsageChannelIncrement [] PROGMEM = "Ch Inc"; -const char pstrUsageChannelDecrement [] PROGMEM = "Ch Dec"; -const char pstrUsageMediaSelectSAP [] PROGMEM = "Med Sel SAP"; -const char pstrUsageVCRPlus [] PROGMEM = "VCR+"; -const char pstrUsageOnce [] PROGMEM = "Once"; -const char pstrUsageDaily [] PROGMEM = "Daily"; -const char pstrUsageWeekly [] PROGMEM = "Weekly"; -const char pstrUsageMonthly [] PROGMEM = "Monthly"; -//const char pstrUsagePlay [] PROGMEM = "Play"; -//const char pstrUsagePause [] PROGMEM = "Pause"; -//const char pstrUsageRecord [] PROGMEM = "Rec"; -//const char pstrUsageFastForward [] PROGMEM = "FF"; -//const char pstrUsageRewind [] PROGMEM = "Rewind"; -const char pstrUsageScanNextTrack [] PROGMEM = "Next Track"; -const char pstrUsageScanPreviousTrack [] PROGMEM = "Prev Track"; -//const char pstrUsageStop [] PROGMEM = "Stop"; -const char pstrUsageEject [] PROGMEM = "Eject"; -const char pstrUsageRandomPlay [] PROGMEM = "Random"; -const char pstrUsageSelectDisk [] PROGMEM = "Sel Disk"; -const char pstrUsageEnterDisk [] PROGMEM = "Ent Disk"; -//const char pstrUsageRepeat [] PROGMEM = "Repeat"; -const char pstrUsageTracking [] PROGMEM = "Tracking"; -const char pstrUsageTrackNormal [] PROGMEM = "Trk Norm"; -const char pstrUsageSlowTracking [] PROGMEM = "Slow Trk"; -const char pstrUsageFrameForward [] PROGMEM = "Frm Fwd"; -const char pstrUsageFrameBackwards [] PROGMEM = "Frm Back"; -const char pstrUsageMark [] PROGMEM = "Mark"; -const char pstrUsageClearMark [] PROGMEM = "Clr Mark"; -const char pstrUsageRepeatFromMark [] PROGMEM = "Rpt Mark"; -const char pstrUsageReturnToMark [] PROGMEM = "Ret to Mark"; -const char pstrUsageSearchMarkForward [] PROGMEM = "Search Mark Fwd"; -const char pstrUsageSearchMarkBackwards [] PROGMEM = "Search Mark Back"; -const char pstrUsageCounterReset [] PROGMEM = "Counter Reset"; -const char pstrUsageShowCounter [] PROGMEM = "Show Counter"; -const char pstrUsageTrackingIncrement [] PROGMEM = "Track Inc"; -const char pstrUsageTrackingDecrement [] PROGMEM = "Track Dec"; -const char pstrUsageStopEject [] PROGMEM = "Stop/Eject"; -const char pstrUsagePlayPause [] PROGMEM = "Play/Pause"; -const char pstrUsagePlaySkip [] PROGMEM = "Play/Skip"; -const char pstrUsageVolume [] PROGMEM = "Vol"; -const char pstrUsageBalance [] PROGMEM = "Balance"; -//const char pstrUsageMute [] PROGMEM = "Mute"; -const char pstrUsageBass [] PROGMEM = "Bass"; -const char pstrUsageTreble [] PROGMEM = "Treble"; -const char pstrUsageBassBoost [] PROGMEM = "Bass Boost"; -const char pstrUsageSurroundMode [] PROGMEM = "Surround"; -const char pstrUsageLoudness [] PROGMEM = "Loud"; -const char pstrUsageMPX [] PROGMEM = "MPX"; -const char pstrUsageVolumeIncrement [] PROGMEM = "Vol Inc"; -const char pstrUsageVolumeDecrement [] PROGMEM = "Vol Dec"; -const char pstrUsageSpeedSelect [] PROGMEM = "Speed"; -const char pstrUsagePlaybackSpeed [] PROGMEM = "Play Speed"; -const char pstrUsageStandardPlay [] PROGMEM = "Std Play"; -const char pstrUsageLongPlay [] PROGMEM = "Long Play"; -const char pstrUsageExtendedPlay [] PROGMEM = "Ext Play"; -const char pstrUsageSlow [] PROGMEM = "Slow"; -const char pstrUsageFanEnable [] PROGMEM = "Fan Enbl"; -const char pstrUsageFanSpeed [] PROGMEM = "Fan Speed"; -const char pstrUsageLightEnable [] PROGMEM = "Light Enbl"; -const char pstrUsageLightIlluminationLevel [] PROGMEM = "Light Illum Lev"; -const char pstrUsageClimateControlEnable [] PROGMEM = "Climate Enbl"; -const char pstrUsageRoomTemperature [] PROGMEM = "Room Temp"; -const char pstrUsageSecurityEnable [] PROGMEM = "Secur Enbl"; -const char pstrUsageFireAlarm [] PROGMEM = "Fire Alm"; -const char pstrUsagePoliceAlarm [] PROGMEM = "Police Alm"; -const char pstrUsageProximity [] PROGMEM = "Prox"; -const char pstrUsageMotion [] PROGMEM = "Motion"; -const char pstrUsageDuresAlarm [] PROGMEM = "Dures Alm"; -const char pstrUsageHoldupAlarm [] PROGMEM = "Holdup Alm"; -const char pstrUsageMedicalAlarm [] PROGMEM = "Med Alm"; -const char pstrUsageBalanceRight [] PROGMEM = "Balance Right"; -const char pstrUsageBalanceLeft [] PROGMEM = "Balance Left"; -const char pstrUsageBassIncrement [] PROGMEM = "Bass Inc"; -const char pstrUsageBassDecrement [] PROGMEM = "Bass Dec"; -const char pstrUsageTrebleIncrement [] PROGMEM = "Treble Inc"; -const char pstrUsageTrebleDecrement [] PROGMEM = "Treble Dec"; -const char pstrUsageSpeakerSystem [] PROGMEM = "Spk Sys"; -const char pstrUsageChannelLeft [] PROGMEM = "Ch Left"; -const char pstrUsageChannelRight [] PROGMEM = "Ch Right"; -const char pstrUsageChannelCenter [] PROGMEM = "Ch Center"; -const char pstrUsageChannelFront [] PROGMEM = "Ch Front"; -const char pstrUsageChannelCenterFront [] PROGMEM = "Ch Cntr Front"; -const char pstrUsageChannelSide [] PROGMEM = "Ch Side"; -const char pstrUsageChannelSurround [] PROGMEM = "Ch Surround"; -const char pstrUsageChannelLowFreqEnhancement [] PROGMEM = "Ch Low Freq Enh"; -const char pstrUsageChannelTop [] PROGMEM = "Ch Top"; -const char pstrUsageChannelUnknown [] PROGMEM = "Ch Unk"; -const char pstrUsageSubChannel [] PROGMEM = "Sub-ch"; -const char pstrUsageSubChannelIncrement [] PROGMEM = "Sub-ch Inc"; -const char pstrUsageSubChannelDecrement [] PROGMEM = "Sub-ch Dec"; -const char pstrUsageAlternateAudioIncrement [] PROGMEM = "Alt Aud Inc"; -const char pstrUsageAlternateAudioDecrement [] PROGMEM = "Alt Aud Dec"; -const char pstrUsageApplicationLaunchButtons [] PROGMEM = "App Launch Btns"; -const char pstrUsageALLaunchButtonConfigTool [] PROGMEM = "AL Launch Conf Tl"; -const char pstrUsageALProgrammableButton [] PROGMEM = "AL Pgm Btn"; -const char pstrUsageALConsumerControlConfig [] PROGMEM = "AL Cons Ctrl Cfg"; -const char pstrUsageALWordProcessor [] PROGMEM = "AL Word Proc"; -const char pstrUsageALTextEditor [] PROGMEM = "AL Txt Edtr"; -const char pstrUsageALSpreadsheet [] PROGMEM = "AL Sprdsheet"; -const char pstrUsageALGraphicsEditor [] PROGMEM = "AL Graph Edtr"; -const char pstrUsageALPresentationApp [] PROGMEM = "AL Present App"; -const char pstrUsageALDatabaseApp [] PROGMEM = "AL DB App"; -const char pstrUsageALEmailReader [] PROGMEM = "AL E-mail Rdr"; -const char pstrUsageALNewsreader [] PROGMEM = "AL Newsrdr"; -const char pstrUsageALVoicemail [] PROGMEM = "AL Voicemail"; -const char pstrUsageALContactsAddressBook [] PROGMEM = "AL Addr Book"; -const char pstrUsageALCalendarSchedule [] PROGMEM = "AL Clndr/Schdlr"; -const char pstrUsageALTaskProjectManager [] PROGMEM = "AL Task/Prj Mgr"; -const char pstrUsageALLogJournalTimecard [] PROGMEM = "AL Log/Jrnl/Tmcrd"; -const char pstrUsageALCheckbookFinance [] PROGMEM = "AL Chckbook/Fin"; -const char pstrUsageALCalculator [] PROGMEM = "AL Calc"; -const char pstrUsageALAVCapturePlayback [] PROGMEM = "AL A/V Capt/Play"; -const char pstrUsageALLocalMachineBrowser [] PROGMEM = "AL Loc Mach Brow"; -const char pstrUsageALLANWANBrow [] PROGMEM = "AL LAN/WAN Brow"; -const char pstrUsageALInternetBrowser [] PROGMEM = "AL I-net Brow"; -const char pstrUsageALRemoteNetISPConnect [] PROGMEM = "AL Rem Net Con"; -const char pstrUsageALNetworkConference [] PROGMEM = "AL Net Conf"; -const char pstrUsageALNetworkChat [] PROGMEM = "AL Net Chat"; -const char pstrUsageALTelephonyDialer [] PROGMEM = "AL Tel/Dial"; -const char pstrUsageALLogon [] PROGMEM = "AL Logon"; -const char pstrUsageALLogoff [] PROGMEM = "AL Logoff"; -const char pstrUsageALLogonLogoff [] PROGMEM = "AL Logon/Logoff"; -const char pstrUsageALTermLockScrSav [] PROGMEM = "AL Term Lock/Scr Sav"; -const char pstrUsageALControlPannel [] PROGMEM = "AL Ctrl Pan"; -const char pstrUsageALCommandLineProcessorRun [] PROGMEM = "AL Cmd/Run"; -const char pstrUsageALProcessTaskManager [] PROGMEM = "AL Task Mgr"; -const char pstrUsageALSelectTaskApplication [] PROGMEM = "AL Sel App"; -const char pstrUsageALNextTaskApplication [] PROGMEM = "AL Next App"; -const char pstrUsageALPreviousTaskApplication [] PROGMEM = "AL Prev App"; -const char pstrUsageALPreemptiveHaltTaskApp [] PROGMEM = "AL Prmpt Halt App"; -const char pstrUsageALIntegratedHelpCenter [] PROGMEM = "AL Hlp Cntr"; -const char pstrUsageALDocuments [] PROGMEM = "AL Docs"; -const char pstrUsageALThesaurus [] PROGMEM = "AL Thsrs"; -const char pstrUsageALDictionary [] PROGMEM = "AL Dict"; -const char pstrUsageALDesktop [] PROGMEM = "AL Desktop"; -const char pstrUsageALSpellCheck [] PROGMEM = "AL Spell Chk"; -const char pstrUsageALGrammarCheck [] PROGMEM = "AL Gram Chk"; -const char pstrUsageALWirelessStatus [] PROGMEM = "AL Wireless Sts"; -const char pstrUsageALKeyboardLayout [] PROGMEM = "AL Kbd Layout"; -const char pstrUsageALVirusProtection [] PROGMEM = "AL Vir Protect"; -const char pstrUsageALEncryption [] PROGMEM = "AL Encrypt"; -const char pstrUsageALScreenSaver [] PROGMEM = "AL Scr Sav"; -const char pstrUsageALAlarms [] PROGMEM = "AL Alarms"; -const char pstrUsageALClock [] PROGMEM = "AL Clock"; -const char pstrUsageALFileBrowser [] PROGMEM = "AL File Brow"; -const char pstrUsageALPowerStatus [] PROGMEM = "AL Pwr Sts"; -const char pstrUsageALImageBrowser [] PROGMEM = "AL Img Brow"; -const char pstrUsageALAudioBrowser [] PROGMEM = "AL Aud Brow"; -const char pstrUsageALMovieBrowser [] PROGMEM = "AL Mov Brow"; -const char pstrUsageALDigitalRightsManager [] PROGMEM = "AL Dig Rights Mgr"; -const char pstrUsageALDigitalWallet [] PROGMEM = "AL Dig Wallet"; -const char pstrUsageALInstantMessaging [] PROGMEM = "AL Inst Msg"; -const char pstrUsageALOEMFeaturesBrowser [] PROGMEM = "AL OEM Tips Brow"; -const char pstrUsageALOEMHelp [] PROGMEM = "AL OEM Hlp"; -const char pstrUsageALOnlineCommunity [] PROGMEM = "AL Online Com"; -const char pstrUsageALEntertainmentContentBrow [] PROGMEM = "AL Ent Cont Brow"; -const char pstrUsageALOnlineShoppingBrowser [] PROGMEM = "AL Online Shop Brow"; -const char pstrUsageALSmartCardInfoHelp [] PROGMEM = "AL SmartCard Inf"; -const char pstrUsageALMarketMonitorFinBrowser [] PROGMEM = "AL Market Brow"; -const char pstrUsageALCustomCorpNewsBrowser [] PROGMEM = "AL Cust Corp News Brow"; -const char pstrUsageALOnlineActivityBrowser [] PROGMEM = "AL Online Act Brow"; -const char pstrUsageALResearchSearchBrowser [] PROGMEM = "AL Search Brow"; -const char pstrUsageALAudioPlayer [] PROGMEM = "AL Aud Player"; -const char pstrUsageGenericGUIAppControls [] PROGMEM = "Gen GUI App Ctrl"; -const char pstrUsageACNew [] PROGMEM = "AC New"; -const char pstrUsageACOpen [] PROGMEM = "AC Open"; -const char pstrUsageACClose [] PROGMEM = "AC Close"; -const char pstrUsageACExit [] PROGMEM = "AC Exit"; -const char pstrUsageACMaximize [] PROGMEM = "AC Max"; -const char pstrUsageACMinimize [] PROGMEM = "AC Min"; -const char pstrUsageACSave [] PROGMEM = "AC Save"; -const char pstrUsageACPrint [] PROGMEM = "AC Print"; -const char pstrUsageACProperties [] PROGMEM = "AC Prop"; -const char pstrUsageACUndo [] PROGMEM = "AC Undo"; -const char pstrUsageACCopy [] PROGMEM = "AC Copy"; -const char pstrUsageACCut [] PROGMEM = "AC Cut"; -const char pstrUsageACPaste [] PROGMEM = "AC Paste"; -const char pstrUsageACSelectAll [] PROGMEM = "AC Sel All"; -const char pstrUsageACFind [] PROGMEM = "AC Find"; -const char pstrUsageACFindAndReplace [] PROGMEM = "AC Find/Replace"; -const char pstrUsageACSearch [] PROGMEM = "AC Search"; -const char pstrUsageACGoto [] PROGMEM = "AC Goto"; -const char pstrUsageACHome [] PROGMEM = "AC Home"; -const char pstrUsageACBack [] PROGMEM = "AC Back"; -const char pstrUsageACForward [] PROGMEM = "AC Fwd"; -const char pstrUsageACStop [] PROGMEM = "AC Stop"; -const char pstrUsageACRefresh [] PROGMEM = "AC Refresh"; -const char pstrUsageACPreviousLink [] PROGMEM = "AC Prev Link"; -const char pstrUsageACNextLink [] PROGMEM = "AC Next Link"; -const char pstrUsageACBookmarks [] PROGMEM = "AC Bkmarks"; -const char pstrUsageACHistory [] PROGMEM = "AC Hist"; -const char pstrUsageACSubscriptions [] PROGMEM = "AC Subscr"; -const char pstrUsageACZoomIn [] PROGMEM = "AC Zoom In"; -const char pstrUsageACZoomOut [] PROGMEM = "AC Zoom Out"; -const char pstrUsageACZoom [] PROGMEM = "AC Zoom"; -const char pstrUsageACFullScreenView [] PROGMEM = "AC Full Scr"; -const char pstrUsageACNormalView [] PROGMEM = "AC Norm View"; -const char pstrUsageACViewToggle [] PROGMEM = "AC View Tgl"; -const char pstrUsageACScrollUp [] PROGMEM = "AC Scroll Up"; -const char pstrUsageACScrollDown [] PROGMEM = "AC Scroll Down"; -const char pstrUsageACScroll [] PROGMEM = "AC Scroll"; -const char pstrUsageACPanLeft [] PROGMEM = "AC Pan Left"; -const char pstrUsageACPanRight [] PROGMEM = "AC Pan Right"; -const char pstrUsageACPan [] PROGMEM = "AC Pan"; -const char pstrUsageACNewWindow [] PROGMEM = "AC New Wnd"; -const char pstrUsageACTileHoriz [] PROGMEM = "AC Tile Horiz"; -const char pstrUsageACTileVert [] PROGMEM = "AC Tile Vert"; -const char pstrUsageACFormat [] PROGMEM = "AC Frmt"; -const char pstrUsageACEdit [] PROGMEM = "AC Edit"; -const char pstrUsageACBold [] PROGMEM = "AC Bold"; -const char pstrUsageACItalics [] PROGMEM = "AC Ital"; -const char pstrUsageACUnderline [] PROGMEM = "AC Under"; -const char pstrUsageACStrikethrough [] PROGMEM = "AC Strike"; -const char pstrUsageACSubscript [] PROGMEM = "AC Sub"; -const char pstrUsageACSuperscript [] PROGMEM = "AC Super"; -const char pstrUsageACAllCaps [] PROGMEM = "AC All Caps"; -const char pstrUsageACRotate [] PROGMEM = "AC Rotate"; -const char pstrUsageACResize [] PROGMEM = "AC Resize"; -const char pstrUsageACFlipHorizontal [] PROGMEM = "AC Flp H"; -const char pstrUsageACFlipVertical [] PROGMEM = "AC Flp V"; -const char pstrUsageACMirrorHorizontal [] PROGMEM = "AC Mir H"; -const char pstrUsageACMirrorVertical [] PROGMEM = "AC Mir V"; -const char pstrUsageACFontSelect [] PROGMEM = "AC Fnt Sel"; -const char pstrUsageACFontColor [] PROGMEM = "AC Fnt Clr"; -const char pstrUsageACFontSize [] PROGMEM = "AC Fnt Size"; -const char pstrUsageACJustifyLeft [] PROGMEM = "AC Just Left"; -const char pstrUsageACJustifyCenterH [] PROGMEM = "AC Just Cent H"; -const char pstrUsageACJustifyRight [] PROGMEM = "AC Just Right"; -const char pstrUsageACJustifyBlockH [] PROGMEM = "AC Just Block H"; -const char pstrUsageACJustifyTop [] PROGMEM = "AC Just Top"; -const char pstrUsageACJustifyCenterV [] PROGMEM = "AC Just Cent V"; -const char pstrUsageACJustifyBottom [] PROGMEM = "AC Just Bot"; -const char pstrUsageACJustifyBlockV [] PROGMEM = "AC Just Block V"; -const char pstrUsageACIndentDecrease [] PROGMEM = "AC Indent Dec"; -const char pstrUsageACIndentIncrease [] PROGMEM = "AC Indent Inc"; -const char pstrUsageACNumberedList [] PROGMEM = "AC Num List"; -const char pstrUsageACRestartNumbering [] PROGMEM = "AC Res Num"; -const char pstrUsageACBulletedList [] PROGMEM = "AC Blt List"; -const char pstrUsageACPromote [] PROGMEM = "AC Promote"; -const char pstrUsageACDemote [] PROGMEM = "AC Demote"; -const char pstrUsageACYes [] PROGMEM = "AC Yes"; -const char pstrUsageACNo [] PROGMEM = "AC No"; -const char pstrUsageACCancel [] PROGMEM = "AC Cancel"; -const char pstrUsageACCatalog [] PROGMEM = "AC Ctlg"; -const char pstrUsageACBuyChkout [] PROGMEM = "AC Buy"; -const char pstrUsageACAddToCart [] PROGMEM = "AC Add2Cart"; -const char pstrUsageACExpand [] PROGMEM = "AC Xpnd"; -const char pstrUsageACExpandAll [] PROGMEM = "AC Xpand All"; -const char pstrUsageACCollapse [] PROGMEM = "AC Collapse"; -const char pstrUsageACCollapseAll [] PROGMEM = "AC Collapse All"; -const char pstrUsageACPrintPreview [] PROGMEM = "AC Prn Prevw"; -const char pstrUsageACPasteSpecial [] PROGMEM = "AC Paste Spec"; -const char pstrUsageACInsertMode [] PROGMEM = "AC Ins Mode"; -const char pstrUsageACDelete [] PROGMEM = "AC Del"; -const char pstrUsageACLock [] PROGMEM = "AC Lock"; -const char pstrUsageACUnlock [] PROGMEM = "AC Unlock"; -const char pstrUsageACProtect [] PROGMEM = "AC Prot"; -const char pstrUsageACUnprotect [] PROGMEM = "AC Unprot"; -const char pstrUsageACAttachComment [] PROGMEM = "AC Attach Cmnt"; -const char pstrUsageACDeleteComment [] PROGMEM = "AC Del Cmnt"; -const char pstrUsageACViewComment [] PROGMEM = "AC View Cmnt"; -const char pstrUsageACSelectWord [] PROGMEM = "AC Sel Word"; -const char pstrUsageACSelectSentence [] PROGMEM = "AC Sel Sntc"; -const char pstrUsageACSelectParagraph [] PROGMEM = "AC Sel Para"; -const char pstrUsageACSelectColumn [] PROGMEM = "AC Sel Col"; -const char pstrUsageACSelectRow [] PROGMEM = "AC Sel Row"; -const char pstrUsageACSelectTable [] PROGMEM = "AC Sel Tbl"; -const char pstrUsageACSelectObject [] PROGMEM = "AC Sel Obj"; -const char pstrUsageACRedoRepeat [] PROGMEM = "AC Redo"; -const char pstrUsageACSort [] PROGMEM = "AC Sort"; -const char pstrUsageACSortAscending [] PROGMEM = "AC Sort Asc"; -const char pstrUsageACSortDescending [] PROGMEM = "AC Sort Desc"; -const char pstrUsageACFilter [] PROGMEM = "AC Filt"; -const char pstrUsageACSetClock [] PROGMEM = "AC Set Clk"; -const char pstrUsageACViewClock [] PROGMEM = "AC View Clk"; -const char pstrUsageACSelectTimeZone [] PROGMEM = "AC Sel Time Z"; -const char pstrUsageACEditTimeZone [] PROGMEM = "AC Edt Time Z"; -const char pstrUsageACSetAlarm [] PROGMEM = "AC Set Alm"; -const char pstrUsageACClearAlarm [] PROGMEM = "AC Clr Alm"; -const char pstrUsageACSnoozeAlarm [] PROGMEM = "AC Snz Alm"; -const char pstrUsageACResetAlarm [] PROGMEM = "AC Rst Alm"; -const char pstrUsageACSyncronize [] PROGMEM = "AC Sync"; -const char pstrUsageACSendReceive [] PROGMEM = "AC Snd/Rcv"; -const char pstrUsageACSendTo [] PROGMEM = "AC Snd To"; -const char pstrUsageACReply [] PROGMEM = "AC Reply"; -const char pstrUsageACReplyAll [] PROGMEM = "AC Reply All"; -const char pstrUsageACForwardMessage [] PROGMEM = "AC Fwd Msg"; -const char pstrUsageACSend [] PROGMEM = "AC Snd"; -const char pstrUsageACAttachFile [] PROGMEM = "AC Att File"; -const char pstrUsageACUpload [] PROGMEM = "AC Upld"; -const char pstrUsageACDownload [] PROGMEM = "AC Dnld"; -const char pstrUsageACSetBorders [] PROGMEM = "AC Set Brd"; -const char pstrUsageACInsertRow [] PROGMEM = "AC Ins Row"; -const char pstrUsageACInsertColumn [] PROGMEM = "AC Ins Col"; -const char pstrUsageACInsertFile [] PROGMEM = "AC Ins File"; -const char pstrUsageACInsertPicture [] PROGMEM = "AC Ins Pic"; -const char pstrUsageACInsertObject [] PROGMEM = "AC Ins Obj"; -const char pstrUsageACInsertSymbol [] PROGMEM = "AC Ins Sym"; -const char pstrUsageACSaveAndClose [] PROGMEM = "AC Sav&Cls"; -const char pstrUsageACRename [] PROGMEM = "AC Rename"; -const char pstrUsageACMerge [] PROGMEM = "AC Merge"; -const char pstrUsageACSplit [] PROGMEM = "AC Split"; -const char pstrUsageACDistributeHorizontaly [] PROGMEM = "AC Dist Hor"; -const char pstrUsageACDistributeVerticaly [] PROGMEM = "AC Dist Ver"; - -// Digitaizers -const char pstrUsageDigitizer [] PROGMEM = "Digitizer"; -const char pstrUsagePen [] PROGMEM = "Pen"; -const char pstrUsageLightPen [] PROGMEM = "Light Pen"; -const char pstrUsageTouchScreen [] PROGMEM = "Touch Scr"; -const char pstrUsageTouchPad [] PROGMEM = "Touch Pad"; -const char pstrUsageWhiteBoard [] PROGMEM = "White Brd"; -const char pstrUsageCoordinateMeasuringMachine [] PROGMEM = "Coord Meas Mach"; -const char pstrUsage3DDigitizer [] PROGMEM = "3D Dgtz"; -const char pstrUsageStereoPlotter [] PROGMEM = "Stereo Plot"; -const char pstrUsageArticulatedArm [] PROGMEM = "Art Arm"; -const char pstrUsageArmature [] PROGMEM = "Armature"; -const char pstrUsageMultiplePointDigitizer [] PROGMEM = "Multi Point Dgtz"; -const char pstrUsageFreeSpaceWand [] PROGMEM = "Free Space Wand"; -const char pstrUsageStylus [] PROGMEM = "Stylus"; -const char pstrUsagePuck [] PROGMEM = "Puck"; -const char pstrUsageFinger [] PROGMEM = "Finger"; -const char pstrUsageTipPressure [] PROGMEM = "Tip Press"; -const char pstrUsageBarrelPressure [] PROGMEM = "Brl Press"; -const char pstrUsageInRange [] PROGMEM = "In Range"; -const char pstrUsageTouch [] PROGMEM = "Touch"; -const char pstrUsageUntouch [] PROGMEM = "Untouch"; -const char pstrUsageTap [] PROGMEM = "Tap"; -const char pstrUsageQuality [] PROGMEM = "Qlty"; -const char pstrUsageDataValid [] PROGMEM = "Data Valid"; -const char pstrUsageTransducerIndex [] PROGMEM = "Transducer Ind"; -const char pstrUsageTabletFunctionKeys [] PROGMEM = "Tabl Func Keys"; -const char pstrUsageProgramChangeKeys [] PROGMEM = "Pgm Chng Keys"; -//const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength"; -const char pstrUsageInvert [] PROGMEM = "Invert"; -const char pstrUsageXTilt [] PROGMEM = "X Tilt"; -const char pstrUsageYTilt [] PROGMEM = "Y Tilt"; -const char pstrUsageAzimuth [] PROGMEM = "Azimuth"; -const char pstrUsageAltitude [] PROGMEM = "Altitude"; -const char pstrUsageTwist [] PROGMEM = "Twist"; -const char pstrUsageTipSwitch [] PROGMEM = "Tip Sw"; -const char pstrUsageSecondaryTipSwitch [] PROGMEM = "Scnd Tip Sw"; -const char pstrUsageBarrelSwitch [] PROGMEM = "Brl Sw"; -const char pstrUsageEraser [] PROGMEM = "Eraser"; -const char pstrUsageTabletPick [] PROGMEM = "Tbl Pick"; - -// Alphanumeric Display Page -const char pstrUsageAlphanumericDisplay [] PROGMEM = "Alphanum Disp"; -const char pstrUsageBitmappedDisplay [] PROGMEM = "Bmp Disp"; -const char pstrUsageDisplayAttributesReport [] PROGMEM = "Disp Attr Rpt"; -const char pstrUsageASCIICharacterSet [] PROGMEM = "ASCII chset"; -const char pstrUsageDataReadBack [] PROGMEM = "Data Rd Back"; -const char pstrUsageFontReadBack [] PROGMEM = "Fnt Rd Back"; -const char pstrUsageDisplayControlReport [] PROGMEM = "Disp Ctrl Rpt"; -const char pstrUsageClearDisplay [] PROGMEM = "Clr Disp"; -//const char pstrUsageDisplayEnable [] PROGMEM = "Disp Enbl"; -const char pstrUsageScreenSaverDelay [] PROGMEM = "Scr Sav Delay"; -const char pstrUsageScreenSaverEnable [] PROGMEM = "Scr Sav Enbl"; -const char pstrUsageVerticalScroll [] PROGMEM = "V Scroll"; -const char pstrUsageHorizontalScroll [] PROGMEM = "H Scroll"; -const char pstrUsageCharacterReport [] PROGMEM = "Char Rpt"; -const char pstrUsageDisplayData [] PROGMEM = "Disp Data"; -const char pstrUsageDisplayStatus [] PROGMEM = "Disp Stat"; -const char pstrUsageStatusNotReady [] PROGMEM = "Stat !Ready"; -const char pstrUsageStatusReady [] PROGMEM = "Stat Ready"; -const char pstrUsageErrorNotALoadableCharacter [] PROGMEM = "Err Not Ld Char"; -const char pstrUsageErrorFotDataCanNotBeRead [] PROGMEM = "Fnt Data Rd Err"; -const char pstrUsageCursorPositionReport [] PROGMEM = "Cur Pos Rpt"; -const char pstrUsageRow [] PROGMEM = "Row"; -const char pstrUsageColumn [] PROGMEM = "Col"; -const char pstrUsageRows [] PROGMEM = "Rows"; -const char pstrUsageColumns [] PROGMEM = "Cols"; -const char pstrUsageCursorPixelPosition [] PROGMEM = "Cur Pix Pos"; -const char pstrUsageCursorMode [] PROGMEM = "Cur Mode"; -const char pstrUsageCursorEnable [] PROGMEM = "Cur Enbl"; -const char pstrUsageCursorBlink [] PROGMEM = "Cur Blnk"; -const char pstrUsageFontReport [] PROGMEM = "Fnt Rpt"; -const char pstrUsageFontData [] PROGMEM = "Fnt Data"; -const char pstrUsageCharacterWidth [] PROGMEM = "Char Wdth"; -const char pstrUsageCharacterHeight [] PROGMEM = "Char Hght"; -const char pstrUsageCharacterSpacingHorizontal [] PROGMEM = "Char Space H"; -const char pstrUsageCharacterSpacingVertical [] PROGMEM = "Char Space V"; -const char pstrUsageUnicodeCharset [] PROGMEM = "Unicode Char"; -const char pstrUsageFont7Segment [] PROGMEM = "Fnt 7-seg"; -const char pstrUsage7SegmentDirectMap [] PROGMEM = "7-seg map"; -const char pstrUsageFont14Segment [] PROGMEM = "Fnt 14-seg"; -const char pstrUsage14SegmentDirectMap [] PROGMEM = "14-seg map"; -const char pstrUsageDisplayBrightness [] PROGMEM = "Disp Bright"; -const char pstrUsageDisplayContrast [] PROGMEM = "Disp Cntrst"; -const char pstrUsageCharacterAttribute [] PROGMEM = "Char Attr"; -const char pstrUsageAttributeReadback [] PROGMEM = "Attr Readbk"; -const char pstrUsageAttributeData [] PROGMEM = "Attr Data"; -const char pstrUsageCharAttributeEnhance [] PROGMEM = "Char Attr Enh"; -const char pstrUsageCharAttributeUnderline [] PROGMEM = "Char Attr Undl"; -const char pstrUsageCharAttributeBlink [] PROGMEM = "Char Attr Blnk"; -const char pstrUsageBitmapSizeX [] PROGMEM = "Bmp Size X"; -const char pstrUsageBitmapSizeY [] PROGMEM = "Bmp Size Y"; -const char pstrUsageBitDepthFormat [] PROGMEM = "Bit Dpth Fmt"; -const char pstrUsageDisplayOrientation [] PROGMEM = "Disp Ornt"; -const char pstrUsagePaletteReport [] PROGMEM = "Pal Rpt"; -const char pstrUsagePaletteDataSize [] PROGMEM = "Pal Data Size"; -const char pstrUsagePaletteDataOffset [] PROGMEM = "Pal Data Off"; -const char pstrUsagePaletteData [] PROGMEM = "Pal Data"; -const char pstrUsageBlitReport [] PROGMEM = "Blit Rpt"; -const char pstrUsageBlitRectangleX1 [] PROGMEM = "Blit Rect X1"; -const char pstrUsageBlitRectangleY1 [] PROGMEM = "Blit Rect Y1"; -const char pstrUsageBlitRectangleX2 [] PROGMEM = "Blit Rect X2"; -const char pstrUsageBlitRectangleY2 [] PROGMEM = "Blit Rect Y2"; -const char pstrUsageBlitData [] PROGMEM = "Blit Data"; -const char pstrUsageSoftButton [] PROGMEM = "Soft Btn"; -const char pstrUsageSoftButtonID [] PROGMEM = "Soft Btn ID"; -const char pstrUsageSoftButtonSide [] PROGMEM = "Soft Btn Side"; -const char pstrUsageSoftButtonOffset1 [] PROGMEM = "Soft Btn Off1"; -const char pstrUsageSoftButtonOffset2 [] PROGMEM = "Soft Btn Off2"; -const char pstrUsageSoftButtonReport [] PROGMEM = "Soft Btn Rpt"; - -// Medical Instrument Page -const char pstrUsageMedicalUltrasound [] PROGMEM = "Med Ultrasnd"; -const char pstrUsageVCRAcquisition [] PROGMEM = "VCR/Acq"; -const char pstrUsageFreezeThaw [] PROGMEM = "Freeze"; -const char pstrUsageClipStore [] PROGMEM = "Clip Store"; -const char pstrUsageUpdate [] PROGMEM = "Update"; -const char pstrUsageNext [] PROGMEM = "Next"; -const char pstrUsageSave [] PROGMEM = "Save"; -const char pstrUsagePrint [] PROGMEM = "Print"; -const char pstrUsageMicrophoneEnable [] PROGMEM = "Mic Enbl"; -const char pstrUsageCine [] PROGMEM = "Cine"; -const char pstrUsageTransmitPower [] PROGMEM = "Trans Pwr"; -//const char pstrUsageVolume [] PROGMEM = "Vol"; -const char pstrUsageFocus [] PROGMEM = "Focus"; -const char pstrUsageDepth [] PROGMEM = "Depth"; -const char pstrUsageSoftStepPrimary [] PROGMEM = "Soft Stp-Pri"; -const char pstrUsageSoftStepSecondary [] PROGMEM = "Soft Stp-Sec"; -const char pstrUsageDepthGainCompensation [] PROGMEM = "Dpth Gain Comp"; -const char pstrUsageZoomSelect [] PROGMEM = "Zoom Sel"; -const char pstrUsageZoomAdjust [] PROGMEM = "Zoom Adj"; -const char pstrUsageSpectralDopplerModeSelect [] PROGMEM = "Spec Dop Mode Sel"; -const char pstrUsageSpectralDopplerModeAdjust [] PROGMEM = "Spec Dop Mode Adj"; -const char pstrUsageColorDopplerModeSelect [] PROGMEM = "Color Dop Mode Sel"; -const char pstrUsageColorDopplerModeAdjust [] PROGMEM = "Color Dop Mode Adj"; -const char pstrUsageMotionModeSelect [] PROGMEM = "Motion Mode Sel"; -const char pstrUsageMotionModeAdjust [] PROGMEM = "Motion Mode Adj"; -const char pstrUsage2DModeSelect [] PROGMEM = "2D Mode Sel"; -const char pstrUsage2DModeAdjust [] PROGMEM = "2D Mode Adj"; -const char pstrUsageSoftControlSelect [] PROGMEM = "Soft Ctrl Sel"; -const char pstrUsageSoftControlAdjust [] PROGMEM = "Soft Ctrl Adj"; - -//extern const char *usagePageTitles0[15]; -//const char *usagePageTitles1[]; -//const char *genDesktopTitles0[]; -//const char *genDesktopTitles1[]; -//const char *genDesktopTitles2[]; -//const char *genDesktopTitles3[]; -//const char *genDesktopTitles4[]; -//const char *simuTitles0[]; -//const char *simuTitles1[]; -//const char *simuTitles2[]; -//const char *vrTitles0[]; -//const char *vrTitles1[]; -//const char *sportsCtrlTitles0[]; -//const char *sportsCtrlTitles1[]; -//const char *sportsCtrlTitles2[]; -//const char *gameTitles0[]; -//const char *gameTitles1[]; -//const char *genDevCtrlTitles[]; -//const char *ledTitles[]; -//const char *telTitles0[]; -//const char *telTitles1[]; -//const char *telTitles2[]; -//const char *telTitles3[]; -//const char *telTitles4[]; -//const char *telTitles5[]; -//const char *consTitles0[]; -//const char *consTitles1[]; -//const char *consTitles2[]; -//const char *consTitles3[]; -//const char *consTitles4[]; -//const char *consTitles5[]; -//const char *consTitles6[]; -//const char *consTitles7[]; -//const char *consTitles8[]; -//const char *consTitles9[]; -//const char *consTitlesA[]; -//const char *consTitlesB[]; -//const char *consTitlesC[]; -//const char *consTitlesD[]; -//const char *consTitlesE[]; -//const char *digitTitles0[]; -//const char *digitTitles1[]; -//const char *digitTitles2[]; -//const char *aplphanumTitles0[]; -//const char *aplphanumTitles1[]; -//const char *aplphanumTitles2[]; -//const char *medInstrTitles0[]; -//const char *medInstrTitles1[]; -//const char *medInstrTitles2[]; -//const char *medInstrTitles3[]; -//const char *medInstrTitles4[]; - -#endif //__HIDUSAGESTR_H__ diff --git a/test/libraries/USBHost/src/macros.h b/test/libraries/USBHost/src/macros.h deleted file mode 100644 index 5df3faff..00000000 --- a/test/libraries/USBHost/src/macros.h +++ /dev/null @@ -1,82 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(MACROS_H) -#error "Never include macros.h directly; include Usb.h instead" -#else -#define MACROS_H - -//////////////////////////////////////////////////////////////////////////////// -// HANDY MACROS -//////////////////////////////////////////////////////////////////////////////// - -#define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h))) -#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h))) -#define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)/*pgm_read_pointer*/(wa), el) -#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el); - -#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) -#ifndef __BYTE_GRABBING_DEFINED__ -#define __BYTE_GRABBING_DEFINED__ 1 -#ifdef BROKEN_OPTIMIZER_LITTLE_ENDIAN -// Note: Use this if your compiler generates horrible assembler! -#define BGRAB0(__usi__) (((uint8_t *)&(__usi__))[0]) -#define BGRAB1(__usi__) (((uint8_t *)&(__usi__))[1]) -#define BGRAB2(__usi__) (((uint8_t *)&(__usi__))[2]) -#define BGRAB3(__usi__) (((uint8_t *)&(__usi__))[3]) -#define BGRAB4(__usi__) (((uint8_t *)&(__usi__))[4]) -#define BGRAB5(__usi__) (((uint8_t *)&(__usi__))[5]) -#define BGRAB6(__usi__) (((uint8_t *)&(__usi__))[6]) -#define BGRAB7(__usi__) (((uint8_t *)&(__usi__))[7]) -#else -// Note: The cast alone to uint8_t is actually enough. -// GCC throws out the "& 0xff", and the size is no different. -// Some compilers need it. -#define BGRAB0(__usi__) ((uint8_t)((__usi__) & 0xff )) -#define BGRAB1(__usi__) ((uint8_t)(((__usi__) >> 8) & 0xff)) -#define BGRAB2(__usi__) ((uint8_t)(((__usi__) >> 16) & 0xff)) -#define BGRAB3(__usi__) ((uint8_t)(((__usi__) >> 24) & 0xff)) -#define BGRAB4(__usi__) ((uint8_t)(((__usi__) >> 32) & 0xff)) -#define BGRAB5(__usi__) ((uint8_t)(((__usi__) >> 40) & 0xff)) -#define BGRAB6(__usi__) ((uint8_t)(((__usi__) >> 48) & 0xff)) -#define BGRAB7(__usi__) ((uint8_t)(((__usi__) >> 56) & 0xff)) -#endif -#define BOVER1(__usi__) ((uint16_t)(__usi__) << 8) -#define BOVER2(__usi__) ((uint32_t)(__usi__) << 16) -#define BOVER3(__usi__) ((uint32_t)(__usi__) << 24) -#define BOVER4(__usi__) ((uint64_t)(__usi__) << 32) -#define BOVER5(__usi__) ((uint64_t)(__usi__) << 40) -#define BOVER6(__usi__) ((uint64_t)(__usi__) << 48) -#define BOVER7(__usi__) ((uint64_t)(__usi__) << 56) - -// These are the smallest and fastest ways I have found so far in pure C/C++. -#define BMAKE16(__usc1__,__usc0__) ((uint16_t)((uint16_t)(__usc0__) | (uint16_t)BOVER1(__usc1__))) -#define BMAKE32(__usc3__,__usc2__,__usc1__,__usc0__) ((uint32_t)((uint32_t)(__usc0__) | (uint32_t)BOVER1(__usc1__) | (uint32_t)BOVER2(__usc2__) | (uint32_t)BOVER3(__usc3__))) -#define BMAKE64(__usc7__,__usc6__,__usc5__,__usc4__,__usc3__,__usc2__,__usc1__,__usc0__) ((uint64_t)((uint64_t)__usc0__ | (uint64_t)BOVER1(__usc1__) | (uint64_t)BOVER2(__usc2__) | (uint64_t)BOVER3(__usc3__) | (uint64_t)BOVER4(__usc4__) | (uint64_t)BOVER5(__usc5__) | (uint64_t)BOVER6(__usc6__) | (uint64_t)BOVER1(__usc7__))) -#endif - -/* - * Debug macros: Strings are stored in progmem (flash) instead of RAM. - */ -#define USBTRACE(s) (Notify(PSTR(s), 0x80)) -#define USBTRACE1(s,l) (Notify(PSTR(s), l)) -#define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80)) -#define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l)) - - -#endif /* MACROS_H */ - diff --git a/test/libraries/USBHost/src/message.cpp b/test/libraries/USBHost/src/message.cpp deleted file mode 100644 index bdcdd183..00000000 --- a/test/libraries/USBHost/src/message.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#include "Usb.h" -// 0x80 is the default (i.e. trace) to turn off set this global to something lower. -// this allows for 126 other debugging levels. -// TO-DO: Allow assignment to a different serial port by software -int UsbDEBUGlvl = 0x80; - -void E_Notifyc(char c, int lvl) { - if(UsbDEBUGlvl < lvl) return; -#if defined(ARDUINO) && ARDUINO >=100 - USB_HOST_SERIAL.print(c); -#else - USB_HOST_SERIAL.print(c, BYTE); -#endif - //USB_HOST_SERIAL.flush(); -} - -void E_Notify(char const * msg, int lvl) { - if(UsbDEBUGlvl < lvl) return; - if(!msg) return; - char c; - - while((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl); -} - -void E_NotifyStr(char const * msg, int lvl) { - if(UsbDEBUGlvl < lvl) return; - if(!msg) return; - char c; - - while((c = *msg++)) E_Notifyc(c, lvl); -} - -void E_Notify(uint8_t b, int lvl) { - if(UsbDEBUGlvl < lvl) return; -#if defined(ARDUINO) && ARDUINO >=100 - USB_HOST_SERIAL.print(b); -#else - USB_HOST_SERIAL.print(b, DEC); -#endif - //USB_HOST_SERIAL.flush(); -} - -void E_Notify(double d, int lvl) { - if(UsbDEBUGlvl < lvl) return; - USB_HOST_SERIAL.print(d); - //USB_HOST_SERIAL.flush(); -} - -#ifdef DEBUG_USB_HOST - -void NotifyFailGetDevDescr(void) { - Notify(PSTR("\r\ngetDevDescr "), 0x80); -} - -void NotifyFailSetDevTblEntry(void) { - Notify(PSTR("\r\nsetDevTblEn "), 0x80); -} - -void NotifyFailGetConfDescr(void) { - Notify(PSTR("\r\ngetConf "), 0x80); -} - -void NotifyFailSetConfDescr(void) { - Notify(PSTR("\r\nsetConf "), 0x80); -} - -void NotifyFailGetDevDescr(uint8_t reason) { - NotifyFailGetDevDescr(); - NotifyFail(reason); -} - -void NotifyFailSetDevTblEntry(uint8_t reason) { - NotifyFailSetDevTblEntry(); - NotifyFail(reason); - -} - -void NotifyFailGetConfDescr(uint8_t reason) { - NotifyFailGetConfDescr(); - NotifyFail(reason); -} - -void NotifyFailSetConfDescr(uint8_t reason) { - NotifyFailSetConfDescr(); - NotifyFail(reason); -} - -void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID) { - Notify(PSTR("\r\nUnknown Device Connected - VID: "), 0x80); - D_PrintHex (VID, 0x80); - Notify(PSTR(" PID: "), 0x80); - D_PrintHex (PID, 0x80); -} - -void NotifyFail(uint8_t rcode) { - D_PrintHex (rcode, 0x80); - Notify(PSTR("\r\n"), 0x80); -} -#endif diff --git a/test/libraries/USBHost/src/message.h b/test/libraries/USBHost/src/message.h deleted file mode 100644 index c26628e7..00000000 --- a/test/libraries/USBHost/src/message.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__MESSAGE_H__) -#error "Never include message.h directly; include Usb.h instead" -#else -#define __MESSAGE_H__ - -extern int UsbDEBUGlvl; - -void E_Notify(char const * msg, int lvl); -void E_Notify(uint8_t b, int lvl); -void E_NotifyStr(char const * msg, int lvl); -void E_Notifyc(char c, int lvl); - -#ifdef DEBUG_USB_HOST -#define Notify E_Notify -#define NotifyStr E_NotifyStr -#define Notifyc E_Notifyc -void NotifyFailGetDevDescr(uint8_t reason); -void NotifyFailSetDevTblEntry(uint8_t reason); -void NotifyFailGetConfDescr(uint8_t reason); -void NotifyFailSetConfDescr(uint8_t reason); -void NotifyFailGetDevDescr(void); -void NotifyFailSetDevTblEntry(void); -void NotifyFailGetConfDescr(void); -void NotifyFailSetConfDescr(void); -void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID); -void NotifyFail(uint8_t rcode); -#else -#define Notify(...) ((void)0) -#define NotifyStr(...) ((void)0) -#define Notifyc(...) ((void)0) -#define NotifyFailGetDevDescr(...) ((void)0) -#define NotifyFailSetDevTblEntry(...) ((void)0) -#define NotifyFailGetConfDescr(...) ((void)0) -#define NotifyFailGetDevDescr(...) ((void)0) -#define NotifyFailSetDevTblEntry(...) ((void)0) -#define NotifyFailGetConfDescr(...) ((void)0) -#define NotifyFailSetConfDescr(...) ((void)0) -#define NotifyFailUnknownDevice(...) ((void)0) -#define NotifyFail(...) ((void)0) -#endif - -template -void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) { -#ifdef DEBUG_USB_HOST - Notify(msg, level); - Notify(PSTR(": "), level); - D_PrintHex (rcode, level); - Notify(PSTR("\r\n"), level); -#endif -} - -template -void ErrorMessage(char const * msg, ERROR_TYPE rcode = 0) { -#ifdef DEBUG_USB_HOST - Notify(msg, 0x80); - Notify(PSTR(": "), 0x80); - D_PrintHex (rcode, 0x80); - Notify(PSTR("\r\n"), 0x80); -#endif -} - -#endif // __MESSAGE_H__ diff --git a/test/libraries/USBHost/src/parsetools.cpp b/test/libraries/USBHost/src/parsetools.cpp deleted file mode 100644 index 00ca9e64..00000000 --- a/test/libraries/USBHost/src/parsetools.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ -#include "Usb.h" - -bool MultiByteValueParser::Parse(uint8_t **pp, uint32_t *pcntdn) { - if(!pBuf) { - Notify(PSTR("Buffer pointer is NULL!\r\n"), 0x80); - return false; - } - for (; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++) - pBuf[valueSize - countDown] = (**pp); - - if(countDown) - return false; - - countDown = valueSize; - return true; -} - -bool PTPListParser::Parse(uint8_t **pp, uint32_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me) { - switch(nStage) { - case 0: - pBuf->valueSize = lenSize; - theParser.Initialize(pBuf); - nStage = 1; - - case 1: - if(!theParser.Parse(pp, pcntdn)) - return false; - - arLen = 0; - arLen = (pBuf->valueSize >= 4) ? *((uint32_t*)pBuf->pValue) : (uint32_t)(*((uint16_t*)pBuf->pValue)); - arLenCntdn = arLen; - nStage = 2; - - case 2: - pBuf->valueSize = valSize; - theParser.Initialize(pBuf); - nStage = 3; - - case 3: - for(; arLenCntdn; arLenCntdn--) { - if(!theParser.Parse(pp, pcntdn)) - return false; - - if(pf) - pf(pBuf, (arLen - arLenCntdn), me); - } - - nStage = 0; - } - return true; -} diff --git a/test/libraries/USBHost/src/parsetools.h b/test/libraries/USBHost/src/parsetools.h deleted file mode 100644 index d4633589..00000000 --- a/test/libraries/USBHost/src/parsetools.h +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(__PARSETOOLS_H__) -#error "Never include parsetools.h directly; include Usb.h instead" -#else -#define __PARSETOOLS_H__ - -#include -//#include "Arduino.h" - -struct MultiValueBuffer { - uint8_t valueSize; - void *pValue; -}; - -class MultiByteValueParser { - uint8_t *pBuf; - uint32_t countDown; - uint32_t valueSize; - -public: - - MultiByteValueParser() : pBuf(NULL), countDown(0), valueSize(0) { - }; - - const uint8_t* GetBuffer() { - return pBuf; - }; - - void Initialize(MultiValueBuffer * const pbuf) { - pBuf = (uint8_t*)pbuf->pValue; - countDown = valueSize = pbuf->valueSize; - }; - - bool Parse(uint8_t **pp, uint32_t *pcntdn); -}; - -class ByteSkipper { - uint8_t *pBuf; - uint32_t nStage; - uint32_t countDown; - -public: - - ByteSkipper() : pBuf(NULL), nStage(0), countDown(0) { - }; - - void Initialize(MultiValueBuffer *pbuf) { - pBuf = (uint8_t*)pbuf->pValue; - countDown = 0; - }; - - bool Skip(uint8_t **pp, uint32_t *pcntdn, uint32_t bytes_to_skip) { - switch(nStage) { - case 0: - countDown = bytes_to_skip; - nStage++; - case 1: - for(; countDown && (*pcntdn); countDown--, (*pp)++, (*pcntdn)--); - - if(!countDown) - nStage = 0; - }; - return (!countDown); - }; -}; - -// Pointer to a callback function triggered for each element of PTP array when used with PTPArrayParser -typedef void (*PTP_ARRAY_EL_FUNC)(const MultiValueBuffer * const p, uint32_t count, const void *me); - -class PTPListParser { -public: - - enum ParseMode { - modeArray, modeRange/*, modeEnum*/ - }; - -private: - uint32_t nStage; - uint32_t enStage; - - uint32_t arLen; - uint32_t arLenCntdn; - - uint32_t lenSize; // size of the array length field in bytes - uint32_t valSize; // size of the array element in bytes - - MultiValueBuffer *pBuf; - - // The only parser for both size and array element parsing - MultiByteValueParser theParser; - - uint32_t /*ParseMode*/ prsMode; - -public: - - PTPListParser() : - nStage(0), - enStage(0), - arLen(0), - arLenCntdn(0), - lenSize(0), - valSize(0), - pBuf(NULL), - prsMode(modeArray) { - }; - - void Initialize(const uint32_t len_size, const uint32_t val_size, MultiValueBuffer * const p, const uint32_t mode = modeArray) { - pBuf = p; - lenSize = len_size; - valSize = val_size; - prsMode = mode; - - if(prsMode == modeRange) { - arLenCntdn = arLen = 3; - nStage = 2; - } else { - arLenCntdn = arLen = 0; - nStage = 0; - } - enStage = 0; - theParser.Initialize(p); - }; - - bool Parse(uint8_t **pp, uint32_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me = NULL); -}; - -#endif // __PARSETOOLS_H__ diff --git a/test/libraries/USBHost/src/printhex.h b/test/libraries/USBHost/src/printhex.h deleted file mode 100644 index 369d7e1f..00000000 --- a/test/libraries/USBHost/src/printhex.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ - -#if !defined(_usb_h_) || defined(__PRINTHEX_H__) -#error "Never include printhex.h directly; include Usb.h instead" -#else -#define __PRINTHEX_H__ - -void E_Notifyc(char c, int lvl); - -template -void PrintHex(T val, int lvl) { - int num_nibbles = sizeof (T) * 2; - - do { - char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); - if(v > 57) v += 7; - E_Notifyc(v, lvl); - } while(--num_nibbles); -} - -template -void PrintBin(T val, int lvl) { - for(T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1) - if(val & mask) - E_Notifyc('1', lvl); - else - E_Notifyc('0', lvl); -} - -template -void SerialPrintHex(T val) { - int num_nibbles = sizeof (T) * 2; - - do { - char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f); - if(v > 57) v += 7; - USB_HOST_SERIAL.print(v); - } while(--num_nibbles); -} - -template -void PrintHex2(Print *prn, T val) { - T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2)); - - while(mask > 1) { - if(val < mask) - prn->print("0"); - - mask >>= 4; - } - prn->print((T)val, HEX); -} - -template void D_PrintHex(T val, int lvl) { -#ifdef DEBUG_USB_HOST - PrintHex (val, lvl); -#endif -} - -template -void D_PrintBin(T val, int lvl) { -#ifdef DEBUG_USB_HOST - PrintBin (val, lvl); -#endif -} - - - -#endif // __PRINTHEX_H__ diff --git a/test/libraries/USBHost/src/sink_parser.h b/test/libraries/USBHost/src/sink_parser.h deleted file mode 100644 index a23637d2..00000000 --- a/test/libraries/USBHost/src/sink_parser.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(_usb_h_) || defined(__SINK_PARSER_H__) -#error "Never include hexdump.h directly; include Usb.h instead" -#else -#define __SINK_PARSER_H__ - -extern int UsbDEBUGlvl; - -// This parser does absolutely nothing with the data, just swallows it. - -template -class SinkParser : public BASE_CLASS { -public: - - SinkParser() { - }; - - void Initialize() { - }; - - void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) { - }; -}; - - -#endif // __HEXDUMP_H__ diff --git a/test/libraries/USBHost/src/usb_ch9.h b/test/libraries/USBHost/src/usb_ch9.h deleted file mode 100644 index 09dd94b9..00000000 --- a/test/libraries/USBHost/src/usb_ch9.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com -*/ - -#if !defined(_usb_h_) || defined(_ch9_h_) -#error "Never include usb_ch9.h directly; include Usb.h instead" -#else - -/* USB chapter 9 structures */ -#define _ch9_h_ - -#include - -/* Misc.USB constants */ -#define DEV_DESCR_LEN 18 //device descriptor length -#define CONF_DESCR_LEN 9 //configuration descriptor length -#define INTR_DESCR_LEN 9 //interface descriptor length -#define EP_DESCR_LEN 7 //endpoint descriptor length - -/* Standard Device Requests */ - -#define USB_REQUEST_GET_STATUS 0 // Standard Device Request - GET STATUS -#define USB_REQUEST_CLEAR_FEATURE 1 // Standard Device Request - CLEAR FEATURE -#define USB_REQUEST_SET_FEATURE 3 // Standard Device Request - SET FEATURE -#define USB_REQUEST_SET_ADDRESS 5 // Standard Device Request - SET ADDRESS -#define USB_REQUEST_GET_DESCRIPTOR 6 // Standard Device Request - GET DESCRIPTOR -#define USB_REQUEST_SET_DESCRIPTOR 7 // Standard Device Request - SET DESCRIPTOR -#define USB_REQUEST_GET_CONFIGURATION 8 // Standard Device Request - GET CONFIGURATION -#define USB_REQUEST_SET_CONFIGURATION 9 // Standard Device Request - SET CONFIGURATION -#define USB_REQUEST_GET_INTERFACE 10 // Standard Device Request - GET INTERFACE -#define USB_REQUEST_SET_INTERFACE 11 // Standard Device Request - SET INTERFACE -#define USB_REQUEST_SYNCH_FRAME 12 // Standard Device Request - SYNCH FRAME - -#define USB_FEATURE_ENDPOINT_HALT 0 // CLEAR/SET FEATURE - Endpoint Halt -#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // CLEAR/SET FEATURE - Device remote wake-up -#define USB_FEATURE_TEST_MODE 2 // CLEAR/SET FEATURE - Test mode - -/* Setup Data Constants */ - -#define USB_SETUP_HOST_TO_DEVICE 0x00 // Device Request bmRequestType transfer direction - host to device transfer -#define USB_SETUP_DEVICE_TO_HOST 0x80 // Device Request bmRequestType transfer direction - device to host transfer -#define USB_SETUP_TYPE_STANDARD 0x00 // Device Request bmRequestType type - standard -#define USB_SETUP_TYPE_CLASS 0x20 // Device Request bmRequestType type - class -#define USB_SETUP_TYPE_VENDOR 0x40 // Device Request bmRequestType type - vendor -#define USB_SETUP_RECIPIENT_DEVICE 0x00 // Device Request bmRequestType recipient - device -#define USB_SETUP_RECIPIENT_INTERFACE 0x01 // Device Request bmRequestType recipient - interface -#define USB_SETUP_RECIPIENT_ENDPOINT 0x02 // Device Request bmRequestType recipient - endpoint -#define USB_SETUP_RECIPIENT_OTHER 0x03 // Device Request bmRequestType recipient - other - -/* USB descriptors */ - -#define USB_DESCRIPTOR_DEVICE 0x01 // bDescriptorType for a Device Descriptor. -#define USB_DESCRIPTOR_CONFIGURATION 0x02 // bDescriptorType for a Configuration Descriptor. -#define USB_DESCRIPTOR_STRING 0x03 // bDescriptorType for a String Descriptor. -#define USB_DESCRIPTOR_INTERFACE 0x04 // bDescriptorType for an Interface Descriptor. -#define USB_DESCRIPTOR_ENDPOINT 0x05 // bDescriptorType for an Endpoint Descriptor. -#define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // bDescriptorType for a Device Qualifier. -#define USB_DESCRIPTOR_OTHER_SPEED 0x07 // bDescriptorType for a Other Speed Configuration. -#define USB_DESCRIPTOR_INTERFACE_POWER 0x08 // bDescriptorType for Interface Power. -#define USB_DESCRIPTOR_OTG 0x09 // bDescriptorType for an OTG Descriptor. - -#define HID_DESCRIPTOR_HID 0x21 - - - -/* OTG SET FEATURE Constants */ -#define OTG_FEATURE_B_HNP_ENABLE 3 // SET FEATURE OTG - Enable B device to perform HNP -#define OTG_FEATURE_A_HNP_SUPPORT 4 // SET FEATURE OTG - A device supports HNP -#define OTG_FEATURE_A_ALT_HNP_SUPPORT 5 // SET FEATURE OTG - Another port on the A device supports HNP - -/* USB Endpoint Transfer Types */ -#define USB_TRANSFER_TYPE_CONTROL 0x00 // Endpoint is a control endpoint. -#define USB_TRANSFER_TYPE_ISOCHRONOUS 0x01 // Endpoint is an isochronous endpoint. -#define USB_TRANSFER_TYPE_BULK 0x02 // Endpoint is a bulk endpoint. -#define USB_TRANSFER_TYPE_INTERRUPT 0x03 // Endpoint is an interrupt endpoint. -#define bmUSB_TRANSFER_TYPE 0x03 // bit mask to separate transfer type from ISO attributes - - -/* Standard Feature Selectors for CLEAR_FEATURE Requests */ -#define USB_FEATURE_ENDPOINT_STALL 0 // Endpoint recipient -#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // Device recipient -#define USB_FEATURE_TEST_MODE 2 // Device recipient - -_Pragma("pack(1)") - -/* descriptor data structures */ - -/* Device descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE). - uint16_t bcdUSB; // USB Spec Release Number (BCD). - uint8_t bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bDeviceSubClass; // Subclass code (assigned by the USB-IF). - uint8_t bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bMaxPacketSize0; // Maximum packet size for endpoint 0. - uint16_t idVendor; // Vendor ID (assigned by the USB-IF). - uint16_t idProduct; // Product ID (assigned by the manufacturer). - uint16_t bcdDevice; // Device release number (BCD). - uint8_t iManufacturer; // Index of String Descriptor describing the manufacturer. - uint8_t iProduct; // Index of String Descriptor describing the product. - uint8_t iSerialNumber; // Index of String Descriptor with the device's serial number. - uint8_t bNumConfigurations; // Number of possible configurations. -} USB_DEVICE_DESCRIPTOR; - -/* Configuration descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION). - uint16_t wTotalLength; // Total length of all descriptors for this configuration. - uint8_t bNumInterfaces; // Number of interfaces in this configuration. - uint8_t bConfigurationValue; // Value of this configuration (1 based). - uint8_t iConfiguration; // Index of String Descriptor describing the configuration. - uint8_t bmAttributes; // Configuration characteristics. - uint8_t bMaxPower; // Maximum power consumed by this configuration. -} USB_CONFIGURATION_DESCRIPTOR; - -/* Interface descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE). - uint8_t bInterfaceNumber; // Number of this interface (0 based). - uint8_t bAlternateSetting; // Value of this alternate interface setting. - uint8_t bNumEndpoints; // Number of endpoints in this interface. - uint8_t bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t bInterfaceSubClass; // Subclass code (assigned by the USB-IF). - uint8_t bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific. - uint8_t iInterface; // Index of String Descriptor describing the interface. -} USB_INTERFACE_DESCRIPTOR; - -/* Endpoint descriptor structure */ -typedef struct { - uint8_t bLength; // Length of this descriptor. - uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT). - uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN). - uint8_t bmAttributes; // Endpoint transfer type. - uint16_t wMaxPacketSize; // Maximum packet size. - uint8_t bInterval; // Polling interval in frames. -} USB_ENDPOINT_DESCRIPTOR; - - -/* HID descriptor */ -typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bcdHID; // HID class specification release - uint8_t bCountryCode; - uint8_t bNumDescriptors; // Number of additional class specific descriptors - uint8_t bDescrType; // Type of class descriptor - uint16_t wDescriptorLength; // Total size of the Report descriptor -} USB_HID_DESCRIPTOR; - -typedef struct { - uint8_t bDescrType; // Type of class descriptor - uint16_t wDescriptorLength; // Total size of the Report descriptor -} HID_CLASS_DESCRIPTOR_LEN_AND_TYPE; - -_Pragma("pack()") - -#endif // _ch9_h_ - diff --git a/test/libraries/USBHost/src/usbhub.cpp b/test/libraries/USBHost/src/usbhub.cpp deleted file mode 100644 index 55d5bc1f..00000000 --- a/test/libraries/USBHost/src/usbhub.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#include "usbhub.h" -#include "delay.h" - -bool USBHub::bResetInitiated = false; - -USBHub::USBHub(USBHost *p) : -pUsb(p), -bAddress(0), -bNbrPorts(0), -//bInitState(0), -qNextPollTime(0), -bPollEnable(false) { - epInfo[0].epAddr = 0; - epInfo[0].maxPktSize = 8; - epInfo[0].epAttribs = 0; - epInfo[0].bmNakPower = USB_NAK_MAX_POWER; - - epInfo[1].epAddr = 1; - epInfo[1].maxPktSize = 8; //kludge - epInfo[1].epAttribs = 0; - epInfo[1].bmNakPower = USB_NAK_NOWAIT; - - if(pUsb) - pUsb->RegisterDeviceClass(this); -} - -uint32_t USBHub::Init(uint32_t parent, uint32_t port, uint32_t lowspeed) { - uint8_t buf[32]; - USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast(buf); - HubDescriptor* hd = reinterpret_cast(buf); - USB_CONFIGURATION_DESCRIPTOR * ucd = reinterpret_cast(buf); - uint32_t rcode; - UsbDeviceDefinition *p = NULL; - EpInfo *oldep_ptr = NULL; - uint32_t len = 0; - uint32_t cd_len = 0; - - //USBTRACE("\r\nHub Init Start "); - //D_PrintHex (bInitState, 0x80); - - AddressPool &addrPool = pUsb->GetAddressPool(); - - //switch (bInitState) { - // case 0: - if(bAddress) - return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE; - - // Get pointer to pseudo device with address 0 assigned - p = addrPool.GetUsbDevicePtr(0); - - if(!p) - return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL; - - if(!p->epinfo) - return USB_ERROR_EPINFO_IS_NULL; - - // Save old pointer to EP_RECORD of address 0 - oldep_ptr = p->epinfo; - - // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence - p->epinfo = epInfo; - - p->lowspeed = lowspeed; - - // Get device descriptor - rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf); - - p->lowspeed = false; - - if(!rcode) - len = (buf[0] > 32) ? 32 : buf[0]; - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - return rcode; - } - - // Extract device class from device descriptor - // If device class is not a hub return - if(udd->bDeviceClass != 0x09) - return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; - - // Allocate new address according to device class - bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port); - - if(!bAddress) - return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL; - - // Extract Max Packet Size from the device descriptor - epInfo[0].maxPktSize = udd->bMaxPacketSize0; - - // Assign new address to the device - rcode = pUsb->setAddr(0, 0, bAddress); - - if(rcode) { - // Restore p->epinfo - p->epinfo = oldep_ptr; - addrPool.FreeAddress(bAddress); - bAddress = 0; - return rcode; - } - - //USBTRACE2("\r\nHub address: ", bAddress ); - - // Restore p->epinfo - p->epinfo = oldep_ptr; - - if(len) - rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf); - - if(rcode) - goto FailGetDevDescr; - - // Assign epInfo to epinfo pointer - rcode = pUsb->setEpInfoEntry(bAddress, 2, epInfo); - - if(rcode) - goto FailSetDevTblEntry; - - // bInitState = 1; - - // case 1: - // Get hub descriptor - rcode = GetHubDescriptor(0, 8, buf); - - if(rcode) - goto FailGetHubDescr; - - // Save number of ports for future use - bNbrPorts = hd->bNbrPorts; - - // bInitState = 2; - - // case 2: - // Read configuration Descriptor in Order To Obtain Proper Configuration Value - rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf); - - if(!rcode) { - cd_len = ucd->wTotalLength; - rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf); - } - if(rcode) - goto FailGetConfDescr; - - // The following code is of no practical use in real life applications. - // It only intended for the usb protocol sniffer to properly parse hub-class requests. - { - uint8_t buf2[24]; - - rcode = pUsb->getConfDescr(bAddress, 0, buf[0], 0, buf2); - - if(rcode) - goto FailGetConfDescr; - } - - // Set Configuration Value - rcode = pUsb->setConf(bAddress, 0, buf[5]); - - if(rcode) - goto FailSetConfDescr; - - // bInitState = 3; - - // case 3: - // Power on all ports - for(uint32_t j = 1; j <= bNbrPorts; j++) - SetPortFeature(HUB_FEATURE_PORT_POWER, j, 0); //HubPortPowerOn(j); - - pUsb->SetHubPreMask(); - bPollEnable = true; - // bInitState = 0; - //} - //bInitState = 0; - //USBTRACE("...OK\r\n"); - return 0; - - // Oleg, No debugging?? -- xxxajk -FailGetDevDescr: - goto Fail; - -FailSetDevTblEntry: - goto Fail; - -FailGetHubDescr: - goto Fail; - -FailGetConfDescr: - goto Fail; - -FailSetConfDescr: - goto Fail; - -Fail: - USBTRACE("...FAIL\r\n"); - return rcode; -} - -uint32_t USBHub::Release() { - pUsb->GetAddressPool().FreeAddress(bAddress); - - if(bAddress == 0x41) - pUsb->SetHubPreMask(); - - bAddress = 0; - bNbrPorts = 0; - qNextPollTime = 0; - bPollEnable = false; - return 0; -} - -uint32_t USBHub::Poll() { - uint32_t rcode = 0; - - if(!bPollEnable) - return 0; - - if(((long)(millis() - qNextPollTime) >= 0L)) { - rcode = CheckHubStatus(); - qNextPollTime = millis() + 100; - } - return rcode; -} - -uint32_t USBHub::CheckHubStatus() { - uint32_t rcode; - uint8_t buf[8]; - uint32_t read = 1; - - rcode = pUsb->inTransfer(bAddress, 1, (uint8_t*)&read, buf); - - if(rcode) - return rcode; - - //if (buf[0] & 0x01) // Hub Status Change - //{ - // pUsb->PrintHubStatus(addr); - // rcode = GetHubStatus(1, 0, 1, 4, buf); - // if (rcode) - // { - // USB_HOST_SERIAL.print("GetHubStatus Error"); - // USB_HOST_SERIAL.println(rcode, HEX); - // return rcode; - // } - //} - for(uint32_t port = 1, mask = 0x02; port < 8; mask <<= 1, port++) { - if(buf[0] & mask) { - HubEvent evt; - evt.bmEvent = 0; - - rcode = GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) - continue; - - rcode = PortStatusChange(port, evt); - - if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) - return 0; - - if(rcode) - return rcode; - } - } // for - - for(uint32_t port = 1; port <= bNbrPorts; port++) { - HubEvent evt; - evt.bmEvent = 0; - - rcode = GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) - continue; - - if((evt.bmStatus & bmHUB_PORT_STATE_CHECK_DISABLED) != bmHUB_PORT_STATE_DISABLED) - continue; - - // Emulate connection event for the port - evt.bmChange |= bmHUB_PORT_STATUS_C_PORT_CONNECTION; - - rcode = PortStatusChange(port, evt); - - if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET) - return 0; - - if(rcode) - return rcode; - } // for - return 0; -} - -void USBHub::ResetHubPort(uint32_t port) { - HubEvent evt; - evt.bmEvent = 0; - uint8_t rcode; - - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0); - - - for(int i = 0; i < 3; i++) { - rcode = GetPortStatus(port, 4, evt.evtBuff); - if(rcode) break; // Some kind of error, bail. - if(evt.bmEvent == bmHUB_PORT_EVENT_RESET_COMPLETE || evt.bmEvent == bmHUB_PORT_EVENT_LS_RESET_COMPLETE) { - break; - } - delay(100); // simulate polling. - } - ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - delay(20); -} - -uint32_t USBHub::PortStatusChange(uint32_t port, HubEvent &evt) { - switch(evt.bmEvent) { - // Device connected event - case bmHUB_PORT_EVENT_CONNECT: - case bmHUB_PORT_EVENT_LS_CONNECT: - if(bResetInitiated) - return 0; - - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0); - bResetInitiated = true; - return HUB_ERROR_PORT_HAS_BEEN_RESET; - - // Device disconnected event - case bmHUB_PORT_EVENT_DISCONNECT: - ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - bResetInitiated = false; - - UsbDeviceAddress a; - a.devAddress = 0; - a.bmHub = 0; - a.bmParent = bAddress; - a.bmAddress = port; - pUsb->ReleaseDevice(a.devAddress); - return 0; - - // Reset complete event - case bmHUB_PORT_EVENT_RESET_COMPLETE: - case bmHUB_PORT_EVENT_LS_RESET_COMPLETE: - ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0); - ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0); - - delay(20); - - a.devAddress = bAddress; - - pUsb->Configuring(a.bmAddress, port, (evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED)); - bResetInitiated = false; - break; - - } // switch (evt.bmEvent) - return 0; -} - -void PrintHubPortStatus(USBHub *hubptr, uint32_t addr, uint32_t port, uint32_t print_changes) { - uint8_t rcode = 0; - HubEvent evt; - - rcode = hubptr->GetPortStatus(port, 4, evt.evtBuff); - - if(rcode) { - USB_HOST_SERIAL.println("ERROR!"); - return; - } - USB_HOST_SERIAL.print("\r\nPort "); - USB_HOST_SERIAL.println(port, DEC); - - USB_HOST_SERIAL.println("Status"); - USB_HOST_SERIAL.print("CONNECTION:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_CONNECTION) > 0, DEC); - USB_HOST_SERIAL.print("ENABLE:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_ENABLE) > 0, DEC); - USB_HOST_SERIAL.print("SUSPEND:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_SUSPEND) > 0, DEC); - USB_HOST_SERIAL.print("OVER_CURRENT:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_OVER_CURRENT) > 0, DEC); - USB_HOST_SERIAL.print("RESET:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_RESET) > 0, DEC); - USB_HOST_SERIAL.print("POWER:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_POWER) > 0, DEC); - USB_HOST_SERIAL.print("LOW_SPEED:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED) > 0, DEC); - USB_HOST_SERIAL.print("HIGH_SPEED:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_HIGH_SPEED) > 0, DEC); - USB_HOST_SERIAL.print("TEST:\t\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_TEST) > 0, DEC); - USB_HOST_SERIAL.print("INDICATOR:\t"); - USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_INDICATOR) > 0, DEC); - - if(!print_changes) - return; - - USB_HOST_SERIAL.println("\r\nChange"); - USB_HOST_SERIAL.print("CONNECTION:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_CONNECTION) > 0, DEC); - USB_HOST_SERIAL.print("ENABLE:\t\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_ENABLE) > 0, DEC); - USB_HOST_SERIAL.print("SUSPEND:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_SUSPEND) > 0, DEC); - USB_HOST_SERIAL.print("OVER_CURRENT:\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT) > 0, DEC); - USB_HOST_SERIAL.print("RESET:\t\t"); - USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_RESET) > 0, DEC); -} diff --git a/test/libraries/USBHost/src/usbhub.h b/test/libraries/USBHost/src/usbhub.h deleted file mode 100644 index 6a80a123..00000000 --- a/test/libraries/USBHost/src/usbhub.h +++ /dev/null @@ -1,252 +0,0 @@ -/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved. - -This software may be distributed and modified under the terms of the GNU -General Public License version 2 (GPL2) as published by the Free Software -Foundation and appearing in the file GPL2.TXT included in the packaging of -this file. Please note that GPL2 Section 2[b] requires that all works based -on this software must also be made publicly available under the terms of -the GPL2 ("Copyleft"). - -Contact information -------------------- - -Circuits At Home, LTD -Web : http://www.circuitsathome.com -e-mail : support@circuitsathome.com - */ -#if !defined(__USBHUB_H__) -#define __USBHUB_H__ - -#include "Usb.h" - -#define USB_DESCRIPTOR_HUB 0x09 // Hub descriptor type - -// Hub Requests -#define bmREQ_CLEAR_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_CLEAR_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_CLEAR_TT_BUFFER USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_GET_HUB_DESCRIPTOR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_GET_HUB_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_GET_PORT_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_RESET_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_SET_HUB_DESCRIPTOR USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_SET_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE -#define bmREQ_SET_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_GET_TT_STATE USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER -#define bmREQ_STOP_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER - -// Hub Class Requests -#define HUB_REQUEST_CLEAR_TT_BUFFER 8 -#define HUB_REQUEST_RESET_TT 9 -#define HUB_REQUEST_GET_TT_STATE 10 -#define HUB_REQUEST_STOP_TT 11 - -// Hub Features -#define HUB_FEATURE_C_HUB_LOCAL_POWER 0 -#define HUB_FEATURE_C_HUB_OVER_CURRENT 1 -#define HUB_FEATURE_PORT_CONNECTION 0 -#define HUB_FEATURE_PORT_ENABLE 1 -#define HUB_FEATURE_PORT_SUSPEND 2 -#define HUB_FEATURE_PORT_OVER_CURRENT 3 -#define HUB_FEATURE_PORT_RESET 4 -#define HUB_FEATURE_PORT_POWER 8 -#define HUB_FEATURE_PORT_LOW_SPEED 9 -#define HUB_FEATURE_C_PORT_CONNECTION 16 -#define HUB_FEATURE_C_PORT_ENABLE 17 -#define HUB_FEATURE_C_PORT_SUSPEND 18 -#define HUB_FEATURE_C_PORT_OVER_CURRENT 19 -#define HUB_FEATURE_C_PORT_RESET 20 -#define HUB_FEATURE_PORT_TEST 21 -#define HUB_FEATURE_PORT_INDICATOR 22 - -// Hub Port Test Modes -#define HUB_PORT_TEST_MODE_J 1 -#define HUB_PORT_TEST_MODE_K 2 -#define HUB_PORT_TEST_MODE_SE0_NAK 3 -#define HUB_PORT_TEST_MODE_PACKET 4 -#define HUB_PORT_TEST_MODE_FORCE_ENABLE 5 - -// Hub Port Indicator Color -#define HUB_PORT_INDICATOR_AUTO 0 -#define HUB_PORT_INDICATOR_AMBER 1 -#define HUB_PORT_INDICATOR_GREEN 2 -#define HUB_PORT_INDICATOR_OFF 3 - -// Hub Port Status Bitmasks -#define bmHUB_PORT_STATUS_PORT_CONNECTION 0x0001 -#define bmHUB_PORT_STATUS_PORT_ENABLE 0x0002 -#define bmHUB_PORT_STATUS_PORT_SUSPEND 0x0004 -#define bmHUB_PORT_STATUS_PORT_OVER_CURRENT 0x0008 -#define bmHUB_PORT_STATUS_PORT_RESET 0x0010 -#define bmHUB_PORT_STATUS_PORT_POWER 0x0100 -#define bmHUB_PORT_STATUS_PORT_LOW_SPEED 0x0200 -#define bmHUB_PORT_STATUS_PORT_HIGH_SPEED 0x0400 -#define bmHUB_PORT_STATUS_PORT_TEST 0x0800 -#define bmHUB_PORT_STATUS_PORT_INDICATOR 0x1000 - -// Hub Port Status Change Bitmasks (used one byte instead of two) -#define bmHUB_PORT_STATUS_C_PORT_CONNECTION 0x0001 -#define bmHUB_PORT_STATUS_C_PORT_ENABLE 0x0002 -#define bmHUB_PORT_STATUS_C_PORT_SUSPEND 0x0004 -#define bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT 0x0008 -#define bmHUB_PORT_STATUS_C_PORT_RESET 0x0010 - -// Hub Status Bitmasks (used one byte instead of two) -#define bmHUB_STATUS_LOCAL_POWER_SOURCE 0x01 -#define bmHUB_STATUS_OVER_CURRENT 0x12 - -// Hub Status Change Bitmasks (used one byte instead of two) -#define bmHUB_STATUS_C_LOCAL_POWER_SOURCE 0x01 -#define bmHUB_STATUS_C_OVER_CURRENT 0x12 - - -// Hub Port Configuring Substates -#define USB_STATE_HUB_PORT_CONFIGURING 0xb0 -#define USB_STATE_HUB_PORT_POWERED_OFF 0xb1 -#define USB_STATE_HUB_PORT_WAIT_FOR_POWER_GOOD 0xb2 -#define USB_STATE_HUB_PORT_DISCONNECTED 0xb3 -#define USB_STATE_HUB_PORT_DISABLED 0xb4 -#define USB_STATE_HUB_PORT_RESETTING 0xb5 -#define USB_STATE_HUB_PORT_ENABLED 0xb6 - -// Additional Error Codes -#define HUB_ERROR_PORT_HAS_BEEN_RESET 0xb1 - -// The bit mask to check for all necessary state bits -#define bmHUB_PORT_STATUS_ALL_MAIN ((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE | bmHUB_PORT_STATUS_C_PORT_SUSPEND | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND) - -// Bit mask to check for DISABLED state in HubEvent::bmStatus field -#define bmHUB_PORT_STATE_CHECK_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND) - -// Hub Port States -#define bmHUB_PORT_STATE_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION) - -// Hub Port Events -#define bmHUB_PORT_EVENT_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION) -#define bmHUB_PORT_EVENT_DISCONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER) -#define bmHUB_PORT_EVENT_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION) - -#define bmHUB_PORT_EVENT_LS_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) -#define bmHUB_PORT_EVENT_LS_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) -#define bmHUB_PORT_EVENT_LS_PORT_ENABLED (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED) - -struct HubDescriptor { - uint32_t bDescLength; // descriptor length - uint32_t bDescriptorType; // descriptor type - uint32_t bNbrPorts; // number of ports a hub equiped with - - struct { - uint32_t LogPwrSwitchMode : 2; - uint32_t CompoundDevice : 1; - uint32_t OverCurrentProtectMode : 2; - uint32_t TTThinkTime : 2; - uint32_t PortIndicatorsSupported : 1; - uint32_t Reserved : 24; - } __attribute__((packed)); - - uint32_t bPwrOn2PwrGood; - uint32_t bHubContrCurrent; -} __attribute__((packed)); - -struct HubEvent { - - union { - - struct { - uint32_t bmStatus; // port status bits - uint32_t bmChange; // port status change bits - } __attribute__((packed)); - uint32_t bmEvent; - uint8_t evtBuff[4]; - }; -} __attribute__((packed)); - -class USBHub : USBDeviceConfig { - static bool bResetInitiated; // True when reset is triggered - - USBHost *pUsb; // USB class instance pointer - - EpInfo epInfo[2]; // interrupt endpoint info structure - - uint32_t bAddress; // address - uint32_t bNbrPorts; // number of ports - // uint8_t bInitState; // initialization state variable - uint32_t qNextPollTime; // next poll time - uint32_t bPollEnable; // poll enable flag - - uint32_t CheckHubStatus(); - uint32_t PortStatusChange(uint32_t port, HubEvent &evt); - -public: - USBHub(USBHost *p); - - uint32_t ClearHubFeature(uint32_t fid); - uint32_t ClearPortFeature(uint32_t fid, uint32_t port, uint32_t sel = 0); - uint32_t GetHubDescriptor(uint32_t index, uint32_t nbytes, uint8_t *dataptr); - uint32_t GetHubStatus(uint32_t nbytes, uint8_t* dataptr); - uint32_t GetPortStatus(uint32_t port, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetHubDescriptor(uint32_t port, uint32_t nbytes, uint8_t* dataptr); - uint32_t SetHubFeature(uint32_t fid); - uint32_t SetPortFeature(uint32_t fid, uint32_t port, uint32_t sel = 0); - - void PrintHubStatus(); - - virtual uint32_t Init(uint32_t parent, uint32_t port, uint32_t lowspeed); - virtual uint32_t Release(); - virtual uint32_t Poll(); - virtual void ResetHubPort(uint32_t port); - - virtual uint32_t GetAddress() { - return bAddress; - }; - - virtual uint32_t DEVCLASSOK(uint32_t klass) { - return (klass == 0x09); - } - -}; - -// Clear Hub Feature - -inline uint32_t USBHub::ClearHubFeature(uint32_t fid) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_HUB_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); -} -// Clear Port Feature - -inline uint32_t USBHub::ClearPortFeature(uint32_t fid, uint32_t port, uint32_t sel) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_PORT_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, ((0x0000 | port) | (sel << 8)), 0, 0, NULL, NULL)); -} -// Get Hub Descriptor - -inline uint32_t USBHub::GetHubDescriptor(uint32_t index, uint32_t nbytes, uint8_t *dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_DESCRIPTOR, USB_REQUEST_GET_DESCRIPTOR, index, 0x29, 0, nbytes, nbytes, dataptr, NULL)); -} -// Get Hub Status - -inline uint32_t USBHub::GetHubStatus(uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_STATUS, USB_REQUEST_GET_STATUS, 0, 0, 0x0000, nbytes, nbytes, dataptr, NULL)); -} -// Get Port Status - -inline uint32_t USBHub::GetPortStatus(uint32_t port, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_PORT_STATUS, USB_REQUEST_GET_STATUS, 0, 0, port, nbytes, nbytes, dataptr, NULL)); -} -// Set Hub Descriptor - -inline uint32_t USBHub::SetHubDescriptor(uint32_t port, uint32_t nbytes, uint8_t* dataptr) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_DESCRIPTOR, USB_REQUEST_SET_DESCRIPTOR, 0, 0, port, nbytes, nbytes, dataptr, NULL)); -} -// Set Hub Feature - -inline uint32_t USBHub::SetHubFeature(uint32_t fid) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, 0, 0, 0, NULL, NULL)); -} -// Set Port Feature - -inline uint32_t USBHub::SetPortFeature(uint32_t fid, uint32_t port, uint32_t sel) { - return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_PORT_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, (((0x0000 | sel) << 8) | port), 0, 0, NULL, NULL)); -} - -void PrintHubPortStatus(USBHost *usbptr, uint32_t addr, uint32_t port, uint32_t print_changes = false); - -#endif // __USBHUB_H__ diff --git a/test/libraries/testlib1/testlib1.h b/test/libraries/testlib1/testlib1.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib2/testlib2.h b/test/libraries/testlib2/testlib2.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib3/testlib3.h b/test/libraries/testlib3/testlib3.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/testlib4/testlib4.h b/test/libraries/testlib4/testlib4.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/wronglib/library.properties b/test/libraries/wronglib/library.properties deleted file mode 100644 index b235c667..00000000 --- a/test/libraries/wronglib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=wronglib -version=1.0 -author=Arduino -maintainer=Arduino -sentence=sentence -paragraph=paragraph -url=url -architectures=* -category=Other diff --git a/test/libraries/wronglib/src/.gitkeep b/test/libraries/wronglib/src/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries/wronglib/utility/.gitkeep b/test/libraries/wronglib/utility/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/libraries_loader_test.go b/test/libraries_loader_test.go deleted file mode 100644 index 294f40c9..00000000 --- a/test/libraries_loader_test.go +++ /dev/null @@ -1,304 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "sort" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/libraries" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func extractLibraries(ctx *types.Context) []*libraries.Library { - res := []*libraries.Library{} - for _, lib := range ctx.LibrariesManager.Libraries { - for _, libAlternative := range lib.Alternatives { - res = append(res, libAlternative) - } - } - return res -} -func TestLoadLibrariesAVR(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesManager.LibrariesDir - require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) - - libs := extractLibraries(ctx) - require.Equal(t, 24, len(libs)) - - sort.Sort(ByLibraryName(libs)) - - idx := 0 - - require.Equal(t, "ANewLibrary-master", libs[idx].Name) - - idx++ - require.Equal(t, "Adafruit_PN532", libs[idx].Name) - require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].InstallDir)) - require.True(t, Abs(t, paths.New("downloaded_libraries/Adafruit_PN532")).EquivalentTo(libs[idx].SourceDir)) - require.Equal(t, 1, len(libs[idx].Architectures)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, libs[idx].Architectures[0]) - require.False(t, libs[idx].IsLegacy) - - idx++ - require.Equal(t, "Audio", libs[idx].Name) - - idx++ - require.Equal(t, "Balanduino", libs[idx].Name) - require.True(t, libs[idx].IsLegacy) - - idx++ - bridgeLib := libs[idx] - require.Equal(t, "Bridge", bridgeLib.Name) - require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge")).EquivalentTo(bridgeLib.InstallDir)) - require.True(t, Abs(t, paths.New("downloaded_libraries/Bridge/src")).EquivalentTo(bridgeLib.SourceDir)) - require.Equal(t, 1, len(bridgeLib.Architectures)) - require.Equal(t, constants.LIBRARY_ALL_ARCHS, bridgeLib.Architectures[0]) - require.Equal(t, "Arduino", bridgeLib.Author) - require.Equal(t, "Arduino ", bridgeLib.Maintainer) - - idx++ - require.Equal(t, "CapacitiveSensor", libs[idx].Name) - idx++ - require.Equal(t, "EEPROM", libs[idx].Name) - idx++ - require.Equal(t, "Ethernet", libs[idx].Name) - idx++ - require.Equal(t, "FakeAudio", libs[idx].Name) - idx++ - require.Equal(t, "FastLED", libs[idx].Name) - idx++ - require.Equal(t, "HID", libs[idx].Name) - idx++ - require.Equal(t, "IRremote", libs[idx].Name) - idx++ - require.Equal(t, "Robot_IR_Remote", libs[idx].Name) - idx++ - require.Equal(t, "SPI", libs[idx].Name) - idx++ - require.Equal(t, "SPI", libs[idx].Name) - idx++ - require.Equal(t, "ShouldNotRecurseWithOldLibs", libs[idx].Name) - idx++ - require.Equal(t, "SoftwareSerial", libs[idx].Name) - idx++ - require.Equal(t, "USBHost", libs[idx].Name) - idx++ - require.Equal(t, "Wire", libs[idx].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("Audio.h") - require.Len(t, libs, 2) - sort.Sort(ByLibraryName(libs)) - require.Equal(t, "Audio", libs[0].Name) - require.Equal(t, "FakeAudio", libs[1].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("FakeAudio.h") - require.Len(t, libs, 1) - require.Equal(t, "FakeAudio", libs[0].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("Adafruit_PN532.h") - require.Len(t, libs, 1) - require.Equal(t, "Adafruit_PN532", libs[0].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("IRremote.h") - require.Len(t, libs, 1) - require.Equal(t, "IRremote", libs[0].Name) -} - -func TestLoadLibrariesSAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesManager.LibrariesDir - require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "sam", "libraries")).EquivalentTo(librariesFolders[1].Path)) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) - - libraries := extractLibraries(ctx) - require.Equal(t, 22, len(libraries)) - - sort.Sort(ByLibraryName(libraries)) - - idx := 0 - require.Equal(t, "ANewLibrary-master", libraries[idx].Name) - idx++ - require.Equal(t, "Adafruit_PN532", libraries[idx].Name) - idx++ - require.Equal(t, "Audio", libraries[idx].Name) - idx++ - require.Equal(t, "Balanduino", libraries[idx].Name) - idx++ - require.Equal(t, "Bridge", libraries[idx].Name) - idx++ - require.Equal(t, "CapacitiveSensor", libraries[idx].Name) - idx++ - require.Equal(t, "Ethernet", libraries[idx].Name) - idx++ - require.Equal(t, "FakeAudio", libraries[idx].Name) - idx++ - require.Equal(t, "FastLED", libraries[idx].Name) - idx++ - require.Equal(t, "HID", libraries[idx].Name) - idx++ - require.Equal(t, "IRremote", libraries[idx].Name) - idx++ - require.Equal(t, "Robot_IR_Remote", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "SPI", libraries[idx].Name) - idx++ - require.Equal(t, "ShouldNotRecurseWithOldLibs", libraries[idx].Name) - idx++ - require.Equal(t, "USBHost", libraries[idx].Name) - idx++ - require.Equal(t, "Wire", libraries[idx].Name) - - libs := ctx.LibrariesResolver.AlternativesFor("Audio.h") - require.Len(t, libs, 2) - sort.Sort(ByLibraryName(libs)) - require.Equal(t, "Audio", libs[0].Name) - require.Equal(t, "FakeAudio", libs[1].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("FakeAudio.h") - require.Len(t, libs, 1) - require.Equal(t, "FakeAudio", libs[0].Name) - - libs = ctx.LibrariesResolver.AlternativesFor("IRremote.h") - require.Len(t, libs, 1) - require.Equal(t, "IRremote", libs[0].Name) -} - -func TestLoadLibrariesAVRNoDuplicateLibrariesFolders(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesManager.LibrariesDir - require.Equal(t, 3, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[2].Path)) -} - -func TestLoadLibrariesMyAVRPlatform(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "user_hardware", "downloaded_hardware"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries", filepath.Join("downloaded_hardware", "arduino", "avr", "libraries")), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - } - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.LibrariesLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - librariesFolders := ctx.LibrariesManager.LibrariesDir - require.Equal(t, 4, len(librariesFolders)) - require.True(t, Abs(t, paths.New("downloaded_libraries")).EquivalentTo(librariesFolders[0].Path)) - require.True(t, Abs(t, paths.New("downloaded_hardware", "arduino", "avr", "libraries")).EquivalentTo(librariesFolders[1].Path)) - require.True(t, Abs(t, paths.New("user_hardware", "my_avr_platform", "avr", "libraries")).EquivalentTo(librariesFolders[2].Path)) - require.True(t, Abs(t, paths.New("libraries")).EquivalentTo(librariesFolders[3].Path)) -} diff --git a/test/load_previous_build_options_map_test.go b/test/load_previous_build_options_map_test.go deleted file mode 100644 index 99a445ec..00000000 --- a/test/load_previous_build_options_map_test.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func TestLoadPreviousBuildOptionsMap(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - err := buildPath.Join(constants.BUILD_OPTIONS_FILE).WriteFile([]byte("test")) - NoError(t, err) - - command := builder.LoadPreviousBuildOptionsMap{} - err = command.Run(ctx) - NoError(t, err) - - require.Equal(t, "test", ctx.BuildOptionsJsonPrevious) -} - -func TestLoadPreviousBuildOptionsMapMissingFile(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - command := builder.LoadPreviousBuildOptionsMap{} - err := command.Run(ctx) - NoError(t, err) - - require.Empty(t, ctx.BuildOptionsJsonPrevious) -} diff --git a/test/load_vid_pid_specific_properties_test.go b/test/load_vid_pid_specific_properties_test.go deleted file mode 100644 index 9a6e0335..00000000 --- a/test/load_vid_pid_specific_properties_test.go +++ /dev/null @@ -1,103 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestLoadVIDPIDSpecificPropertiesWhenNoVIDPIDAreProvided(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools", "./tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:micro"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "0x0037", buildProperties.Get("pid.0")) - require.Equal(t, "\"Genuino Micro\"", buildProperties.Get("vid.4.build.usb_product")) - require.Equal(t, "0x8037", buildProperties.Get("build.pid")) -} - -func TestLoadVIDPIDSpecificProperties(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools", "./tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:micro"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - ctx.USBVidPid = "0x2341_0x0237" - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "0x0037", buildProperties.Get("pid.0")) - require.Equal(t, "\"Genuino Micro\"", buildProperties.Get("vid.4.build.usb_product")) - require.Equal(t, "0x2341", buildProperties.Get("build.vid")) - require.Equal(t, "0x8237", buildProperties.Get("build.pid")) -} diff --git a/test/merge_sketch_with_bootloader_test.go b/test/merge_sketch_with_bootloader_test.go deleted file mode 100644 index 2a280fc3..00000000 --- a/test/merge_sketch_with_bootloader_test.go +++ /dev/null @@ -1,206 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestMergeSketchWithBootloader(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - err := buildPath.Join("sketch").MkdirAll() - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = buildPath.Join("sketch", "sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := buildPath.Join("sketch", "sketch.ino.with_bootloader.hex").ReadFile() - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:107E0000112484B714BE81FFF0D085E080938100F7\n")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":0400000300007E007B\n:00000001FF\n")) -} - -func TestMergeSketchWithBootloaderSketchInBuildPath(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - err := buildPath.Join("sketch").MkdirAll() - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = buildPath.Join("sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := buildPath.Join("sketch.ino.with_bootloader.hex").ReadFile() - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:107E0000112484B714BE81FFF0D085E080938100F7\n")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":0400000300007E007B\n:00000001FF\n")) -} - -func TestMergeSketchWithBootloaderWhenNoBootloaderAvailable(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - buildProperties.Remove(constants.BUILD_PROPERTIES_BOOTLOADER_NOBLINK) - buildProperties.Remove(constants.BUILD_PROPERTIES_BOOTLOADER_FILE) - - command := &builder.MergeSketchWithBootloader{} - err := command.Run(ctx) - NoError(t, err) - - exist, err := buildPath.Join("sketch.ino.with_bootloader.hex").ExistCheck() - require.NoError(t, err) - require.False(t, exist) -} - -func TestMergeSketchWithBootloaderPathIsParameterized(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - ToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:mymega:cpu=atmega2560"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - err := buildPath.Join("sketch").MkdirAll() - NoError(t, err) - - fakeSketchHex := "row 1\n" + - "row 2\n" - err = buildPath.Join("sketch", "sketch.ino.hex").WriteFile([]byte(fakeSketchHex)) - NoError(t, err) - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - &builder.MergeSketchWithBootloader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - bytes, err := buildPath.Join("sketch", "sketch.ino.with_bootloader.hex").ReadFile() - NoError(t, err) - mergedSketchHex := string(bytes) - - require.True(t, strings.HasPrefix(mergedSketchHex, "row 1\n:020000023000CC")) - require.True(t, strings.HasSuffix(mergedSketchHex, ":040000033000E000E9\n:00000001FF\n")) -} diff --git a/test/platform_keys_rewrite_loader_test.go b/test/platform_keys_rewrite_loader_test.go deleted file mode 100644 index b091453b..00000000 --- a/test/platform_keys_rewrite_loader_test.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestLoadPlatformKeysRewrite(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_hardware", filepath.Join("..", "hardware"), "hardware"), - } - - commands := []types.Command{ - &builder.PlatformKeysRewriteLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - platformKeysRewrite := ctx.PlatformKeyRewrites - - require.Equal(t, 13, len(platformKeysRewrite.Rewrites)) - require.Equal(t, "compiler.path", platformKeysRewrite.Rewrites[0].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platformKeysRewrite.Rewrites[0].OldValue) - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platformKeysRewrite.Rewrites[0].NewValue) - - require.Equal(t, "tools.avrdude.cmd.path", platformKeysRewrite.Rewrites[1].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/avrdude", platformKeysRewrite.Rewrites[1].OldValue) - require.Equal(t, "{path}/bin/avrdude", platformKeysRewrite.Rewrites[1].NewValue) - - require.Equal(t, "compiler.path", platformKeysRewrite.Rewrites[3].Key) - require.Equal(t, "{runtime.ide.path}/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin/", platformKeysRewrite.Rewrites[3].OldValue) - require.Equal(t, "{runtime.tools.arm-none-eabi-gcc.path}/bin/", platformKeysRewrite.Rewrites[3].NewValue) - - require.Equal(t, "recipe.c.combine.pattern", platformKeysRewrite.Rewrites[5].Key) - require.Equal(t, "\"{compiler.path}{compiler.c.elf.cmd}\" {compiler.c.elf.flags} -mcpu={build.mcu} \"-T{build.variant.path}/{build.ldscript}\" \"-Wl,-Map,{build.path}/{build.project_name}.map\" {compiler.c.elf.extra_flags} -o \"{build.path}/{build.project_name}.elf\" \"-L{build.path}\" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group \"{build.path}/syscalls_sam3.c.o\" {object_files} \"{build.variant.path}/{build.variant_system_lib}\" \"{build.path}/{archive_file}\" -Wl,--end-group -lm -gcc", platformKeysRewrite.Rewrites[5].OldValue) - require.Equal(t, "\"{compiler.path}{compiler.c.elf.cmd}\" {compiler.c.elf.flags} -mcpu={build.mcu} \"-T{build.variant.path}/{build.ldscript}\" \"-Wl,-Map,{build.path}/{build.project_name}.map\" {compiler.c.elf.extra_flags} -o \"{build.path}/{build.project_name}.elf\" \"-L{build.path}\" -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group \"{build.path}/core/syscalls_sam3.c.o\" {object_files} \"{build.variant.path}/{build.variant_system_lib}\" \"{build.path}/{archive_file}\" -Wl,--end-group -lm -gcc", platformKeysRewrite.Rewrites[5].NewValue) -} diff --git a/test/prototypes_adder_test.go b/test/prototypes_adder_test.go deleted file mode 100644 index 4353f7b1..00000000 --- a/test/prototypes_adder_test.go +++ /dev/null @@ -1,950 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestPrototypesAdderBridgeExample(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("downloaded_libraries", "Bridge", "examples", "Bridge", "Bridge.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - ctx.DebugLevel = 10 - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 33 "+quotedSketchLocation+"\nvoid setup();\n#line 46 "+quotedSketchLocation+"\nvoid loop();\n#line 62 "+quotedSketchLocation+"\nvoid process(BridgeClient client);\n#line 82 "+quotedSketchLocation+"\nvoid digitalCommand(BridgeClient client);\n#line 109 "+quotedSketchLocation+"\nvoid analogCommand(BridgeClient client);\n#line 149 "+quotedSketchLocation+"\nvoid modeCommand(BridgeClient client);\n#line 33 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithIfDef(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch2", "SketchWithIfDef.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch2", "SketchWithIfDef.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderBaladuino(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch3", "Baladuino.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch3", "Baladuino.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderCharWithEscapedDoubleQuote(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch4", "CharWithEscapedDoubleQuote.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch4", "CharWithEscapedDoubleQuote.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderIncludeBetweenMultilineComment(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch5", "IncludeBetweenMultilineComment.ino"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch5", "IncludeBetweenMultilineComment.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderLineContinuations(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch6", "/LineContinuations.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch6", "LineContinuations.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderStringWithComment(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch7", "StringWithComment.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch7", "StringWithComment.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithStruct(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch8", "SketchWithStruct.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch8", "SketchWithStruct.preprocessed.txt"), ctx) - obtained := strings.Replace(ctx.Source, "\r\n", "\n", -1) - // ctags based preprocessing removes the space after "dostuff", but this is still OK - // TODO: remove this exception when moving to a more powerful parser - preprocessed = strings.Replace(preprocessed, "void dostuff (A_NEW_TYPE * bar);", "void dostuff(A_NEW_TYPE * bar);", 1) - obtained = strings.Replace(obtained, "void dostuff (A_NEW_TYPE * bar);", "void dostuff(A_NEW_TYPE * bar);", 1) - require.Equal(t, preprocessed, obtained) -} - -func TestPrototypesAdderSketchWithConfig(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_config", "sketch_with_config.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 13 "+quotedSketchLocation+"\nvoid setup();\n#line 17 "+quotedSketchLocation+"\nvoid loop();\n#line 13 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - preprocessed := LoadAndInterpolate(t, filepath.Join("sketch_with_config", "sketch_with_config.preprocessed.txt"), ctx) - require.Equal(t, preprocessed, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchNoFunctionsTwoFiles(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_no_functions_two_files", "main.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_no_functions_two_files", "main.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchNoFunctions(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketch_no_functions", "main.ino"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - sketchLocation := paths.New("sketch_no_functions", "main.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithDefaultArgs(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_default_args", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 4 "+quotedSketchLocation+"\nvoid setup();\n#line 7 "+quotedSketchLocation+"\nvoid loop();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithInlineFunction(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_inline_function", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - - expected := "#line 1 " + quotedSketchLocation + "\nvoid setup();\n#line 2 " + quotedSketchLocation + "\nvoid loop();\n#line 4 " + quotedSketchLocation + "\nshort unsigned int testInt();\n#line 8 " + quotedSketchLocation + "\nstatic int8_t testInline();\n#line 12 " + quotedSketchLocation + "\n__attribute__((always_inline)) uint8_t testAttribute();\n#line 1 " + quotedSketchLocation + "\n" - obtained := ctx.PrototypesSection - // ctags based preprocessing removes "inline" but this is still OK - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "static inline int8_t testInline();", "static int8_t testInline();", -1) - obtained = strings.Replace(obtained, "static inline int8_t testInline();", "static int8_t testInline();", -1) - // ctags based preprocessing removes "__attribute__ ....." but this is still OK - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "__attribute__((always_inline)) uint8_t testAttribute();", "uint8_t testAttribute();", -1) - obtained = strings.Replace(obtained, "__attribute__((always_inline)) uint8_t testAttribute();", "uint8_t testAttribute();", -1) - require.Equal(t, expected, obtained) -} - -func TestPrototypesAdderSketchWithFunctionSignatureInsideIFDEF(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_function_signature_inside_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 1 "+quotedSketchLocation+"\nvoid setup();\n#line 3 "+quotedSketchLocation+"\nvoid loop();\n#line 15 "+quotedSketchLocation+"\nint8_t adalight();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithUSBCON(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_usbcon", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 5 "+quotedSketchLocation+"\nvoid ciao();\n#line 10 "+quotedSketchLocation+"\nvoid setup();\n#line 15 "+quotedSketchLocation+"\nvoid loop();\n#line 5 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithTypename(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_typename", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInLibrariesDirs: paths.NewPathList("libraries", "downloaded_libraries"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - expected := "#line 6 " + quotedSketchLocation + "\nvoid setup();\n#line 10 " + quotedSketchLocation + "\nvoid loop();\n#line 12 " + quotedSketchLocation + "\ntypename Foo::Bar func();\n#line 6 " + quotedSketchLocation + "\n" - obtained := ctx.PrototypesSection - // ctags based preprocessing ignores line with typename - // TODO: remove this exception when moving to a more powerful parser - expected = strings.Replace(expected, "#line 12 "+quotedSketchLocation+"\ntypename Foo::Bar func();\n", "", -1) - obtained = strings.Replace(obtained, "#line 12 "+quotedSketchLocation+"\ntypename Foo::Bar func();\n", "", -1) - require.Equal(t, expected, obtained) -} - -func TestPrototypesAdderSketchWithIfDef2(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:yun"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 5 "+quotedSketchLocation+"\nvoid elseBranch();\n#line 9 "+quotedSketchLocation+"\nvoid f1();\n#line 10 "+quotedSketchLocation+"\nvoid f2();\n#line 12 "+quotedSketchLocation+"\nvoid setup();\n#line 14 "+quotedSketchLocation+"\nvoid loop();\n#line 5 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - expectedSource := LoadAndInterpolate(t, filepath.Join("sketch_with_ifdef", "sketch.preprocessed.txt"), ctx) - require.Equal(t, expectedSource, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithIfDef2SAM(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_ifdef", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x_dbg"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 2 "+quotedSketchLocation+"\nvoid ifBranch();\n#line 9 "+quotedSketchLocation+"\nvoid f1();\n#line 10 "+quotedSketchLocation+"\nvoid f2();\n#line 12 "+quotedSketchLocation+"\nvoid setup();\n#line 14 "+quotedSketchLocation+"\nvoid loop();\n#line 2 "+quotedSketchLocation+"\n", ctx.PrototypesSection) - - expectedSource := LoadAndInterpolate(t, filepath.Join("sketch_with_ifdef", "sketch.preprocessed.SAM.txt"), ctx) - require.Equal(t, expectedSource, strings.Replace(ctx.Source, "\r\n", "\n", -1)) -} - -func TestPrototypesAdderSketchWithConst(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - sketchLocation := paths.New("sketch_with_const", "sketch.ino") - quotedSketchLocation := utils.QuoteCppPath(Abs(t, sketchLocation)) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "#include \n#line 1 "+quotedSketchLocation+"\n", ctx.IncludeSection) - require.Equal(t, "#line 1 "+quotedSketchLocation+"\nvoid setup();\n#line 2 "+quotedSketchLocation+"\nvoid loop();\n#line 4 "+quotedSketchLocation+"\nconst __FlashStringHelper* test();\n#line 6 "+quotedSketchLocation+"\nconst int test3();\n#line 8 "+quotedSketchLocation+"\nvolatile __FlashStringHelper* test2();\n#line 10 "+quotedSketchLocation+"\nvolatile int test4();\n#line 1 "+quotedSketchLocation+"\n", ctx.PrototypesSection) -} - -func TestPrototypesAdderSketchWithDosEol(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("eol_processing", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - // only requires no error as result -} - -func TestPrototypesAdderSketchWithSubstringFunctionMember(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - sketchLocation := paths.New("sketch_with_class_and_method_substring", "sketch_with_class_and_method_substring.ino") - quotedSketchLocation := utils.QuoteCppString(Abs(t, sketchLocation).String()) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: sketchLocation, - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - Verbose: true, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - - &builder.ContainerMergeCopySketchFiles{}, - - &builder.ContainerFindIncludes{}, - - &builder.PrintUsedLibrariesIfVerbose{}, - &builder.WarnAboutArchIncompatibleLibraries{}, - - &builder.ContainerAddPrototypes{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Contains(t, ctx.Source, "class Foo {\nint blooper(int x) { return x+1; }\n};\n\nFoo foo;\n\n#line 7 "+quotedSketchLocation+"\nvoid setup();") -} diff --git a/test/read_file_and_store_in_context_test.go b/test/read_file_and_store_in_context_test.go deleted file mode 100644 index f6977b7c..00000000 --- a/test/read_file_and_store_in_context_test.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "io/ioutil" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestReadFileAndStoreInContext(t *testing.T) { - filePath, err := ioutil.TempFile("", "test") - NoError(t, err) - - file := paths.New(filePath.Name()) - defer file.RemoveAll() - - file.WriteFile([]byte("test test\nciao")) - - ctx := &types.Context{} - - command := &builder.ReadFileAndStoreInContext{FileToRead: file, Target: &ctx.SourceGccMinusE} - err = command.Run(ctx) - NoError(t, err) - - require.Equal(t, "test test\nciao", ctx.SourceGccMinusE) -} diff --git a/test/recipe_runner_test.go b/test/recipe_runner_test.go deleted file mode 100644 index 47896501..00000000 --- a/test/recipe_runner_test.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-properties-orderedmap" - "github.com/stretchr/testify/require" -) - -// TODO -// I can't find a command I can run on linux, mac and windows -// and that allows to test if the recipe is actually run -// So this test is pretty useless -func TestRecipeRunner(t *testing.T) { - ctx := &types.Context{} - buildProperties := properties.NewMap() - ctx.BuildProperties = buildProperties - - buildProperties.Set("recipe.hooks.prebuild.1.pattern", "echo") - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RecipeByPrefixSuffixRunner{Prefix: constants.HOOKS_PREBUILD, Suffix: constants.HOOKS_PATTERN_SUFFIX}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } -} - -func TestRecipesComposition(t *testing.T) { - require.Equal(t, "recipe.hooks.core.postbuild", constants.HOOKS_CORE_POSTBUILD) - require.Equal(t, "recipe.hooks.postbuild", constants.HOOKS_POSTBUILD) - require.Equal(t, "recipe.hooks.linking.prelink", constants.HOOKS_LINKING_PRELINK) - require.Equal(t, "recipe.hooks.objcopy.preobjcopy", constants.HOOKS_OBJCOPY_PREOBJCOPY) -} diff --git a/test/rewrite_hardware_keys_test.go b/test/rewrite_hardware_keys_test.go deleted file mode 100644 index d5b65342..00000000 --- a/test/rewrite_hardware_keys_test.go +++ /dev/null @@ -1,124 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" - properties "github.com/arduino/go-properties-orderedmap" - "github.com/stretchr/testify/require" -) - -func TestRewriteHardwareKeys(t *testing.T) { - ctx := &types.Context{} - - packages := &cores.Packages{} - packages.Packages = map[string]*cores.Package{} - aPackage := &cores.Package{Name: "dummy"} - packages.Packages["dummy"] = aPackage - aPackage.Platforms = map[string]*cores.Platform{} - - platform := &cores.PlatformRelease{ - Properties: properties.NewFromHashmap(map[string]string{ - "name": "A test platform", - "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", - }), - } - aPackage.Platforms["dummy"] = &cores.Platform{ - Architecture: "dummy", - Releases: map[string]*cores.PlatformRelease{ - "": platform, - }, - } - - ctx.Hardware = packages - - rewrite := types.PlatforKeyRewrite{Key: "compiler.path", OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} - platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} - ctx.PlatformKeyRewrites = platformKeysRewrite - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "{runtime.tools.avr-gcc.path}/bin/", platform.Properties.Get("compiler.path")) -} - -func TestRewriteHardwareKeysWithRewritingDisabled(t *testing.T) { - ctx := &types.Context{} - - packages := &cores.Packages{} - packages.Packages = make(map[string]*cores.Package) - aPackage := &cores.Package{Name: "dummy"} - packages.Packages["dummy"] = aPackage - aPackage.Platforms = make(map[string]*cores.Platform) - - platform := &cores.PlatformRelease{ - Properties: properties.NewFromHashmap(map[string]string{ - "name": "A test platform", - "compiler.path": "{runtime.ide.path}/hardware/tools/avr/bin/", - "rewriting": "disabled", - }), - } - aPackage.Platforms["dummy"] = &cores.Platform{ - Architecture: "dummy", - Releases: map[string]*cores.PlatformRelease{ - "": platform, - }, - } - - ctx.Hardware = packages - - rewrite := types.PlatforKeyRewrite{Key: "compiler.path", OldValue: "{runtime.ide.path}/hardware/tools/avr/bin/", NewValue: "{runtime.tools.avr-gcc.path}/bin/"} - platformKeysRewrite := types.PlatforKeysRewrite{Rewrites: []types.PlatforKeyRewrite{rewrite}} - - ctx.PlatformKeyRewrites = platformKeysRewrite - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.RewriteHardwareKeys{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - require.Equal(t, "{runtime.ide.path}/hardware/tools/avr/bin/", platform.Properties.Get("compiler.path")) -} diff --git a/test/setup_build_properties_test.go b/test/setup_build_properties_test.go deleted file mode 100644 index 4cf9a069..00000000 --- a/test/setup_build_properties_test.go +++ /dev/null @@ -1,244 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestSetupBuildProperties(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.ToolsLoader{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties.Get("software")) - - require.Equal(t, "uno", buildProperties.Get("_id")) - require.Equal(t, "Arduino/Genuino Uno", buildProperties.Get("name")) - require.Equal(t, "0x2341", buildProperties.Get("vid.0")) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties.Get("tools.avrdude.config.path")) - - requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), "downloaded_hardware/arduino/avr") - requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), "downloaded_hardware/arduino") - require.Equal(t, "10600", buildProperties.Get("runtime.ide.version")) - require.NotEmpty(t, buildProperties.Get("runtime.os")) - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude-6.0.1-arduino5.path"), "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude.path"), "tools_builtin/avr", "downloaded_tools/avrdude/6.0.1-arduino5") - - bossacPath := buildProperties.Get("runtime.tools.bossac.path") - bossac161Path := buildProperties.Get("runtime.tools.bossac-1.6.1-arduino.path") - bossac15Path := buildProperties.Get("runtime.tools.bossac-1.5-arduino.path") - requireEquivalentPaths(t, bossac161Path, "downloaded_tools/bossac/1.6.1-arduino") - requireEquivalentPaths(t, bossac15Path, "downloaded_tools/bossac/1.5-arduino") - requireEquivalentPaths(t, bossacPath, bossac161Path, bossac15Path) - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - - requireEquivalentPaths(t, buildProperties.Get("build.source.path"), "sketch1") - - require.True(t, buildProperties.ContainsKey("extra.time.utc")) - require.True(t, buildProperties.ContainsKey("extra.time.local")) - require.True(t, buildProperties.ContainsKey("extra.time.zone")) - require.True(t, buildProperties.ContainsKey("extra.time.dst")) -} - -func TestSetupBuildPropertiesWithSomeCustomOverrides(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - ArduinoAPIVersion: "10600", - - CustomBuildProperties: []string{"name=fake name", "tools.avrdude.config.path=non existent path with space and a ="}, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.ToolsLoader{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - &builder.SetCustomBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties.Get("software")) - - require.Equal(t, "uno", buildProperties.Get("_id")) - require.Equal(t, "fake name", buildProperties.Get("name")) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) - require.Equal(t, "non existent path with space and a =", buildProperties.Get("tools.avrdude.config.path")) -} - -func TestSetupBuildPropertiesUserHardware(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.AddAdditionalEntriesToContext{}, - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - &builder.ToolsLoader{}, - &builder.SketchLoader{}, - &builder.SetupBuildProperties{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties.Get("software")) - - require.Equal(t, "custom_yun", buildProperties.Get("_id")) - require.Equal(t, "caterina/Caterina-custom_yun.hex", buildProperties.Get("bootloader.file")) - requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), filepath.Join("user_hardware", "my_avr_platform", "avr")) - requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), filepath.Join("user_hardware", "my_avr_platform")) -} - -func TestSetupBuildPropertiesWithMissingPropsFromParentPlatformTxtFiles(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - SketchLocation: paths.New("sketch1", "sketch.ino"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - ArduinoAPIVersion: "10600", - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.ContainerSetupHardwareToolsLibsSketchAndProps{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - buildProperties := ctx.BuildProperties - - require.Equal(t, "ARDUINO", buildProperties.Get("software")) - - require.Equal(t, "custom_yun", buildProperties.Get("_id")) - require.Equal(t, "Arduino Yún", buildProperties.Get("name")) - require.Equal(t, "0x2341", buildProperties.Get("vid.0")) - require.Equal(t, "\"{compiler.path}{compiler.c.cmd}\" {compiler.c.flags} -mmcu={build.mcu} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {includes} \"{source_file}\" -o \"{object_file}\"", buildProperties.Get("recipe.c.o.pattern")) - require.Equal(t, "{path}/etc/avrdude.conf", buildProperties.Get("tools.avrdude.config.path")) - - requireEquivalentPaths(t, buildProperties.Get("runtime.platform.path"), "user_hardware/my_avr_platform/avr") - requireEquivalentPaths(t, buildProperties.Get("runtime.hardware.path"), "user_hardware/my_avr_platform") - require.Equal(t, "10600", buildProperties.Get("runtime.ide.version")) - require.NotEmpty(t, buildProperties.Get("runtime.os")) - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.arm-none-eabi-gcc-4.8.3-2014q1.path"), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac-1.6.1-arduino.path"), "downloaded_tools/bossac/1.6.1-arduino") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac-1.5-arduino.path"), "downloaded_tools/bossac/1.5-arduino") - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.bossac.path"), "downloaded_tools/bossac/1.6.1-arduino", "downloaded_tools/bossac/1.5-arduino") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude.path"), "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avrdude-6.0.1-arduino5.path"), "downloaded_tools/avrdude/6.0.1-arduino5", "tools_builtin/avr") - - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - requireEquivalentPaths(t, buildProperties.Get("runtime.tools.avr-gcc-4.8.1-arduino5.path"), "downloaded_tools/avr-gcc/4.8.1-arduino5", "tools_builtin/avr") - - requireEquivalentPaths(t, buildProperties.Get("build.source.path"), "sketch1") - - require.True(t, buildProperties.ContainsKey("extra.time.utc")) - require.True(t, buildProperties.ContainsKey("extra.time.local")) - require.True(t, buildProperties.ContainsKey("extra.time.zone")) - require.True(t, buildProperties.ContainsKey("extra.time.dst")) -} diff --git a/test/sketch1/doc.txt b/test/sketch1/doc.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/header.h b/test/sketch1/header.h deleted file mode 100644 index 2e24536f..00000000 --- a/test/sketch1/header.h +++ /dev/null @@ -1 +0,0 @@ -#define TRUE FALSE \ No newline at end of file diff --git a/test/sketch1/merged_sketch.txt b/test/sketch1/merged_sketch.txt deleted file mode 100644 index 4654de32..00000000 --- a/test/sketch1/merged_sketch.txt +++ /dev/null @@ -1,16 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - -} -#line 1 {{QuoteCppString (index .sketch.OtherSketchFiles 0).Name}} - -#line 1 {{QuoteCppString (index .sketch.OtherSketchFiles 1).Name}} -String hello() { - return "world"; -} diff --git a/test/sketch1/old.pde b/test/sketch1/old.pde deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/other.ino b/test/sketch1/other.ino deleted file mode 100644 index c426196c..00000000 --- a/test/sketch1/other.ino +++ /dev/null @@ -1,3 +0,0 @@ -String hello() { - return "world"; -} \ No newline at end of file diff --git a/test/sketch1/s_file.S b/test/sketch1/s_file.S deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch1/sketch.ino b/test/sketch1/sketch.ino deleted file mode 100644 index 0d5e0f5c..00000000 --- a/test/sketch1/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch1/src/helper.h b/test/sketch1/src/helper.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch10/sketch.ino b/test/sketch10/sketch.ino deleted file mode 100644 index 28c88524..00000000 --- a/test/sketch10/sketch.ino +++ /dev/null @@ -1,5 +0,0 @@ -#include -#include - -void setup() {} -void loop() {} diff --git a/test/sketch11/sketch_fastleds.ino b/test/sketch11/sketch_fastleds.ino deleted file mode 100644 index eba4f526..00000000 --- a/test/sketch11/sketch_fastleds.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include "FastLED.h" - -#define DATA_PIN 7 -#define CLK_PIN 6 -#define LED_TYPE APA102 -#define COLOR_ORDER GRB -#define NUM_LEDS 79 -CRGB leds[NUM_LEDS]; - -#define BRIGHTNESS 96 -#define FRAMES_PER_SECOND 120 -void setup() { - - FastLED.addLeds(leds, NUM_LEDS).setCorrection(TypicalLEDStrip); -} - -void loop() { - -} - -typedef void (*SimplePatternList[])(); -//SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, sinelon, juggle, bpm }; -SimplePatternList gPatterns = {sinelon}; - -void sinelon() -{ -} \ No newline at end of file diff --git a/test/sketch12/sketch12.ino b/test/sketch12/sketch12.ino deleted file mode 100644 index ec00136a..00000000 --- a/test/sketch12/sketch12.ino +++ /dev/null @@ -1,16 +0,0 @@ -// See: https://github.com/arduino/arduino-builder/issues/68 - -// The following avoid duplicate definitions of min and max -#undef min -#undef max - -#include - -void setup() { - test(); -} - -void loop() {} - -void test() {} - diff --git a/test/sketch2/SketchWithIfDef.ino b/test/sketch2/SketchWithIfDef.ino deleted file mode 100644 index ddd7f3d4..00000000 --- a/test/sketch2/SketchWithIfDef.ino +++ /dev/null @@ -1,50 +0,0 @@ -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - -#if DISABLED -#include -#endif - -#ifdef DISABLED -#include "empty_1.h" -#endif - -#include "empty_2.h" - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -#if DISABLED -void shouldNotBePrototyped() { - -} -#endif - -#if DEBUG -void debug() { - -} -#endif - -#ifdef UNDEFINED -void undefinedFunction() { -} -#endif - -#ifdef DISABLED -void disabledIsDefined() { -} -#endif - -int useMyType(MyType type) { - -} diff --git a/test/sketch2/SketchWithIfDef.preprocessed.txt b/test/sketch2/SketchWithIfDef.preprocessed.txt deleted file mode 100644 index e0380e17..00000000 --- a/test/sketch2/SketchWithIfDef.preprocessed.txt +++ /dev/null @@ -1,65 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - -#if DISABLED -#include -#endif - -#ifdef DISABLED -#include "empty_1.h" -#endif - -#include "empty_2.h" - -#line 16 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 21 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 33 {{QuoteCppString .sketch.MainFile.Name}} -void debug(); -#line 44 {{QuoteCppString .sketch.MainFile.Name}} -void disabledIsDefined(); -#line 48 {{QuoteCppString .sketch.MainFile.Name}} -int useMyType(MyType type); -#line 16 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -#if DISABLED -void shouldNotBePrototyped() { - -} -#endif - -#if DEBUG -void debug() { - -} -#endif - -#ifdef UNDEFINED -void undefinedFunction() { -} -#endif - -#ifdef DISABLED -void disabledIsDefined() { -} -#endif - -int useMyType(MyType type) { - -} - diff --git a/test/sketch2/SketchWithIfDef.resolved.directives.txt b/test/sketch2/SketchWithIfDef.resolved.directives.txt deleted file mode 100644 index c01a6fe3..00000000 --- a/test/sketch2/SketchWithIfDef.resolved.directives.txt +++ /dev/null @@ -1,55 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#define DEBUG 1 -#define DISABLED 0 - -typedef int MyType; - - - - - - -#include "empty_1.h" - - -#include "empty_2.h" - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} - - - - - - - - -void debug() { - -} - - - - - - - - -void disabledIsDefined() { -} - - -int useMyType(MyType type) { - -} - - diff --git a/test/sketch2/empty_1.h b/test/sketch2/empty_1.h deleted file mode 100644 index 2741ec6f..00000000 --- a/test/sketch2/empty_1.h +++ /dev/null @@ -1,4 +0,0 @@ -#define world - -void two() { -} \ No newline at end of file diff --git a/test/sketch2/empty_2.h b/test/sketch2/empty_2.h deleted file mode 100644 index 11f2de2c..00000000 --- a/test/sketch2/empty_2.h +++ /dev/null @@ -1,4 +0,0 @@ -#define hello - -void one(MyType arg){ -} \ No newline at end of file diff --git a/test/sketch3/Baladuino.ino b/test/sketch3/Baladuino.ino deleted file mode 100644 index a208fafd..00000000 --- a/test/sketch3/Baladuino.ino +++ /dev/null @@ -1,303 +0,0 @@ -/* - * The code is released under the GNU General Public License. - * Developed by Kristian Lauszus, TKJ Electronics 2013 - * This is the algorithm for the Balanduino balancing robot. - * It can be controlled by either an Android app or a Processing application via Bluetooth. - * The Android app can be found at the following link: https://github.com/TKJElectronics/BalanduinoAndroidApp - * The Processing application can be found here: https://github.com/TKJElectronics/BalanduinoProcessingApp - * It can also be controlled by a PS3, Wii or a Xbox controller - * For details, see: http://balanduino.net/ - */ - -/* Use this to enable and disable the different options */ -#define ENABLE_TOOLS -#define ENABLE_SPP -#define ENABLE_PS3 -#define ENABLE_WII -#define ENABLE_XBOX -#define ENABLE_ADK - -#include "Balanduino.h" -#include // Official Arduino Wire library -#include // Some dongles can have a hub inside - -#ifdef ENABLE_ADK -#include -#endif - -// These are all open source libraries written by Kristian Lauszus, TKJ Electronics -// The USB libraries are located at the following link: https://github.com/felis/USB_Host_Shield_2.0 -#include // Kalman filter library - see: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it/ - -#ifdef ENABLE_XBOX -#include -#endif -#ifdef ENABLE_SPP -#include -#endif -#ifdef ENABLE_PS3 -#include -#endif -#ifdef ENABLE_WII -#include -#endif - -// Create the Kalman library instance -Kalman kalman; // See https://github.com/TKJElectronics/KalmanFilter for source code - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) || defined(ENABLE_XBOX) || defined(ENABLE_ADK) -#define ENABLE_USB -USB Usb; // This will take care of all USB communication -#endif - -#ifdef ENABLE_ADK -// Implementation for the Android Open Accessory Protocol. Simply connect your phone to get redirected to the Play Store -ADK adk(&Usb, "TKJ Electronics", // Manufacturer Name - "Balanduino", // Model Name - "Android App for Balanduino", // Description - user visible string - "0.5.0", // Version of the Android app - "https://play.google.com/store/apps/details?id=com.tkjelectronics.balanduino", // URL - web page to visit if no installed apps support the accessory - "1234"); // Serial Number - this is not used -#endif - -#ifdef ENABLE_XBOX -XBOXRECV Xbox(&Usb); // You have to connect a Xbox wireless receiver to the Arduino to control it with a wireless Xbox controller -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) -USBHub Hub(&Usb); // Some dongles have a hub inside -BTD Btd(&Usb); // This is the main Bluetooth library, it will take care of all the USB and HCI communication with the Bluetooth dongle -#endif - -#ifdef ENABLE_SPP -SPP SerialBT(&Btd, "Balanduino", "0000"); // The SPP (Serial Port Protocol) emulates a virtual Serial port, which is supported by most computers and mobile phones -#endif - -#ifdef ENABLE_PS3 -PS3BT PS3(&Btd); // The PS3 library supports all three official controllers: the Dualshock 3, Navigation and Move controller -#endif - -#ifdef ENABLE_WII -WII Wii(&Btd); // The Wii library can communicate with Wiimotes and the Nunchuck and Motion Plus extension and finally the Wii U Pro Controller -//WII Wii(&Btd,PAIR); // You will have to pair with your Wiimote first by creating the instance like this and the press 1+2 on the Wiimote -// or press sync if you are using a Wii U Pro Controller -// Or you can simply send "CW;" to the robot to start the pairing sequence -// This can also be done using the Android or Processing application -#endif - -void setup() { - /* Initialize UART */ - Serial.begin(115200); - - /* Read the PID values, target angle and other saved values in the EEPROM */ - if (!checkInitializationFlags()) - readEEPROMValues(); // Only read the EEPROM values if they have not been restored - - /* Setup encoders */ - pinMode(leftEncoder1, INPUT); - pinMode(leftEncoder2, INPUT); - pinMode(rightEncoder1, INPUT); - pinMode(rightEncoder2, INPUT); - attachInterrupt(0, leftEncoder, CHANGE); - attachInterrupt(1, rightEncoder, CHANGE); - - /* Enable the motor drivers */ - pinMode(leftEnable, OUTPUT); - pinMode(rightEnable, OUTPUT); - digitalWrite(leftEnable, HIGH); - digitalWrite(rightEnable, HIGH); - - /* Setup motor pins to output */ - sbi(pwmPortDirection, leftPWM); - sbi(leftPortDirection, leftA); - sbi(leftPortDirection, leftB); - sbi(pwmPortDirection, rightPWM); - sbi(rightPortDirection, rightA); - sbi(rightPortDirection, rightB); - - /* Set PWM frequency to 20kHz - see the datasheet http://www.atmel.com/Images/doc8272.pdf page 128-135 */ - // Set up PWM, Phase and Frequency Correct on pin 18 (OC1A) & pin 17 (OC1B) with ICR1 as TOP using Timer1 - TCCR1B = _BV(WGM13) | _BV(CS10); // Set PWM Phase and Frequency Correct with ICR1 as TOP and no prescaling - ICR1 = PWMVALUE; // ICR1 is the TOP value - this is set so the frequency is equal to 20kHz - - /* Enable PWM on pin 18 (OC1A) & pin 17 (OC1B) */ - // Clear OC1A/OC1B on compare match when up-counting - // Set OC1A/OC1B on compare match when downcounting - TCCR1A = _BV(COM1A1) | _BV(COM1B1); - setPWM(leftPWM, 0); // Turn off PWM on both pins - setPWM(rightPWM, 0); - - /* Setup buzzer pin */ - pinMode(buzzer, OUTPUT); - -#ifdef ENABLE_USB - if (Usb.Init() == -1) { // Check if USB Host is working - Serial.print(F("OSC did not start")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } -#endif - - /* Attach onInit function */ - // This is used to set the LEDs according to the voltage level and vibrate the controller to indicate the new connection -#ifdef ENABLE_PS3 - PS3.attachOnInit(onInit); -#endif -#ifdef ENABLE_WII - Wii.attachOnInit(onInit); -#endif -#ifdef ENABLE_XBOX - Xbox.attachOnInit(onInit); -#endif - - /* Setup IMU */ - Wire.begin(); - - while (i2cRead(0x75, i2cBuffer, 1)); - if (i2cBuffer[0] != 0x68) { // Read "WHO_AM_I" register - Serial.print(F("Error reading sensor")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } - - i2cBuffer[0] = 19; // Set the sample rate to 400Hz - 8kHz/(19+1) = 400Hz - i2cBuffer[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling - i2cBuffer[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s - i2cBuffer[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g - while (i2cWrite(0x19, i2cBuffer, 4, false)); // Write to all four registers at once - while (i2cWrite(0x6B, 0x09, true)); // PLL with X axis gyroscope reference, disable temperature sensor and disable sleep mode - - delay(100); // Wait for the sensor to get ready - - /* Set Kalman and gyro starting angle */ - while (i2cRead(0x3D, i2cBuffer, 4)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - kalman.setAngle(accAngle); // Set starting angle - pitch = accAngle; - gyroAngle = accAngle; - - /* Find gyro zero value */ - calibrateGyro(); - - pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN is defined in pins_arduino.h in the hardware add-on - - /* Beep to indicate that it is now ready */ - digitalWrite(buzzer, HIGH); - delay(100); - digitalWrite(buzzer, LOW); - - /* Setup timing */ - kalmanTimer = micros(); - pidTimer = kalmanTimer; - encoderTimer = kalmanTimer; - imuTimer = millis(); - reportTimer = imuTimer; - ledTimer = imuTimer; - blinkTimer = imuTimer; -} - -void loop() { -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Calculate pitch */ - while (i2cRead(0x3D, i2cBuffer, 8)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - gyroX = ((i2cBuffer[6] << 8) | i2cBuffer[7]); - - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - uint32_t timer = micros(); - // This fixes the 0-360 transition problem when the accelerometer angle jumps between 0 and 360 degrees - if ((accAngle < 90 && pitch > 270) || (accAngle > 270 && pitch < 90)) { - kalman.setAngle(accAngle); - pitch = accAngle; - gyroAngle = accAngle; - } else { - gyroRate = ((double)gyroX - gyroXzero) / 131.0; // Convert to deg/s - double dt = (double)(timer - kalmanTimer) / 1000000.0; - gyroAngle += gyroRate * dt; // Gyro angle is only used for debugging - if (gyroAngle < 0 || gyroAngle > 360) - gyroAngle = pitch; // Reset the gyro angle when it has drifted too much - pitch = kalman.getAngle(accAngle, gyroRate, dt); // Calculate the angle using a Kalman filter - } - kalmanTimer = timer; - //Serial.print(accAngle);Serial.print('\t');Serial.print(gyroAngle);Serial.print('\t');Serial.println(pitch); - -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Drive motors */ - timer = micros(); - // If the robot is laying down, it has to be put in a vertical position before it starts balancing - // If it's already balancing it has to be ±45 degrees before it stops trying to balance - if ((layingDown && (pitch < cfg.targetAngle - 10 || pitch > cfg.targetAngle + 10)) || (!layingDown && (pitch < cfg.targetAngle - 45 || pitch > cfg.targetAngle + 45))) { - layingDown = true; // The robot is in a unsolvable position, so turn off both motors and wait until it's vertical again - stopAndReset(); - } else { - layingDown = false; // It's no longer laying down - updatePID(cfg.targetAngle, targetOffset, turningOffset, (double)(timer - pidTimer) / 1000000.0); - } - pidTimer = timer; - - /* Update encoders */ - timer = micros(); - if (timer - encoderTimer >= 100000) { // Update encoder values every 100ms - encoderTimer = timer; - int32_t wheelPosition = getWheelsPosition(); - wheelVelocity = wheelPosition - lastWheelPosition; - lastWheelPosition = wheelPosition; - //Serial.print(wheelPosition);Serial.print('\t');Serial.print(targetPosition);Serial.print('\t');Serial.println(wheelVelocity); - if (abs(wheelVelocity) <= 40 && !stopped) { // Set new targetPosition if braking - targetPosition = wheelPosition; - stopped = true; - } - - batteryCounter++; - if (batteryCounter > 10) { // Measure battery every 1s - batteryCounter = 0; - batteryVoltage = (double)analogRead(VBAT) / 63.050847458; // VBAT is connected to analog input 5 which is not broken out. This is then connected to a 47k-12k voltage divider - 1023.0/(3.3/(12.0/(12.0+47.0))) = 63.050847458 - if (batteryVoltage < 10.2 && batteryVoltage > 5) // Equal to 3.4V per cell - don't turn on if it's below 5V, this means that no battery is connected - digitalWrite(buzzer, HIGH); - else - digitalWrite(buzzer, LOW); - } - } - - /* Read the Bluetooth dongle and send PID and IMU values */ -#ifdef ENABLE_USB - readUsb(); -#endif -#ifdef ENABLE_TOOLS - checkSerialData(); -#endif -#if defined(ENABLE_TOOLS) || defined(ENABLE_SPP) - printValues(); -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) - if (Btd.isReady()) { - timer = millis(); - if ((Btd.watingForConnection && timer - blinkTimer > 1000) || (!Btd.watingForConnection && timer - blinkTimer > 100)) { - blinkTimer = timer; - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // Used to blink the built in LED, starts blinking faster upon an incoming Bluetooth request - } - } else if (ledState) { // The LED is on - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // This will turn it off - } -#endif -} \ No newline at end of file diff --git a/test/sketch3/Baladuino.preprocessed.txt b/test/sketch3/Baladuino.preprocessed.txt deleted file mode 100644 index 989b6b9b..00000000 --- a/test/sketch3/Baladuino.preprocessed.txt +++ /dev/null @@ -1,311 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -/* - * The code is released under the GNU General Public License. - * Developed by Kristian Lauszus, TKJ Electronics 2013 - * This is the algorithm for the Balanduino balancing robot. - * It can be controlled by either an Android app or a Processing application via Bluetooth. - * The Android app can be found at the following link: https://github.com/TKJElectronics/BalanduinoAndroidApp - * The Processing application can be found here: https://github.com/TKJElectronics/BalanduinoProcessingApp - * It can also be controlled by a PS3, Wii or a Xbox controller - * For details, see: http://balanduino.net/ - */ - -/* Use this to enable and disable the different options */ -#define ENABLE_TOOLS -#define ENABLE_SPP -#define ENABLE_PS3 -#define ENABLE_WII -#define ENABLE_XBOX -#define ENABLE_ADK - -#include "Balanduino.h" -#include // Official Arduino Wire library -#include // Some dongles can have a hub inside - -#ifdef ENABLE_ADK -#include -#endif - -// These are all open source libraries written by Kristian Lauszus, TKJ Electronics -// The USB libraries are located at the following link: https://github.com/felis/USB_Host_Shield_2.0 -#include // Kalman filter library - see: http://blog.tkjelectronics.dk/2012/09/a-practical-approach-to-kalman-filter-and-how-to-implement-it/ - -#ifdef ENABLE_XBOX -#include -#endif -#ifdef ENABLE_SPP -#include -#endif -#ifdef ENABLE_PS3 -#include -#endif -#ifdef ENABLE_WII -#include -#endif - -// Create the Kalman library instance -Kalman kalman; // See https://github.com/TKJElectronics/KalmanFilter for source code - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) || defined(ENABLE_XBOX) || defined(ENABLE_ADK) -#define ENABLE_USB -USB Usb; // This will take care of all USB communication -#endif - -#ifdef ENABLE_ADK -// Implementation for the Android Open Accessory Protocol. Simply connect your phone to get redirected to the Play Store -ADK adk(&Usb, "TKJ Electronics", // Manufacturer Name - "Balanduino", // Model Name - "Android App for Balanduino", // Description - user visible string - "0.5.0", // Version of the Android app - "https://play.google.com/store/apps/details?id=com.tkjelectronics.balanduino", // URL - web page to visit if no installed apps support the accessory - "1234"); // Serial Number - this is not used -#endif - -#ifdef ENABLE_XBOX -XBOXRECV Xbox(&Usb); // You have to connect a Xbox wireless receiver to the Arduino to control it with a wireless Xbox controller -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) -USBHub Hub(&Usb); // Some dongles have a hub inside -BTD Btd(&Usb); // This is the main Bluetooth library, it will take care of all the USB and HCI communication with the Bluetooth dongle -#endif - -#ifdef ENABLE_SPP -SPP SerialBT(&Btd, "Balanduino", "0000"); // The SPP (Serial Port Protocol) emulates a virtual Serial port, which is supported by most computers and mobile phones -#endif - -#ifdef ENABLE_PS3 -PS3BT PS3(&Btd); // The PS3 library supports all three official controllers: the Dualshock 3, Navigation and Move controller -#endif - -#ifdef ENABLE_WII -WII Wii(&Btd); // The Wii library can communicate with Wiimotes and the Nunchuck and Motion Plus extension and finally the Wii U Pro Controller -//WII Wii(&Btd,PAIR); // You will have to pair with your Wiimote first by creating the instance like this and the press 1+2 on the Wiimote -// or press sync if you are using a Wii U Pro Controller -// Or you can simply send "CW;" to the robot to start the pairing sequence -// This can also be done using the Android or Processing application -#endif - -#line 88 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 204 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 88 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - /* Initialize UART */ - Serial.begin(115200); - - /* Read the PID values, target angle and other saved values in the EEPROM */ - if (!checkInitializationFlags()) - readEEPROMValues(); // Only read the EEPROM values if they have not been restored - - /* Setup encoders */ - pinMode(leftEncoder1, INPUT); - pinMode(leftEncoder2, INPUT); - pinMode(rightEncoder1, INPUT); - pinMode(rightEncoder2, INPUT); - attachInterrupt(0, leftEncoder, CHANGE); - attachInterrupt(1, rightEncoder, CHANGE); - - /* Enable the motor drivers */ - pinMode(leftEnable, OUTPUT); - pinMode(rightEnable, OUTPUT); - digitalWrite(leftEnable, HIGH); - digitalWrite(rightEnable, HIGH); - - /* Setup motor pins to output */ - sbi(pwmPortDirection, leftPWM); - sbi(leftPortDirection, leftA); - sbi(leftPortDirection, leftB); - sbi(pwmPortDirection, rightPWM); - sbi(rightPortDirection, rightA); - sbi(rightPortDirection, rightB); - - /* Set PWM frequency to 20kHz - see the datasheet http://www.atmel.com/Images/doc8272.pdf page 128-135 */ - // Set up PWM, Phase and Frequency Correct on pin 18 (OC1A) & pin 17 (OC1B) with ICR1 as TOP using Timer1 - TCCR1B = _BV(WGM13) | _BV(CS10); // Set PWM Phase and Frequency Correct with ICR1 as TOP and no prescaling - ICR1 = PWMVALUE; // ICR1 is the TOP value - this is set so the frequency is equal to 20kHz - - /* Enable PWM on pin 18 (OC1A) & pin 17 (OC1B) */ - // Clear OC1A/OC1B on compare match when up-counting - // Set OC1A/OC1B on compare match when downcounting - TCCR1A = _BV(COM1A1) | _BV(COM1B1); - setPWM(leftPWM, 0); // Turn off PWM on both pins - setPWM(rightPWM, 0); - - /* Setup buzzer pin */ - pinMode(buzzer, OUTPUT); - -#ifdef ENABLE_USB - if (Usb.Init() == -1) { // Check if USB Host is working - Serial.print(F("OSC did not start")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } -#endif - - /* Attach onInit function */ - // This is used to set the LEDs according to the voltage level and vibrate the controller to indicate the new connection -#ifdef ENABLE_PS3 - PS3.attachOnInit(onInit); -#endif -#ifdef ENABLE_WII - Wii.attachOnInit(onInit); -#endif -#ifdef ENABLE_XBOX - Xbox.attachOnInit(onInit); -#endif - - /* Setup IMU */ - Wire.begin(); - - while (i2cRead(0x75, i2cBuffer, 1)); - if (i2cBuffer[0] != 0x68) { // Read "WHO_AM_I" register - Serial.print(F("Error reading sensor")); - digitalWrite(buzzer, HIGH); - while (1); // Halt - } - - i2cBuffer[0] = 19; // Set the sample rate to 400Hz - 8kHz/(19+1) = 400Hz - i2cBuffer[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling - i2cBuffer[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s - i2cBuffer[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g - while (i2cWrite(0x19, i2cBuffer, 4, false)); // Write to all four registers at once - while (i2cWrite(0x6B, 0x09, true)); // PLL with X axis gyroscope reference, disable temperature sensor and disable sleep mode - - delay(100); // Wait for the sensor to get ready - - /* Set Kalman and gyro starting angle */ - while (i2cRead(0x3D, i2cBuffer, 4)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - kalman.setAngle(accAngle); // Set starting angle - pitch = accAngle; - gyroAngle = accAngle; - - /* Find gyro zero value */ - calibrateGyro(); - - pinMode(LED_BUILTIN, OUTPUT); // LED_BUILTIN is defined in pins_arduino.h in the hardware add-on - - /* Beep to indicate that it is now ready */ - digitalWrite(buzzer, HIGH); - delay(100); - digitalWrite(buzzer, LOW); - - /* Setup timing */ - kalmanTimer = micros(); - pidTimer = kalmanTimer; - encoderTimer = kalmanTimer; - imuTimer = millis(); - reportTimer = imuTimer; - ledTimer = imuTimer; - blinkTimer = imuTimer; -} - -void loop() { -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Calculate pitch */ - while (i2cRead(0x3D, i2cBuffer, 8)); - accY = ((i2cBuffer[0] << 8) | i2cBuffer[1]); - accZ = ((i2cBuffer[2] << 8) | i2cBuffer[3]); - gyroX = ((i2cBuffer[6] << 8) | i2cBuffer[7]); - - // atan2 outputs the value of -π to π (radians) - see http://en.wikipedia.org/wiki/Atan2 - // We then convert it to 0 to 2π and then from radians to degrees - accAngle = (atan2((double)accY - cfg.accYzero, (double)accZ - cfg.accZzero) + PI) * RAD_TO_DEG; - - uint32_t timer = micros(); - // This fixes the 0-360 transition problem when the accelerometer angle jumps between 0 and 360 degrees - if ((accAngle < 90 && pitch > 270) || (accAngle > 270 && pitch < 90)) { - kalman.setAngle(accAngle); - pitch = accAngle; - gyroAngle = accAngle; - } else { - gyroRate = ((double)gyroX - gyroXzero) / 131.0; // Convert to deg/s - double dt = (double)(timer - kalmanTimer) / 1000000.0; - gyroAngle += gyroRate * dt; // Gyro angle is only used for debugging - if (gyroAngle < 0 || gyroAngle > 360) - gyroAngle = pitch; // Reset the gyro angle when it has drifted too much - pitch = kalman.getAngle(accAngle, gyroRate, dt); // Calculate the angle using a Kalman filter - } - kalmanTimer = timer; - //Serial.print(accAngle);Serial.print('\t');Serial.print(gyroAngle);Serial.print('\t');Serial.println(pitch); - -#ifdef ENABLE_WII - if (Wii.wiimoteConnected) // We have to read much more often from the Wiimote to decrease latency - Usb.Task(); -#endif - - /* Drive motors */ - timer = micros(); - // If the robot is laying down, it has to be put in a vertical position before it starts balancing - // If it's already balancing it has to be ±45 degrees before it stops trying to balance - if ((layingDown && (pitch < cfg.targetAngle - 10 || pitch > cfg.targetAngle + 10)) || (!layingDown && (pitch < cfg.targetAngle - 45 || pitch > cfg.targetAngle + 45))) { - layingDown = true; // The robot is in a unsolvable position, so turn off both motors and wait until it's vertical again - stopAndReset(); - } else { - layingDown = false; // It's no longer laying down - updatePID(cfg.targetAngle, targetOffset, turningOffset, (double)(timer - pidTimer) / 1000000.0); - } - pidTimer = timer; - - /* Update encoders */ - timer = micros(); - if (timer - encoderTimer >= 100000) { // Update encoder values every 100ms - encoderTimer = timer; - int32_t wheelPosition = getWheelsPosition(); - wheelVelocity = wheelPosition - lastWheelPosition; - lastWheelPosition = wheelPosition; - //Serial.print(wheelPosition);Serial.print('\t');Serial.print(targetPosition);Serial.print('\t');Serial.println(wheelVelocity); - if (abs(wheelVelocity) <= 40 && !stopped) { // Set new targetPosition if braking - targetPosition = wheelPosition; - stopped = true; - } - - batteryCounter++; - if (batteryCounter > 10) { // Measure battery every 1s - batteryCounter = 0; - batteryVoltage = (double)analogRead(VBAT) / 63.050847458; // VBAT is connected to analog input 5 which is not broken out. This is then connected to a 47k-12k voltage divider - 1023.0/(3.3/(12.0/(12.0+47.0))) = 63.050847458 - if (batteryVoltage < 10.2 && batteryVoltage > 5) // Equal to 3.4V per cell - don't turn on if it's below 5V, this means that no battery is connected - digitalWrite(buzzer, HIGH); - else - digitalWrite(buzzer, LOW); - } - } - - /* Read the Bluetooth dongle and send PID and IMU values */ -#ifdef ENABLE_USB - readUsb(); -#endif -#ifdef ENABLE_TOOLS - checkSerialData(); -#endif -#if defined(ENABLE_TOOLS) || defined(ENABLE_SPP) - printValues(); -#endif - -#if defined(ENABLE_SPP) || defined(ENABLE_PS3) || defined(ENABLE_WII) - if (Btd.isReady()) { - timer = millis(); - if ((Btd.watingForConnection && timer - blinkTimer > 1000) || (!Btd.watingForConnection && timer - blinkTimer > 100)) { - blinkTimer = timer; - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // Used to blink the built in LED, starts blinking faster upon an incoming Bluetooth request - } - } else if (ledState) { // The LED is on - ledState = !ledState; - digitalWrite(LED_BUILTIN, ledState); // This will turn it off - } -#endif -} diff --git a/test/sketch4/CharWithEscapedDoubleQuote.ino b/test/sketch4/CharWithEscapedDoubleQuote.ino deleted file mode 100644 index 35c1d6ee..00000000 --- a/test/sketch4/CharWithEscapedDoubleQuote.ino +++ /dev/null @@ -1,338 +0,0 @@ -#include // required to send and receive AT commands from the GPRS Shield -#include // required for I2C communication with the RTC - -// pin numbers for RTC -#define DS3231_I2C_ADDRESS 104 // 0x68 // Address for RTC -#define DS3231_TIME_CAL_ADDR 0 // 0x00 -#define DS3231_ALARM1_ADDR 7 // 0x07 -#define DS3231_ALARM2_ADDR 11 // 0x0B -#define DS3231_CONTROL_ADDR 14 // 0x0E -#define DS3231_STATUS_ADDR 15 // 0x0F -//#define DS3231_AGING_OFFSET_ADDR 16 // 0x10 -#define DS3231_TEMPERATURE_ADDR 17 // 0x11 - -// Declarations for GPRS shield -SoftwareSerial GPRS( 7, 8 ); // A softwareSerial line is defined for the GPRS Shield -byte buffer[ 64 ]; // Buffer is used to transfer data from the GPRS line to the serial line -int count = 0, e = 0, count2 = 0, t = 0, q; -char temp, lastCaller[13] = "blank"; -boolean callIncoming = false, done; - -// Declarations for RTC -byte time[ 7 ]; // second, minute, hour, dow, day, month, year -byte time_A1[ 5 ]; // second_A1, minute_A1, hour_A1, day_A1, DY/DT -byte time_A2[ 4 ]; // minute_A2, hour_A2, day_A2, DY/DT -byte received[1]; // used to catch bytes sent from the clock -float temperature; // clock temperature is updated every 64 s - -// Declarations for RemoteCallLogger -char telescopeNames[6][4]; - -/* -Code Exclusively for GPRS shield: -*/ - -// -// Default set of instructions for GPRS Shield power control -// - -void setPowerStateTo( int newState ) -{ - if( newState != 1 && newState != 0 ) { // tests for an invalid state. In this case no change is made to powerstate - Serial.print( "Error: Invalid powerstate. Current powerstate = " ); - Serial.print( getPowerState() ); - Serial.print( "\n" ); - } - else { - if( newState == getPowerState() ) { // if the requested powerstate is already in effect, no action is taken - Serial.print( "Powerstate = " ); - Serial.print( newState ); - Serial.print( " remains unchanged.\n" ); - } - else { - powerUpOrDown(); // This is the only case where the powerstate is changed - Serial.print( "Powerstate changed from " ); - Serial.print( 1 - newState ); - Serial.print( " to " ); - Serial.print( newState ); - Serial.print( "\n" ); - } - } - delay( 5000 ); // for startup -} - -int getPowerState() // returns 0 if GPRS Shield is off, and 1 if GPRS Shield is on. This corresponds to the constant HIGH LOW enumeration -{ - int ret; - if ( digitalRead(18) == 0 && digitalRead(19) == 0 ) // tests pins 18 and 19 for activity. See ExFoundImportantPins sketch to find out why - ret = 1; - else - ret = 0; - - return ret; -} - -void powerUpOrDown() // toggle the power of the shield -{ - pinMode( 9, OUTPUT ); - digitalWrite( 9, LOW ); - delay( 1000 ); - digitalWrite( 9, HIGH ); - delay( 2000 ); - digitalWrite( 9, LOW ); - delay( 3000 ); -} - -// -// End of default power control -// - -void clearBufferArray() // gives each element in the buffer array a null value -{ - for( int i = 0; i < count; i++ ) - buffer[ i ] = NULL; -} - -void makeMissedCall( char num[] ) -{ - int i; - char in[ 18 ] = "ATD"; - for( i = 3; i <= 14; i++ ) // AT command string containing telephone number is prepared - in[ i ] = num[ i - 3] ; - in[ 15 ] = ';'; - in[ 16 ] = '\r'; - in[ 17 ] = '\0'; - GPRS.write( in ); // AT command requesting call is sent - delay( 10000 ); // enough time is given for GSM connection, and at least one ring. - GPRS.write( "ATH\r\0" ); // AT command requesting hangup is sent - delay( 1000 ); -} - -void sendTextMessage( char number[], char messg[] ) -{ - char temp[ 27 ] = "AT + CMGS = \""; - for( q = 0; q < 12; q++ ) // for-loop is used to prepare the AT command string containing the telephone number - temp[ q + 13 ] = number[ q ]; - temp[ 25 ] = '\"'; - temp[ 26 ] = '\0'; - - GPRS.println( "AT+CMGF=1\r" ); // AT command requesting SMS in text mode is sent - delay( 1000 ); - GPRS.println( temp ); // AT command containing telephone number is sent - delay( 1000 ); - GPRS.println( messg ); //the content of the message - delay( 1000 ); - GPRS.println( (char) 26 ); //the ASCII code of the ctrl+z is 26. This character indicates the end of the message. - delay( 1000 ); -} - -void analise(byte incoming[], int length) // this function receives and analyses all text sent from the GPRS Shield to the serial line. It stores the cell number of the last caller. -{ - e = 0; // Counter that represents a letter in the buffer - done = false; // Boolean that prevents unneccessary loop revolutions - while( e < length && !done){ // while e does not surpass the last letter index of the buffer... - temp = char( incoming[e] ); // store the character at index e in a temporary char - switch( temp ){ // inspect temp - case 'R': - { - if( length > e + 3 && !callIncoming ) { // This case responds to "RING" - if(char( incoming[e + 1] ) == 'I' - && char( incoming[e + 2] ) == 'N' - && char( incoming[e + 3] ) == 'G'){ - GPRS.write("AT+CLCC\r"); // call information is requested - delay(500); // time is given for processing - GPRS.write("ATH\r"); // GPRS shield hangs up - callIncoming = true; // this ensures that a number cannot be stored in any other case than a missed call - done = true; // prevents the further operation of this while loop - } - } - } - break; - case '+': - { - if(char( buffer[ e + 1]) == '2' && length > e + 11 && callIncoming){ // this case responds to "+2", but only if the buffer contains enough characters for a valid cell number - for(t = 0; t < 12; t++) // and only if the callIncoming boolean had been triggered by a previous instance of this function - lastCaller[t] = char( buffer[ e + t ]); // the number of this caller is stored in lastCaller - lastCaller[12] = '\0'; - callIncoming = false; // now we are ready for the next call - done = true; // prevents the further operation of this while loop - } - } - break; - case 'l': - Serial.println(lastCaller); // an easy way to test this function. Simply type "l" to see the value of lastCaller (default "blank") - break; - } - e++; // buffer index is incremented - } -} - -/* -End of GPRS Shield code -*/ - - -/* -Code exclusively for RTC -*/ - -byte decToBcd( byte b ) // converts a byte from a decimal format to a binary-coded decimal -{ - return ( b / 10 << 4 ) + b % 10; -} - -boolean getBit( byte addr, int pos ) // returns a single bit from a determined location in the RTC register -{ - byte temp = getByte( addr ); - return boolean( (temp >> pos) & B00000001 ); -} - -void setBit( byte addr, int pos, boolean newBit ) // ensures that a single bit from a determined location in the RTC register is a determined value -{ - boolean oldBit = getBit( addr, pos ); // bits' current state is retrieved - byte temp = received[ 0 ]; // complete byte is retrieved. it is still left in received from the previous command - if ( oldBit != newBit ) // change is only made if the bit isnt already the correct value - { - if( newBit ) // if newBit is 1, then old bit must be 0, thus we must add an amount - temp += (B00000001 << pos); // 2 to the power of the bit position is added to the byte - else - temp -= (B00000001 << pos); // 2 to the power of the bit position is subtracted from the byte - } - setByte( addr, temp ); // the register is updated with the new byte -} - -byte getByte( byte addr ) // returns a single byte from the given address in the RTC register -{ - byte temp; - if( getBytes( addr, 1) ) // If one byte was read from the address: - temp = received[ 0 ]; // get that byte - else temp = -1; // -1 is returned as an error - return temp; -} - -boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address -{ // ^ returns false if reading failed - boolean wireWorked = false; - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to read from the given address - Wire.endTransmission(); // We want to receive, so we stop transmitting - Wire.requestFrom( DS3231_I2C_ADDRESS, amount ); // we request the given amount of bytes from the RTC - if( Wire.available() ){ - received[amount]; // prepare the array for the amount of incoming bytes - for( int i = 0; i < amount; i++){ - received[ i ] = Wire.read(); // we read the given amount of bytes - } - wireWorked = true; // everything went as planned - } - return wireWorked; -} - -void setByte( byte addr, byte newByte ) // writes a given byte to a given address in the RTCs register. convenient -{ - setBytes( addr, &newByte, 1); // call the setBytes function with the default amount = 1 -} - -void setBytes( byte addr, byte newBytes[], int amount ) // writes a given amount of bytes in a sequence starting from a given address -{ - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to start writing from the given address - for( int i = 0; i < amount; i++ ) - Wire.write( newBytes[ i ] ); // we write each byte in sequence - Wire.endTransmission(); // we're done here -} - -void getTime() // reads the current time from the register and updates the byte array containing the current time -{ - if( getBytes( DS3231_TIME_CAL_ADDR, 7) ) // if 7 bytes were read in from the time address: - { - for(int i = 0; i < 7; i++) // place each byte in it's place - time[ i ] = received[ i ]; - // The following conversions convert the values from binary-coded decimal format to regular binary: - time[ 0 ] = ( ( time[ 0 ] & B01110000 ) >> 4 ) * 10 + ( time[ 0 ] & B00001111 ); // second - time[ 1 ] = ( ( time[ 1 ] & B01110000 ) >> 4 ) * 10 + ( time[ 1 ] & B00001111 ); // minute - time[ 2 ] = ( ( time[ 2 ] & B00110000 ) >> 4 ) * 10 + ( time[ 2 ] & B00001111 ); // hour - time[ 4 ] = ( ( time[ 4 ] & B00110000 ) >> 4 ) * 10 + ( time[ 4 ] & B00001111 ); // day of month - time[ 5 ] = ( ( time[ 5 ] & B00010000 ) >> 4 ) * 10 + ( time[ 5 ] & B00001111 ); // month - time[ 6 ] = ( ( time[ 6 ] & B11110000 ) >> 4 ) * 10 + ( time[ 6 ] & B00001111 ); // year - } -} - -void setTime( byte newTime[ 7 ] ) // sets the time in the RTC register to the given values -{ - for(int i = 0; i < 7; i++) - newTime[i] = decToBcd(newTime[i]); // the time consists of 7 bytes, each which must be converted to binary-coded decimal - setBytes( DS3231_TIME_CAL_ADDR, newTime, 7 ); // bytes are sent to be written -} - -void getRTCTemperature() // reads the temperature from the register and updates the global temperature float -{ - //temp registers (11h-12h) get updated automatically every 64s - if( getBytes( DS3231_TEMPERATURE_ADDR, 2 ) ) // if 2 bytes were read from the temperature addresss - { - temperature = ( received[ 0 ] & B01111111 ); // assign the integer part of the integer - temperature += ( ( received[ 1 ] >> 6 ) * 0.25 ); // assign the fractional part of the temperature - } -} - -void gprsListen() -{ - if( GPRS.available() ) { // If the GPRS Shield is transmitting data to the Stalker... - while( GPRS.available() ) { // While there is still data left... - buffer[ count++ ] = GPRS.read(); // get the next byte of data - if ( count == 64 ) // we only handle a maximum of 64 bytes of data at a time - break; - } - Serial.write( buffer, count ); // Send the data to the serial line - analise( buffer, count ); - clearBufferArray(); // clear the buffer - count = 0; // reset counter - } - if (Serial.available()) // if the Stalker is transmitting data.... - GPRS.write(Serial.read()); // send the data to the GPRS Shield. -} - -void printTime() // updates time, and prints it in a convenient format -{ - getTime(); - Serial.print( int( time[ 3 ] ) ); // dow - Serial.print( ' ' ); - Serial.print( int( time[ 2 ] ) ); // hour - Serial.print( ':' ); - Serial.print( int( time[ 1 ] ) ); // minute - Serial.print( ':' ); - Serial.print( int( time[ 0 ] ) ); // second - Serial.print( ' ' ); - Serial.print( int( time[ 4 ] ) ); // day - Serial.print( '/' ); - Serial.print( int( time[ 5 ] ) ); // month - Serial.print( "/20" ); - Serial.print( int( time[ 6 ] ) ); // year - Serial.println(); -} - -/* -End of RTC code -*/ - -void setup() -{ - // GPRS Shield startup code - GPRS.begin( 9600 ); - delay(1000); - setPowerStateTo(1); - delay(1000); - - // RTC Startup code - Wire.begin(); - delay(1000); - - Serial.begin(9600); - delay(1000); - -} - -void loop() -{ - gprsListen(); // GPRS Shield listener. Todo: replace w interrupt - getTime(); // Updates the time. Todo: replace w interrupt -} diff --git a/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt b/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt deleted file mode 100644 index 62fa1ac6..00000000 --- a/test/sketch4/CharWithEscapedDoubleQuote.preprocessed.txt +++ /dev/null @@ -1,385 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include // required to send and receive AT commands from the GPRS Shield -#include // required for I2C communication with the RTC - -// pin numbers for RTC -#define DS3231_I2C_ADDRESS 104 // 0x68 // Address for RTC -#define DS3231_TIME_CAL_ADDR 0 // 0x00 -#define DS3231_ALARM1_ADDR 7 // 0x07 -#define DS3231_ALARM2_ADDR 11 // 0x0B -#define DS3231_CONTROL_ADDR 14 // 0x0E -#define DS3231_STATUS_ADDR 15 // 0x0F -//#define DS3231_AGING_OFFSET_ADDR 16 // 0x10 -#define DS3231_TEMPERATURE_ADDR 17 // 0x11 - -// Declarations for GPRS shield -SoftwareSerial GPRS( 7, 8 ); // A softwareSerial line is defined for the GPRS Shield -byte buffer[ 64 ]; // Buffer is used to transfer data from the GPRS line to the serial line -int count = 0, e = 0, count2 = 0, t = 0, q; -char temp, lastCaller[13] = "blank"; -boolean callIncoming = false, done; - -// Declarations for RTC -byte time[ 7 ]; // second, minute, hour, dow, day, month, year -byte time_A1[ 5 ]; // second_A1, minute_A1, hour_A1, day_A1, DY/DT -byte time_A2[ 4 ]; // minute_A2, hour_A2, day_A2, DY/DT -byte received[1]; // used to catch bytes sent from the clock -float temperature; // clock temperature is updated every 64 s - -// Declarations for RemoteCallLogger -char telescopeNames[6][4]; - -/* -Code Exclusively for GPRS shield: -*/ - -// -// Default set of instructions for GPRS Shield power control -// - -#line 39 {{QuoteCppString .sketch.MainFile.Name}} -void setPowerStateTo( int newState ); -#line 64 {{QuoteCppString .sketch.MainFile.Name}} -int getPowerState(); -#line 75 {{QuoteCppString .sketch.MainFile.Name}} -void powerUpOrDown(); -#line 90 {{QuoteCppString .sketch.MainFile.Name}} -void clearBufferArray(); -#line 96 {{QuoteCppString .sketch.MainFile.Name}} -void makeMissedCall( char num[] ); -#line 111 {{QuoteCppString .sketch.MainFile.Name}} -void sendTextMessage( char number[], char messg[] ); -#line 129 {{QuoteCppString .sketch.MainFile.Name}} -void analise(byte incoming[], int length); -#line 179 {{QuoteCppString .sketch.MainFile.Name}} -byte decToBcd( byte b ); -#line 184 {{QuoteCppString .sketch.MainFile.Name}} -boolean getBit( byte addr, int pos ); -#line 190 {{QuoteCppString .sketch.MainFile.Name}} -void setBit( byte addr, int pos, boolean newBit ); -#line 204 {{QuoteCppString .sketch.MainFile.Name}} -byte getByte( byte addr ); -#line 213 {{QuoteCppString .sketch.MainFile.Name}} -boolean getBytes( byte addr, int amount ); -#line 230 {{QuoteCppString .sketch.MainFile.Name}} -void setByte( byte addr, byte newByte ); -#line 235 {{QuoteCppString .sketch.MainFile.Name}} -void setBytes( byte addr, byte newBytes[], int amount ); -#line 244 {{QuoteCppString .sketch.MainFile.Name}} -void getTime(); -#line 260 {{QuoteCppString .sketch.MainFile.Name}} -void setTime( byte newTime[ 7 ] ); -#line 267 {{QuoteCppString .sketch.MainFile.Name}} -void getRTCTemperature(); -#line 277 {{QuoteCppString .sketch.MainFile.Name}} -void gprsListen(); -#line 294 {{QuoteCppString .sketch.MainFile.Name}} -void printTime(); -#line 317 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 334 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 39 {{QuoteCppString .sketch.MainFile.Name}} -void setPowerStateTo( int newState ) -{ - if( newState != 1 && newState != 0 ) { // tests for an invalid state. In this case no change is made to powerstate - Serial.print( "Error: Invalid powerstate. Current powerstate = " ); - Serial.print( getPowerState() ); - Serial.print( "\n" ); - } - else { - if( newState == getPowerState() ) { // if the requested powerstate is already in effect, no action is taken - Serial.print( "Powerstate = " ); - Serial.print( newState ); - Serial.print( " remains unchanged.\n" ); - } - else { - powerUpOrDown(); // This is the only case where the powerstate is changed - Serial.print( "Powerstate changed from " ); - Serial.print( 1 - newState ); - Serial.print( " to " ); - Serial.print( newState ); - Serial.print( "\n" ); - } - } - delay( 5000 ); // for startup -} - -int getPowerState() // returns 0 if GPRS Shield is off, and 1 if GPRS Shield is on. This corresponds to the constant HIGH LOW enumeration -{ - int ret; - if ( digitalRead(18) == 0 && digitalRead(19) == 0 ) // tests pins 18 and 19 for activity. See ExFoundImportantPins sketch to find out why - ret = 1; - else - ret = 0; - - return ret; -} - -void powerUpOrDown() // toggle the power of the shield -{ - pinMode( 9, OUTPUT ); - digitalWrite( 9, LOW ); - delay( 1000 ); - digitalWrite( 9, HIGH ); - delay( 2000 ); - digitalWrite( 9, LOW ); - delay( 3000 ); -} - -// -// End of default power control -// - -void clearBufferArray() // gives each element in the buffer array a null value -{ - for( int i = 0; i < count; i++ ) - buffer[ i ] = NULL; -} - -void makeMissedCall( char num[] ) -{ - int i; - char in[ 18 ] = "ATD"; - for( i = 3; i <= 14; i++ ) // AT command string containing telephone number is prepared - in[ i ] = num[ i - 3] ; - in[ 15 ] = ';'; - in[ 16 ] = '\r'; - in[ 17 ] = '\0'; - GPRS.write( in ); // AT command requesting call is sent - delay( 10000 ); // enough time is given for GSM connection, and at least one ring. - GPRS.write( "ATH\r\0" ); // AT command requesting hangup is sent - delay( 1000 ); -} - -void sendTextMessage( char number[], char messg[] ) -{ - char temp[ 27 ] = "AT + CMGS = \""; - for( q = 0; q < 12; q++ ) // for-loop is used to prepare the AT command string containing the telephone number - temp[ q + 13 ] = number[ q ]; - temp[ 25 ] = '\"'; - temp[ 26 ] = '\0'; - - GPRS.println( "AT+CMGF=1\r" ); // AT command requesting SMS in text mode is sent - delay( 1000 ); - GPRS.println( temp ); // AT command containing telephone number is sent - delay( 1000 ); - GPRS.println( messg ); //the content of the message - delay( 1000 ); - GPRS.println( (char) 26 ); //the ASCII code of the ctrl+z is 26. This character indicates the end of the message. - delay( 1000 ); -} - -void analise(byte incoming[], int length) // this function receives and analyses all text sent from the GPRS Shield to the serial line. It stores the cell number of the last caller. -{ - e = 0; // Counter that represents a letter in the buffer - done = false; // Boolean that prevents unneccessary loop revolutions - while( e < length && !done){ // while e does not surpass the last letter index of the buffer... - temp = char( incoming[e] ); // store the character at index e in a temporary char - switch( temp ){ // inspect temp - case 'R': - { - if( length > e + 3 && !callIncoming ) { // This case responds to "RING" - if(char( incoming[e + 1] ) == 'I' - && char( incoming[e + 2] ) == 'N' - && char( incoming[e + 3] ) == 'G'){ - GPRS.write("AT+CLCC\r"); // call information is requested - delay(500); // time is given for processing - GPRS.write("ATH\r"); // GPRS shield hangs up - callIncoming = true; // this ensures that a number cannot be stored in any other case than a missed call - done = true; // prevents the further operation of this while loop - } - } - } - break; - case '+': - { - if(char( buffer[ e + 1]) == '2' && length > e + 11 && callIncoming){ // this case responds to "+2", but only if the buffer contains enough characters for a valid cell number - for(t = 0; t < 12; t++) // and only if the callIncoming boolean had been triggered by a previous instance of this function - lastCaller[t] = char( buffer[ e + t ]); // the number of this caller is stored in lastCaller - lastCaller[12] = '\0'; - callIncoming = false; // now we are ready for the next call - done = true; // prevents the further operation of this while loop - } - } - break; - case 'l': - Serial.println(lastCaller); // an easy way to test this function. Simply type "l" to see the value of lastCaller (default "blank") - break; - } - e++; // buffer index is incremented - } -} - -/* -End of GPRS Shield code -*/ - - -/* -Code exclusively for RTC -*/ - -byte decToBcd( byte b ) // converts a byte from a decimal format to a binary-coded decimal -{ - return ( b / 10 << 4 ) + b % 10; -} - -boolean getBit( byte addr, int pos ) // returns a single bit from a determined location in the RTC register -{ - byte temp = getByte( addr ); - return boolean( (temp >> pos) & B00000001 ); -} - -void setBit( byte addr, int pos, boolean newBit ) // ensures that a single bit from a determined location in the RTC register is a determined value -{ - boolean oldBit = getBit( addr, pos ); // bits' current state is retrieved - byte temp = received[ 0 ]; // complete byte is retrieved. it is still left in received from the previous command - if ( oldBit != newBit ) // change is only made if the bit isnt already the correct value - { - if( newBit ) // if newBit is 1, then old bit must be 0, thus we must add an amount - temp += (B00000001 << pos); // 2 to the power of the bit position is added to the byte - else - temp -= (B00000001 << pos); // 2 to the power of the bit position is subtracted from the byte - } - setByte( addr, temp ); // the register is updated with the new byte -} - -byte getByte( byte addr ) // returns a single byte from the given address in the RTC register -{ - byte temp; - if( getBytes( addr, 1) ) // If one byte was read from the address: - temp = received[ 0 ]; // get that byte - else temp = -1; // -1 is returned as an error - return temp; -} - -boolean getBytes( byte addr, int amount ) // updates the byte array "received" with the given amount of bytes, read from the given address -{ // ^ returns false if reading failed - boolean wireWorked = false; - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to read from the given address - Wire.endTransmission(); // We want to receive, so we stop transmitting - Wire.requestFrom( DS3231_I2C_ADDRESS, amount ); // we request the given amount of bytes from the RTC - if( Wire.available() ){ - received[amount]; // prepare the array for the amount of incoming bytes - for( int i = 0; i < amount; i++){ - received[ i ] = Wire.read(); // we read the given amount of bytes - } - wireWorked = true; // everything went as planned - } - return wireWorked; -} - -void setByte( byte addr, byte newByte ) // writes a given byte to a given address in the RTCs register. convenient -{ - setBytes( addr, &newByte, 1); // call the setBytes function with the default amount = 1 -} - -void setBytes( byte addr, byte newBytes[], int amount ) // writes a given amount of bytes in a sequence starting from a given address -{ - Wire.beginTransmission( DS3231_I2C_ADDRESS ); // We transmit to the RTC - Wire.write( addr ); // We want to start writing from the given address - for( int i = 0; i < amount; i++ ) - Wire.write( newBytes[ i ] ); // we write each byte in sequence - Wire.endTransmission(); // we're done here -} - -void getTime() // reads the current time from the register and updates the byte array containing the current time -{ - if( getBytes( DS3231_TIME_CAL_ADDR, 7) ) // if 7 bytes were read in from the time address: - { - for(int i = 0; i < 7; i++) // place each byte in it's place - time[ i ] = received[ i ]; - // The following conversions convert the values from binary-coded decimal format to regular binary: - time[ 0 ] = ( ( time[ 0 ] & B01110000 ) >> 4 ) * 10 + ( time[ 0 ] & B00001111 ); // second - time[ 1 ] = ( ( time[ 1 ] & B01110000 ) >> 4 ) * 10 + ( time[ 1 ] & B00001111 ); // minute - time[ 2 ] = ( ( time[ 2 ] & B00110000 ) >> 4 ) * 10 + ( time[ 2 ] & B00001111 ); // hour - time[ 4 ] = ( ( time[ 4 ] & B00110000 ) >> 4 ) * 10 + ( time[ 4 ] & B00001111 ); // day of month - time[ 5 ] = ( ( time[ 5 ] & B00010000 ) >> 4 ) * 10 + ( time[ 5 ] & B00001111 ); // month - time[ 6 ] = ( ( time[ 6 ] & B11110000 ) >> 4 ) * 10 + ( time[ 6 ] & B00001111 ); // year - } -} - -void setTime( byte newTime[ 7 ] ) // sets the time in the RTC register to the given values -{ - for(int i = 0; i < 7; i++) - newTime[i] = decToBcd(newTime[i]); // the time consists of 7 bytes, each which must be converted to binary-coded decimal - setBytes( DS3231_TIME_CAL_ADDR, newTime, 7 ); // bytes are sent to be written -} - -void getRTCTemperature() // reads the temperature from the register and updates the global temperature float -{ - //temp registers (11h-12h) get updated automatically every 64s - if( getBytes( DS3231_TEMPERATURE_ADDR, 2 ) ) // if 2 bytes were read from the temperature addresss - { - temperature = ( received[ 0 ] & B01111111 ); // assign the integer part of the integer - temperature += ( ( received[ 1 ] >> 6 ) * 0.25 ); // assign the fractional part of the temperature - } -} - -void gprsListen() -{ - if( GPRS.available() ) { // If the GPRS Shield is transmitting data to the Stalker... - while( GPRS.available() ) { // While there is still data left... - buffer[ count++ ] = GPRS.read(); // get the next byte of data - if ( count == 64 ) // we only handle a maximum of 64 bytes of data at a time - break; - } - Serial.write( buffer, count ); // Send the data to the serial line - analise( buffer, count ); - clearBufferArray(); // clear the buffer - count = 0; // reset counter - } - if (Serial.available()) // if the Stalker is transmitting data.... - GPRS.write(Serial.read()); // send the data to the GPRS Shield. -} - -void printTime() // updates time, and prints it in a convenient format -{ - getTime(); - Serial.print( int( time[ 3 ] ) ); // dow - Serial.print( ' ' ); - Serial.print( int( time[ 2 ] ) ); // hour - Serial.print( ':' ); - Serial.print( int( time[ 1 ] ) ); // minute - Serial.print( ':' ); - Serial.print( int( time[ 0 ] ) ); // second - Serial.print( ' ' ); - Serial.print( int( time[ 4 ] ) ); // day - Serial.print( '/' ); - Serial.print( int( time[ 5 ] ) ); // month - Serial.print( "/20" ); - Serial.print( int( time[ 6 ] ) ); // year - Serial.println(); -} - -/* -End of RTC code -*/ - -void setup() -{ - // GPRS Shield startup code - GPRS.begin( 9600 ); - delay(1000); - setPowerStateTo(1); - delay(1000); - - // RTC Startup code - Wire.begin(); - delay(1000); - - Serial.begin(9600); - delay(1000); - -} - -void loop() -{ - gprsListen(); // GPRS Shield listener. Todo: replace w interrupt - getTime(); // Updates the time. Todo: replace w interrupt -} - diff --git a/test/sketch5/IncludeBetweenMultilineComment.ino b/test/sketch5/IncludeBetweenMultilineComment.ino deleted file mode 100644 index 65909275..00000000 --- a/test/sketch5/IncludeBetweenMultilineComment.ino +++ /dev/null @@ -1,15 +0,0 @@ -#include -/* -#include -*/ -CapacitiveSensor cs_13_8 = CapacitiveSensor(13,8); -void setup() -{ - Serial.begin(9600); -} -void loop() -{ - long total1 = cs_13_8.capacitiveSensor(30); - Serial.println(total1); - delay(100); -} diff --git a/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt b/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt deleted file mode 100644 index a19528dc..00000000 --- a/test/sketch5/IncludeBetweenMultilineComment.preprocessed.txt +++ /dev/null @@ -1,24 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include -/* -#include -*/ -CapacitiveSensor cs_13_8 = CapacitiveSensor(13,8); -#line 6 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 6 {{QuoteCppString .sketch.MainFile.Name}} -void setup() -{ - Serial.begin(9600); -} -void loop() -{ - long total1 = cs_13_8.capacitiveSensor(30); - Serial.println(total1); - delay(100); -} - diff --git a/test/sketch6/LineContinuations.ino b/test/sketch6/LineContinuations.ino deleted file mode 100644 index 8611603e..00000000 --- a/test/sketch6/LineContinuations.ino +++ /dev/null @@ -1,34 +0,0 @@ -const char *foo = "\ -hello \ -world\n"; - -//" delete this comment line and the IDE parser will crash - -void setup() -{ -} - -void loop() -{ -} -/* -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -*/ diff --git a/test/sketch6/LineContinuations.preprocessed.txt b/test/sketch6/LineContinuations.preprocessed.txt deleted file mode 100644 index 1d584583..00000000 --- a/test/sketch6/LineContinuations.preprocessed.txt +++ /dev/null @@ -1,43 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -const char *foo = "\ -hello \ -world\n"; - -//" delete this comment line and the IDE parser will crash - -#line 7 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 11 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 7 {{QuoteCppString .sketch.MainFile.Name}} -void setup() -{ -} - -void loop() -{ -} -/* -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx -*/ - diff --git a/test/sketch7/StringWithComment.ino b/test/sketch7/StringWithComment.ino deleted file mode 100644 index 88b94e1d..00000000 --- a/test/sketch7/StringWithComment.ino +++ /dev/null @@ -1,13 +0,0 @@ -void setup() { - // put your setup code here, to run once: - // "comment with a double quote - /* \" other comment with double quote */ - Serial.println("Accept: */*"); - Serial.println("Accept: \" */*"); - Serial.println("Accept: \\"); // */*"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} \ No newline at end of file diff --git a/test/sketch7/StringWithComment.preprocessed.txt b/test/sketch7/StringWithComment.preprocessed.txt deleted file mode 100644 index f4432fcd..00000000 --- a/test/sketch7/StringWithComment.preprocessed.txt +++ /dev/null @@ -1,21 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - // put your setup code here, to run once: - // "comment with a double quote - /* \" other comment with double quote */ - Serial.println("Accept: */*"); - Serial.println("Accept: \" */*"); - Serial.println("Accept: \\"); // */*"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/test/sketch8/SketchWithStruct.ino b/test/sketch8/SketchWithStruct.ino deleted file mode 100644 index 05f277da..00000000 --- a/test/sketch8/SketchWithStruct.ino +++ /dev/null @@ -1,22 +0,0 @@ -/* START CODE */ - -struct A_NEW_TYPE { - int a = 10; - int b; - int c; -} foo; - -void setup() { - -} - -void loop() { - dostuff(&foo); -} - -void dostuff (A_NEW_TYPE * bar) -{ - Serial.print("bar.a: "); - Serial.print(bar->a); -} -/* END CODE */ \ No newline at end of file diff --git a/test/sketch8/SketchWithStruct.preprocessed.txt b/test/sketch8/SketchWithStruct.preprocessed.txt deleted file mode 100644 index 35302e16..00000000 --- a/test/sketch8/SketchWithStruct.preprocessed.txt +++ /dev/null @@ -1,32 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -/* START CODE */ - -struct A_NEW_TYPE { - int a = 10; - int b; - int c; -} foo; - -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 17 {{QuoteCppString .sketch.MainFile.Name}} -void dostuff (A_NEW_TYPE * bar); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - dostuff(&foo); -} - -void dostuff (A_NEW_TYPE * bar) -{ - Serial.print("bar.a: "); - Serial.print(bar->a); -} -/* END CODE */ diff --git a/test/sketch9/sketch.ino b/test/sketch9/sketch.ino deleted file mode 100644 index 105b1014..00000000 --- a/test/sketch9/sketch.ino +++ /dev/null @@ -1,6 +0,0 @@ -#include -#include -#include - -void setup() {} -void loop() {} \ No newline at end of file diff --git a/test/sketch_class_function/sketch_class_function.ino b/test/sketch_class_function/sketch_class_function.ino deleted file mode 100644 index 45250090..00000000 --- a/test/sketch_class_function/sketch_class_function.ino +++ /dev/null @@ -1,8 +0,0 @@ -class test { - void asdf() {} -}; -void setup() { - asdf(); -} -void loop() {} -void asdf() {} \ No newline at end of file diff --git a/test/sketch_loader_test.go b/test/sketch_loader_test.go deleted file mode 100644 index 0e98d79f..00000000 --- a/test/sketch_loader_test.go +++ /dev/null @@ -1,178 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestLoadSketchWithFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch1"), - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketchNonExistentPath(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("asdasd78128123981723981273asdasd"), - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketch(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch1", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") - - require.Equal(t, 2, len(sketch.OtherSketchFiles)) - require.Contains(t, sketch.OtherSketchFiles[0].Name.String(), "old.pde") - require.Contains(t, sketch.OtherSketchFiles[1].Name.String(), "other.ino") - - require.Equal(t, 3, len(sketch.AdditionalFiles)) - require.Contains(t, sketch.AdditionalFiles[0].Name.String(), "header.h") - require.Contains(t, sketch.AdditionalFiles[1].Name.String(), "s_file.S") - require.Contains(t, sketch.AdditionalFiles[2].Name.String(), "helper.h") -} - -func TestFailToLoadSketchFromFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("./sketch1"), - } - - loader := builder.SketchLoader{} - err := loader.Run(ctx) - require.Error(t, err) - require.Nil(t, ctx.Sketch) -} - -func TestLoadSketchFromFolder(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch_with_subfolders"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name.String(), "sketch_with_subfolders.ino") - - require.Equal(t, 0, len(sketch.OtherSketchFiles)) - - require.Equal(t, 4, len(sketch.AdditionalFiles)) - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[0].Name.String()), "sketch_with_subfolders/src/subfolder/other.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[1].Name.String()), "sketch_with_subfolders/src/subfolder/other.h") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[2].Name.String()), "sketch_with_subfolders/subfolder/dont_load_me.cpp") - require.Contains(t, filepath.ToSlash(sketch.AdditionalFiles[3].Name.String()), "sketch_with_subfolders/subfolder/other.h") -} - -func TestLoadSketchWithBackup(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch_with_backup_files", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") - - require.Equal(t, 0, len(sketch.AdditionalFiles)) - require.Equal(t, 0, len(sketch.OtherSketchFiles)) -} - -func TestLoadSketchWithMacOSXGarbage(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch_with_macosx_garbage", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - sketch := ctx.Sketch - require.NotNil(t, sketch) - - require.Contains(t, sketch.MainFile.Name.String(), "sketch.ino") - - require.Equal(t, 0, len(sketch.AdditionalFiles)) - require.Equal(t, 0, len(sketch.OtherSketchFiles)) -} diff --git a/test/sketch_no_functions/main.ino b/test/sketch_no_functions/main.ino deleted file mode 100644 index b11f61cc..00000000 --- a/test/sketch_no_functions/main.ino +++ /dev/null @@ -1,8 +0,0 @@ -/* - -Test sketch - - - -*/ - diff --git a/test/sketch_no_functions_two_files/main.ino b/test/sketch_no_functions_two_files/main.ino deleted file mode 100644 index b11f61cc..00000000 --- a/test/sketch_no_functions_two_files/main.ino +++ /dev/null @@ -1,8 +0,0 @@ -/* - -Test sketch - - - -*/ - diff --git a/test/sketch_no_functions_two_files/partb.ino b/test/sketch_no_functions_two_files/partb.ino deleted file mode 100644 index 0e272748..00000000 --- a/test/sketch_no_functions_two_files/partb.ino +++ /dev/null @@ -1,4 +0,0 @@ -#include - -int a = 0; -int b = 0; \ No newline at end of file diff --git a/test/sketch_source_merger_test.go b/test/sketch_source_merger_test.go deleted file mode 100644 index 44cdb5f7..00000000 --- a/test/sketch_source_merger_test.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "path/filepath" - "strings" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestMergeSketch(t *testing.T) { - ctx := &types.Context{ - SketchLocation: paths.New("sketch1", "sketch.ino"), - } - - commands := []types.Command{ - &builder.SketchLoader{}, - &builder.SketchSourceMerger{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - source := ctx.Source - - expected_source := LoadAndInterpolate(t, filepath.Join("sketch1", "merged_sketch.txt"), ctx) - require.Equal(t, expected_source, strings.Replace(source, "\r\n", "\n", -1)) -} diff --git a/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino b/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino deleted file mode 100644 index 106c39f2..00000000 --- a/test/sketch_that_checks_if_SPI_has_transactions/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -#include - -#if !defined(SPI_HAS_TRANSACTION) || !SPI_HAS_TRANSACTION -#error "Where is my SPI_HAS_TRANSACTION!?!?" -#endif - -void setup() {} -void loop() {} diff --git a/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino b/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino deleted file mode 100644 index 68092faa..00000000 --- a/test/sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet/sketch.ino +++ /dev/null @@ -1,9 +0,0 @@ -#include -#include - -#if !defined(SPI_HAS_TRANSACTION) || !SPI_HAS_TRANSACTION -#error "Where is my SPI_HAS_TRANSACTION!?!?" -#endif - -void setup() {} -void loop() {} diff --git a/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino b/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino deleted file mode 100644 index 515d9fe5..00000000 --- a/test/sketch_that_includes_arduino_h/sketch_that_includes_arduino_h.ino +++ /dev/null @@ -1,14 +0,0 @@ -// Arduino.h should not be automatically included by the Arduino -// preprocessor before the explicit include line in this sketch. - -#if defined(HIGH) -#error Arduino.h seems to be automatically included -#endif - - # include - -void setup() { -} - -void loop() { -} diff --git a/test/sketch_usbhost/sketch_usbhost.ino b/test/sketch_usbhost/sketch_usbhost.ino deleted file mode 100644 index 47d6ccd6..00000000 --- a/test/sketch_usbhost/sketch_usbhost.ino +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include -#include - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_backup_files/backup/sketch.ino b/test/sketch_with_backup_files/backup/sketch.ino deleted file mode 100644 index 86875cfc..00000000 --- a/test/sketch_with_backup_files/backup/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -broken diff --git a/test/sketch_with_backup_files/sketch.ino b/test/sketch_with_backup_files/sketch.ino deleted file mode 100644 index 0d5e0f5c..00000000 --- a/test/sketch_with_backup_files/sketch.ino +++ /dev/null @@ -1,7 +0,0 @@ -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_class/sketch.ino b/test/sketch_with_class/sketch.ino deleted file mode 100644 index 97f31071..00000000 --- a/test/sketch_with_class/sketch.ino +++ /dev/null @@ -1,19 +0,0 @@ -class Rectangle { - int width, height; - public: - void set_values (int,int); - int area() {return width*height;} -}; - -void Rectangle::set_values (int x, int y) { - width = x; - height = y; -} - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino b/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino deleted file mode 100644 index d933816a..00000000 --- a/test/sketch_with_class_and_method_substring/sketch_with_class_and_method_substring.ino +++ /dev/null @@ -1,13 +0,0 @@ -class Foo { -int blooper(int x) { return x+1; } -}; - -Foo foo; - -void setup() { - foo.setup(); -} - -void loop() { - foo.loop(); -} diff --git a/test/sketch_with_config/config.h b/test/sketch_with_config/config.h deleted file mode 100644 index 2998979d..00000000 --- a/test/sketch_with_config/config.h +++ /dev/null @@ -1 +0,0 @@ -#define DEBUG \ No newline at end of file diff --git a/test/sketch_with_config/sketch_with_config.ino b/test/sketch_with_config/sketch_with_config.ino deleted file mode 100644 index 08390371..00000000 --- a/test/sketch_with_config/sketch_with_config.ino +++ /dev/null @@ -1,19 +0,0 @@ -#include "config.h" - -#ifdef DEBUG -#include "src/includes/de bug.h" -#endif - -#ifdef UNDEF -#error -#endif - -#include - -void setup() { - -} - -void loop() { - -} diff --git a/test/sketch_with_config/sketch_with_config.preprocessed.txt b/test/sketch_with_config/sketch_with_config.preprocessed.txt deleted file mode 100644 index 2d56efd3..00000000 --- a/test/sketch_with_config/sketch_with_config.preprocessed.txt +++ /dev/null @@ -1,28 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#include "config.h" - -#ifdef DEBUG -#include "src/includes/de bug.h" -#endif - -#ifdef UNDEF -#error -#endif - -#include - -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 17 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 13 {{QuoteCppString .sketch.MainFile.Name}} -void setup() { - -} - -void loop() { - -} - diff --git a/test/sketch_with_config/src/includes/de bug.cpp b/test/sketch_with_config/src/includes/de bug.cpp deleted file mode 100644 index e4d29505..00000000 --- a/test/sketch_with_config/src/includes/de bug.cpp +++ /dev/null @@ -1,5 +0,0 @@ -#pragma debug - -void debug() { - //add debug code -} \ No newline at end of file diff --git a/test/sketch_with_config/src/includes/de bug.h b/test/sketch_with_config/src/includes/de bug.h deleted file mode 100644 index e69de29b..00000000 diff --git a/test/sketch_with_const/sketch.ino b/test/sketch_with_const/sketch.ino deleted file mode 100644 index f4f52ca0..00000000 --- a/test/sketch_with_const/sketch.ino +++ /dev/null @@ -1,10 +0,0 @@ -void setup() {} -void loop() {} - -const __FlashStringHelper* test() {} - -const int test3() {} - -volatile __FlashStringHelper* test2() {} - -volatile int test4() {} diff --git a/test/sketch_with_default_args/sketch.ino b/test/sketch_with_default_args/sketch.ino deleted file mode 100644 index 6a5ee7cc..00000000 --- a/test/sketch_with_default_args/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -void test(int x = 1) { -} - -void setup() { -} - -void loop() { -} \ No newline at end of file diff --git a/test/sketch_with_dependend_libraries/sketch.ino b/test/sketch_with_dependend_libraries/sketch.ino deleted file mode 100644 index ad070592..00000000 --- a/test/sketch_with_dependend_libraries/sketch.ino +++ /dev/null @@ -1 +0,0 @@ -#include \ No newline at end of file diff --git a/test/sketch_with_enum_class/sketch_with_enum_class.ino b/test/sketch_with_enum_class/sketch_with_enum_class.ino deleted file mode 100644 index 54c3dfbb..00000000 --- a/test/sketch_with_enum_class/sketch_with_enum_class.ino +++ /dev/null @@ -1,19 +0,0 @@ -void test() { - test2(); -} - -enum class MyEnum -{ - AValue = 0, - AnotherValue = 1 -}; - -void test2() { -} - -void setup() { -} - -void loop() { -} - diff --git a/test/sketch_with_externC/sketch_with_externC.ino b/test/sketch_with_externC/sketch_with_externC.ino deleted file mode 100644 index 8e6c53ea..00000000 --- a/test/sketch_with_externC/sketch_with_externC.ino +++ /dev/null @@ -1,11 +0,0 @@ -void setup() { - // put your setup code here, to run once: - test(); -} - -void loop() { - // put your main code here, to run repeatedly: - -} - -extern "C" void test() {} \ No newline at end of file diff --git a/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino b/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino deleted file mode 100644 index e911a4b0..00000000 --- a/test/sketch_with_externC_multiline/sketch_with_externC_multiline.ino +++ /dev/null @@ -1,34 +0,0 @@ -void setup() { - // put your setup code here, to run once: - } - - void loop() { - // put your main code here, to run repeatedly: - test2(); - test4(); - test6(); - test7(); - test10(); - } - - extern "C" { - void test2() {} - } - - extern "C" - { - void test4() {} - } - - extern "C" - - { - void test6() {} - } - - // this function should not have C linkage - void test7() {} - - extern "C" void test10() { - - }; \ No newline at end of file diff --git a/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino b/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino deleted file mode 100644 index eb83500c..00000000 --- a/test/sketch_with_fake_function_pointer/sketch_with_fake_function_pointer.ino +++ /dev/null @@ -1,19 +0,0 @@ -template< uint16_t nBuffSize > - class Foo{ - public: - - template< uint16_t N > - Foo &operator +=( const Foo &ref ){ - //... - return *this; - } -}; - -Foo<64> a; -Foo<32> b; - -void setup(){ - a += b; -} - -void loop(){} diff --git a/test/sketch_with_function_pointer/CallbackBug.h b/test/sketch_with_function_pointer/CallbackBug.h deleted file mode 100644 index cc8ee18b..00000000 --- a/test/sketch_with_function_pointer/CallbackBug.h +++ /dev/null @@ -1,5 +0,0 @@ -class Task { - public: - Task(void (*aCallback)()) {}; -}; - diff --git a/test/sketch_with_function_pointer/sketch.ino b/test/sketch_with_function_pointer/sketch.ino deleted file mode 100644 index aa50e6e0..00000000 --- a/test/sketch_with_function_pointer/sketch.ino +++ /dev/null @@ -1,5 +0,0 @@ -#include "CallbackBug.h" -Task t1(&t1Callback); -void t1Callback() {} -void setup() {} -void loop() {} diff --git a/test/sketch_with_function_signature_inside_ifdef/sketch.ino b/test/sketch_with_function_signature_inside_ifdef/sketch.ino deleted file mode 100644 index 809f2b5a..00000000 --- a/test/sketch_with_function_signature_inside_ifdef/sketch.ino +++ /dev/null @@ -1,20 +0,0 @@ -void setup() {} - -void loop() { - // Visualize leds via Adalight - int8_t newData = adalight(); - -} - - -//#define ADALIGHT_USE_TEMPLATE - -#ifdef ADALIGHT_USE_TEMPLATE -int16_t adalight() -#else -int8_t adalight() -#endif -{ - // Flag if the leds got a new frame that should be updated - return 0; -} diff --git a/test/sketch_with_ifdef/sketch.ino b/test/sketch_with_ifdef/sketch.ino deleted file mode 100644 index 3d3e2f49..00000000 --- a/test/sketch_with_ifdef/sketch.ino +++ /dev/null @@ -1,15 +0,0 @@ -#if __SAM3X8E__ -void ifBranch() { -} -#else -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} \ No newline at end of file diff --git a/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt b/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt deleted file mode 100644 index 2eb36912..00000000 --- a/test/sketch_with_ifdef/sketch.preprocessed.SAM.txt +++ /dev/null @@ -1,29 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#if __SAM3X8E__ -#line 2 {{QuoteCppString .sketch.MainFile.Name}} -void ifBranch(); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void f1(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void f2(); -#line 12 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 14 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 2 {{QuoteCppString .sketch.MainFile.Name}} -void ifBranch() { -} -#else -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} diff --git a/test/sketch_with_ifdef/sketch.preprocessed.txt b/test/sketch_with_ifdef/sketch.preprocessed.txt deleted file mode 100644 index 31c86758..00000000 --- a/test/sketch_with_ifdef/sketch.preprocessed.txt +++ /dev/null @@ -1,29 +0,0 @@ -#include -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#line 1 {{QuoteCppString .sketch.MainFile.Name}} -#if __SAM3X8E__ -void ifBranch() { -} -#else -#line 5 {{QuoteCppString .sketch.MainFile.Name}} -void elseBranch(); -#line 9 {{QuoteCppString .sketch.MainFile.Name}} -void f1(); -#line 10 {{QuoteCppString .sketch.MainFile.Name}} -void f2(); -#line 12 {{QuoteCppString .sketch.MainFile.Name}} -void setup(); -#line 14 {{QuoteCppString .sketch.MainFile.Name}} -void loop(); -#line 5 {{QuoteCppString .sketch.MainFile.Name}} -void elseBranch() { -} -#endif - -void f1(){ f2(); } -void f2(){;} - -void setup() { -} -void loop() { -} diff --git a/test/sketch_with_inline_function/sketch.ino b/test/sketch_with_inline_function/sketch.ino deleted file mode 100644 index f0a25e69..00000000 --- a/test/sketch_with_inline_function/sketch.ino +++ /dev/null @@ -1,14 +0,0 @@ -void setup() {} -void loop() {} - -short unsigned int testInt(){ - -} - -static inline int8_t testInline(){ - -} - -__attribute__((always_inline)) uint8_t testAttribute() { - -} diff --git a/test/sketch_with_macosx_garbage/.#sketch.ino b/test/sketch_with_macosx_garbage/.#sketch.ino deleted file mode 100644 index 71048175..00000000 --- a/test/sketch_with_macosx_garbage/.#sketch.ino +++ /dev/null @@ -1,2 +0,0 @@ -void setup() -void loop) } \ No newline at end of file diff --git a/test/sketch_with_macosx_garbage/sketch.ino b/test/sketch_with_macosx_garbage/sketch.ino deleted file mode 100644 index 4f069e3b..00000000 --- a/test/sketch_with_macosx_garbage/sketch.ino +++ /dev/null @@ -1,2 +0,0 @@ -void setup() {} -void loop() {} \ No newline at end of file diff --git a/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino b/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino deleted file mode 100644 index 85f7fb6d..00000000 --- a/test/sketch_with_multiline_prototypes/sketch_with_multiline_prototypes.ino +++ /dev/null @@ -1,53 +0,0 @@ -void setup() { - myctagstestfunc(1,2,3,4); - test(); - test3(); - test5(1,2,3); - test7(); - test8(); - test9(42, 42); - test10(0,0,0); -} - -void myctagstestfunc(int a, -int b, -int c, -int d) { } - -void loop() {} - -void -test() {} - -void -// comment -test3() {} - -void -test5(int a, - int b, - int c) -{ - -} - -void /* comment */ -test7() {} - -void -/* -multi -line -comment -*/ -test8() {} - - void - /* comment */ - test9(int a, - int b) {} - -void test10(int a, // this - int b, // doesn't - int c // work - ) {} \ No newline at end of file diff --git a/test/sketch_with_multiline_template/sketch_with_multiline_template.ino b/test/sketch_with_multiline_template/sketch_with_multiline_template.ino deleted file mode 100644 index a3ddecdf..00000000 --- a/test/sketch_with_multiline_template/sketch_with_multiline_template.ino +++ /dev/null @@ -1,10 +0,0 @@ -template< typename T > -T func(T t){ - return t * t; -} - -void setup() { - func( 12.34f ); -} - -void loop() {} diff --git a/test/sketch_with_namespace/sketch.ino b/test/sketch_with_namespace/sketch.ino deleted file mode 100644 index 178ba312..00000000 --- a/test/sketch_with_namespace/sketch.ino +++ /dev/null @@ -1,8 +0,0 @@ -namespace Test { - int value() { - return 42; - } - int ciao = 24; -} -void setup() {} -void loop() {} diff --git a/test/sketch_with_old_lib/sketch.ino b/test/sketch_with_old_lib/sketch.ino deleted file mode 100644 index 8be27087..00000000 --- a/test/sketch_with_old_lib/sketch.ino +++ /dev/null @@ -1,9 +0,0 @@ -#include "ShouldNotRecurseWithOldLibs.h" - -void setup() { - -} - -void loop() { - -} \ No newline at end of file diff --git a/test/sketch_with_static_asserts/sketch_with_static_asserts.ino b/test/sketch_with_static_asserts/sketch_with_static_asserts.ino deleted file mode 100644 index 4b5500dd..00000000 --- a/test/sketch_with_static_asserts/sketch_with_static_asserts.ino +++ /dev/null @@ -1,16 +0,0 @@ -// https://github.com/arduino/arduino-builder/issues/68 - -const int a = 10; -const int b = 20; - -static_assert(a < b, "bar"); - -void setup() { - test(); -} - -void loop() { -} - -void test() { -} diff --git a/test/sketch_with_subfolders/sketch_with_subfolders.ino b/test/sketch_with_subfolders/sketch_with_subfolders.ino deleted file mode 100644 index 24a58577..00000000 --- a/test/sketch_with_subfolders/sketch_with_subfolders.ino +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include "subfolder/other.h" -#include "src/subfolder/other.h" - -MyClass myClass; - -void setup() { - myClass.init ( &Serial ); -} - -void loop() { -} diff --git a/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino b/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino deleted file mode 100644 index 1d32675e..00000000 --- a/test/sketch_with_subfolders/src/subfolder/dont_load_me.ino +++ /dev/null @@ -1 +0,0 @@ -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/src/subfolder/other.cpp b/test/sketch_with_subfolders/src/subfolder/other.cpp deleted file mode 100644 index ea74d5a0..00000000 --- a/test/sketch_with_subfolders/src/subfolder/other.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include // Arduino 1.0 -#include - -#include "other.h" - -MyClass::MyClass() { -} - -void MyClass::init ( Stream *stream ) { - controllerStream = stream; -} diff --git a/test/sketch_with_subfolders/src/subfolder/other.h b/test/sketch_with_subfolders/src/subfolder/other.h deleted file mode 100644 index d56bdcdd..00000000 --- a/test/sketch_with_subfolders/src/subfolder/other.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef other__h -#define other__h -#include - -class MyClass { - public: - MyClass(); - void init ( Stream *controllerStream ); - - private: - Stream *controllerStream; -}; -#endif diff --git a/test/sketch_with_subfolders/subfolder/dont_load_me.cpp b/test/sketch_with_subfolders/subfolder/dont_load_me.cpp deleted file mode 100644 index 46b07018..00000000 --- a/test/sketch_with_subfolders/subfolder/dont_load_me.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/subfolder/dont_load_me.ino b/test/sketch_with_subfolders/subfolder/dont_load_me.ino deleted file mode 100644 index 46b07018..00000000 --- a/test/sketch_with_subfolders/subfolder/dont_load_me.ino +++ /dev/null @@ -1,2 +0,0 @@ -#include -#error "Whattya looking at?" diff --git a/test/sketch_with_subfolders/subfolder/other.h b/test/sketch_with_subfolders/subfolder/other.h deleted file mode 100644 index 13a2014b..00000000 --- a/test/sketch_with_subfolders/subfolder/other.h +++ /dev/null @@ -1,2 +0,0 @@ -// This file *is* included from the main sketch, even though it is -// outside of the src/ directory. diff --git a/test/sketch_with_templates_and_shift/template_and_shift.cpp b/test/sketch_with_templates_and_shift/template_and_shift.cpp deleted file mode 100644 index f4f1ece8..00000000 --- a/test/sketch_with_templates_and_shift/template_and_shift.cpp +++ /dev/null @@ -1,19 +0,0 @@ -template<> class FastPin<0> : public _ARMPIN<0, 10, 1 << 10, 0> {};; - -template<> class FastPin<0> : public _ARMPIN<0, 10, 1 < 10, 0> {};; - -template class OtherType> class NestedTemplateClass -{ - OtherType f; -}; - -void printGyro() -{ -} - -template class c {}; -c< 8 > bVar; -c< 1<<8 > aVar; - -template func( c< 1< & aParam) { -} diff --git a/test/sketch_with_typename/sketch.ino b/test/sketch_with_typename/sketch.ino deleted file mode 100644 index 0fdc8167..00000000 --- a/test/sketch_with_typename/sketch.ino +++ /dev/null @@ -1,14 +0,0 @@ -template< typename T > - struct Foo{ - typedef T Bar; -}; - -void setup() { - func(); -} - -void loop() {} - -typename Foo::Bar func(){ - -} diff --git a/test/sketch_with_usbcon/sketch.ino b/test/sketch_with_usbcon/sketch.ino deleted file mode 100644 index 1fa15390..00000000 --- a/test/sketch_with_usbcon/sketch.ino +++ /dev/null @@ -1,18 +0,0 @@ -#if !defined(USBCON) -#error "Where's my USBCON?" -#endif -#if defined(USBCON) -void ciao() { - -} -#endif - -void setup() { - // put your setup code here, to run once: - -} - -void loop() { - // put your main code here, to run repeatedly: - -} \ No newline at end of file diff --git a/test/store_build_options_map_test.go b/test/store_build_options_map_test.go deleted file mode 100644 index da6e2af7..00000000 --- a/test/store_build_options_map_test.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestStoreBuildOptionsMap(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("hardware"), - ToolsDirs: paths.NewPathList("tools"), - BuiltInLibrariesDirs: paths.NewPathList("built-in libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - SketchLocation: paths.New("sketchLocation"), - FQBN: parseFQBN(t, "my:nice:fqbn"), - ArduinoAPIVersion: "ideVersion", - CustomBuildProperties: []string{"custom=prop"}, - Verbose: true, - DebugLevel: 5, - } - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - commands := []types.Command{ - &builder.CreateBuildOptionsMap{}, - &builder.StoreBuildOptionsMap{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - exist, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).ExistCheck() - NoError(t, err) - require.True(t, exist) - - bytes, err := buildPath.Join(constants.BUILD_OPTIONS_FILE).ReadFile() - NoError(t, err) - - require.Equal(t, "{\n"+ - " \"additionalFiles\": \"\",\n"+ - " \"builtInLibrariesFolders\": \"built-in libraries\",\n"+ - " \"customBuildProperties\": \"custom=prop\",\n"+ - " \"fqbn\": \"my:nice:fqbn\",\n"+ - " \"hardwareFolders\": \"hardware\",\n"+ - " \"otherLibrariesFolders\": \"libraries\",\n"+ - " \"runtime.ide.version\": \"ideVersion\",\n"+ - " \"sketchLocation\": \"sketchLocation\",\n"+ - " \"toolsFolders\": \"tools\"\n"+ - "}", string(bytes)) -} diff --git a/test/target_board_resolver_test.go b/test/target_board_resolver_test.go deleted file mode 100644 index d3e2fdea..00000000 --- a/test/target_board_resolver_test.go +++ /dev/null @@ -1,194 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestTargetBoardResolverUno(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:uno"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "uno", targetBoard.BoardID) - require.Equal(t, "atmega328p", targetBoard.Properties.Get("build.mcu")) -} - -func TestTargetBoardResolverDue(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:sam:arduino_due_x"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "sam", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "arduino_due_x", targetBoard.BoardID) - require.Equal(t, "cortex-m3", targetBoard.Properties.Get("build.mcu")) -} - -func TestTargetBoardResolverMega1280(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega1280"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardID) - require.Equal(t, "atmega1280", targetBoard.Properties.Get("build.mcu")) - require.Equal(t, "AVR_MEGA", targetBoard.Properties.Get("build.board")) -} - -func TestTargetBoardResolverMega2560(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware"), - FQBN: parseFQBN(t, "arduino:avr:mega:cpu=atmega2560"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "arduino", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "mega", targetBoard.BoardID) - require.Equal(t, "atmega2560", targetBoard.Properties.Get("build.mcu")) - require.Equal(t, "AVR_MEGA2560", targetBoard.Properties.Get("build.board")) -} - -func TestTargetBoardResolverCustomYun(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "my_avr_platform:avr:custom_yun"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "my_avr_platform", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "custom_yun", targetBoard.BoardID) - require.Equal(t, "atmega32u4", targetBoard.Properties.Get("build.mcu")) - require.Equal(t, "AVR_YUN", targetBoard.Properties.Get("build.board")) -} - -func TestTargetBoardResolverCustomCore(t *testing.T) { - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "user_hardware"), - FQBN: parseFQBN(t, "watterott:avr:attiny841:core=spencekonde,info=info"), - } - - commands := []types.Command{ - &builder.HardwareLoader{}, - &builder.TargetBoardResolver{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - targetPackage := ctx.TargetPackage - require.Equal(t, "watterott", targetPackage.Name) - targetPlatform := ctx.TargetPlatform - require.Equal(t, "avr", targetPlatform.Platform.Architecture) - targetBoard := ctx.TargetBoard - require.Equal(t, "attiny841", targetBoard.BoardID) - require.Equal(t, "tiny841", ctx.BuildCore) - require.Equal(t, "tiny14", targetBoard.Properties.Get("build.variant")) -} diff --git a/test/tools_builtin/avr/builtin_tools_versions.txt b/test/tools_builtin/avr/builtin_tools_versions.txt deleted file mode 100644 index a071f413..00000000 --- a/test/tools_builtin/avr/builtin_tools_versions.txt +++ /dev/null @@ -1,2 +0,0 @@ -arduino.avrdude=6.0.1-arduino5 -arduino.avr-gcc=4.8.1-arduino5 diff --git a/test/tools_loader_test.go b/test/tools_loader_test.go deleted file mode 100644 index 322cdc58..00000000 --- a/test/tools_loader_test.go +++ /dev/null @@ -1,198 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "sort" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -type ByToolIDAndVersion []*cores.ToolRelease - -func (s ByToolIDAndVersion) Len() int { - return len(s) -} -func (s ByToolIDAndVersion) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s ByToolIDAndVersion) Less(i, j int) bool { - if s[i].Tool.Name != s[j].Tool.Name { - return s[i].Tool.Name < s[j].Tool.Name - } - if !s[i].Version.Equal(s[j].Version) { - return s[i].Version.LessThan(s[j].Version) - } - return s[i].InstallDir.String() < s[j].InstallDir.String() -} - -func requireEquivalentPaths(t *testing.T, actual string, expected ...string) { - if len(expected) == 1 { - actualAbs, err := paths.New(actual).Abs() - require.NoError(t, err) - expectedAbs, err := paths.New(expected[0]).Abs() - require.NoError(t, err) - require.Equal(t, expectedAbs.String(), actualAbs.String()) - } else { - actualAbs, err := paths.New(actual).Abs() - require.NoError(t, err) - expectedAbs := paths.NewPathList(expected...) - require.NoError(t, expectedAbs.ToAbs()) - require.Contains(t, expectedAbs.AsStrings(), actualAbs.String()) - } -} - -func TestLoadTools(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - } - - NoError(t, (&builder.HardwareLoader{}).Run(ctx)) - NoError(t, (&builder.ToolsLoader{}).Run(ctx)) - - tools := ctx.AllTools - require.Equal(t, 9, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, ":arduino-preprocessor@0.1.5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arduino-preprocessor/0.1.5") - idx++ - require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - idx++ - require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avr-gcc/4.8.1-arduino5") - idx++ - require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") - idx++ - require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avrdude/6.0.1-arduino5") - idx++ - require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") - idx++ - require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.5-arduino") - idx++ - require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.6.1-arduino") - idx++ - require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/ctags/5.8-arduino11") -} - -func TestLoadToolsWithBoardManagerFolderStructure(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), - } - - NoError(t, (&builder.HardwareLoader{}).Run(ctx)) - NoError(t, (&builder.ToolsLoader{}).Run(ctx)) - - tools := ctx.AllTools - require.Equal(t, 3, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") - idx++ - require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") - idx++ - require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") -} - -func TestLoadLotsOfTools(t *testing.T) { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList("downloaded_board_manager_stuff"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools", "tools_builtin"), - } - - NoError(t, (&builder.HardwareLoader{}).Run(ctx)) - NoError(t, (&builder.ToolsLoader{}).Run(ctx)) - - tools := ctx.AllTools - require.Equal(t, 12, len(tools)) - - sort.Sort(ByToolIDAndVersion(tools)) - - idx := 0 - require.Equal(t, "arduino:CMSIS@4.0.0-atmel", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/CMSIS/4.0.0-atmel") - idx++ - require.Equal(t, ":arduino-preprocessor@0.1.5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arduino-preprocessor/0.1.5") - idx++ - require.Equal(t, "RFduino:arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/RFduino/tools/arm-none-eabi-gcc/4.8.3-2014q1") - idx++ - require.Equal(t, ":arm-none-eabi-gcc@4.8.3-2014q1", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/arm-none-eabi-gcc/4.8.3-2014q1") - idx++ - require.Equal(t, ":avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avr-gcc/4.8.1-arduino5") - idx++ - require.Equal(t, "arduino:avr-gcc@4.8.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") - idx++ - require.Equal(t, ":avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/avrdude/6.0.1-arduino5") - idx++ - require.Equal(t, "arduino:avrdude@6.0.1-arduino5", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "tools_builtin/avr") - idx++ - require.Equal(t, ":bossac@1.5-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.5-arduino") - idx++ - require.Equal(t, ":bossac@1.6.1-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), tools[idx].InstallDir.String(), "downloaded_tools/bossac/1.6.1-arduino") - idx++ - require.Equal(t, ":ctags@5.8-arduino11", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_tools/ctags/5.8-arduino11") - idx++ - require.Equal(t, "arduino:openocd@0.9.0-arduino", tools[idx].String()) - requireEquivalentPaths(t, tools[idx].InstallDir.String(), "downloaded_board_manager_stuff/arduino/tools/openocd/0.9.0-arduino") -} diff --git a/test/try_build_of_problematic_sketch_test.go b/test/try_build_of_problematic_sketch_test.go deleted file mode 100644 index f8ea0156..00000000 --- a/test/try_build_of_problematic_sketch_test.go +++ /dev/null @@ -1,264 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - * Copyright 2015 Matthijs Kooijman - */ - -package test - -import ( - "path/filepath" - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" -) - -func TestTryBuild001(t *testing.T) { - tryBuild(t, "sketch_with_inline_function", "sketch.ino") -} - -func TestTryBuild002(t *testing.T) { - tryBuild(t, "sketch_with_function_signature_inside_ifdef", "sketch.ino") -} - -func TestTryBuild003(t *testing.T) { - tryPreprocess(t, "sketch_no_functions", "main.ino") -} - -func TestTryBuild004(t *testing.T) { - tryBuild(t, "sketch_with_const", "sketch.ino") -} - -func TestTryBuild005(t *testing.T) { - tryBuild(t, "sketch_with_old_lib", "sketch.ino") -} - -func TestTryBuild006(t *testing.T) { - tryBuild(t, "sketch_with_macosx_garbage", "sketch.ino") -} - -func TestTryBuild007(t *testing.T) { - tryBuild(t, "sketch_with_config", "sketch_with_config.ino") -} - -// XXX: Failing sketch, typename not supported -//func TestTryBuild008(t *testing.T) { -// tryBuild(t, "sketch_with_typename", "sketch.ino") -//} - -func TestTryBuild009(t *testing.T) { - tryBuild(t, "sketch_with_usbcon", "sketch.ino") -} - -func TestTryBuild010(t *testing.T) { - tryBuild(t, "sketch_with_namespace", "sketch.ino") -} - -func TestTryBuild011(t *testing.T) { - tryBuild(t, "sketch_with_inline_function", "sketch.ino") -} - -func TestTryBuild012(t *testing.T) { - tryBuild(t, "sketch_with_default_args", "sketch.ino") -} - -func TestTryBuild013(t *testing.T) { - tryBuild(t, "sketch_with_class", "sketch.ino") -} - -func TestTryBuild014(t *testing.T) { - tryBuild(t, "sketch_with_backup_files", "sketch.ino") -} - -func TestTryBuild015(t *testing.T) { - tryBuild(t, "sketch_with_subfolders") -} - -// This is a sketch that fails to build on purpose -//func TestTryBuild016(t *testing.T) { -// tryBuild(t, "sketch_that_checks_if_SPI_has_transactions_and_includes_missing_Ethernet", "sketch.ino") -//} - -func TestTryBuild017(t *testing.T) { - tryPreprocess(t, "sketch_no_functions_two_files", "main.ino") -} - -func TestTryBuild018(t *testing.T) { - tryBuild(t, "sketch_that_checks_if_SPI_has_transactions", "sketch.ino") -} - -func TestTryBuild019(t *testing.T) { - tryBuild(t, "sketch_with_ifdef", "sketch.ino") -} - -func TestTryBuild020(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.OtherLibrariesDirs = paths.NewPathList("dependent_libraries", "libraries") - tryPreprocessWithContext(t, ctx, "sketch_with_dependend_libraries", "sketch.ino") -} - -func TestTryBuild021(t *testing.T) { - tryBuild(t, "sketch_with_function_pointer", "sketch.ino") -} - -func TestTryBuild022(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") - tryBuildWithContext(t, ctx, "sketch_usbhost", "sketch_usbhost.ino") -} - -func TestTryBuild023(t *testing.T) { - tryBuild(t, "sketch1", "sketch.ino") -} - -func TestTryBuild024(t *testing.T) { - tryBuild(t, "sketch2", "SketchWithIfDef.ino") -} - -// The library for this sketch is missing -//func TestTryBuild025(t *testing.T) { -// tryBuild(t, "sketch3", "Baladuino.ino") -//} - -func TestTryBuild026(t *testing.T) { - tryBuild(t, "sketch4", "CharWithEscapedDoubleQuote.ino") -} - -func TestTryBuild027(t *testing.T) { - tryBuild(t, "sketch5", "IncludeBetweenMultilineComment.ino") -} - -func TestTryBuild028(t *testing.T) { - tryBuild(t, "sketch6", "LineContinuations.ino") -} - -func TestTryBuild029(t *testing.T) { - tryBuild(t, "sketch7", "StringWithComment.ino") -} - -func TestTryBuild030(t *testing.T) { - tryBuild(t, "sketch8", "SketchWithStruct.ino") -} - -func TestTryBuild031(t *testing.T) { - tryBuild(t, "sketch9", "sketch.ino") -} - -func TestTryBuild032(t *testing.T) { - tryBuild(t, "sketch10", "sketch.ino") -} - -func TestTryBuild033(t *testing.T) { - tryBuild(t, "sketch_that_includes_arduino_h", "sketch_that_includes_arduino_h.ino") -} - -func TestTryBuild034(t *testing.T) { - tryBuild(t, "sketch_with_static_asserts", "sketch_with_static_asserts.ino") -} - -func TestTryBuild035(t *testing.T) { - tryBuild(t, "sketch_with_enum_class", "sketch_with_enum_class.ino") -} - -func TestTryBuild036(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") - tryBuildWithContext(t, ctx, "sketch11", "sketch_fastleds.ino") -} - -func TestTryBuild037(t *testing.T) { - tryBuild(t, "sketch_with_externC", "sketch_with_externC.ino") -} - -func TestTryBuild038(t *testing.T) { - tryBuild(t, "sketch_with_multiline_prototypes", "sketch_with_multiline_prototypes.ino") -} - -func TestTryBuild039(t *testing.T) { - ctx := makeDefaultContext(t) - ctx.FQBN = parseFQBN(t, "arduino:samd:arduino_zero_native") - tryBuildWithContext(t, ctx, "sketch12", "sketch12.ino") -} - -func TestTryBuild040(t *testing.T) { - tryBuild(t, "sketch_with_externC_multiline", "sketch_with_externC_multiline.ino") -} - -func TestTryBuild041(t *testing.T) { - tryBuild(t, "sketch_with_multiline_template", "sketch_with_multiline_template.ino") -} - -func TestTryBuild042(t *testing.T) { - tryBuild(t, "sketch_with_fake_function_pointer", "sketch_with_fake_function_pointer.ino") -} - -func makeDefaultContext(t *testing.T) *types.Context { - DownloadCoresAndToolsAndLibraries(t) - - ctx := &types.Context{ - HardwareDirs: paths.NewPathList(filepath.Join("..", "hardware"), "hardware", "downloaded_hardware", "downloaded_board_manager_stuff"), - BuiltInToolsDirs: paths.NewPathList("downloaded_tools"), - BuiltInLibrariesDirs: paths.NewPathList("downloaded_libraries"), - OtherLibrariesDirs: paths.NewPathList("libraries"), - FQBN: parseFQBN(t, "arduino:avr:leonardo"), - ArduinoAPIVersion: "10607", - Verbose: true, - DebugPreprocessor: true, - } - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - return ctx -} - -func tryBuild(t *testing.T, sketchPath ...string) { - ctx := makeDefaultContext(t) - tryBuildWithContext(t, ctx, sketchPath...) -} - -func tryBuildWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := paths.New(sketchPath...) - ctx.SketchLocation = sketchLocation - - err := builder.RunBuilder(ctx) - NoError(t, err, "Build error for "+sketchLocation.String()) -} - -func tryPreprocess(t *testing.T, sketchPath ...string) { - ctx := makeDefaultContext(t) - tryPreprocessWithContext(t, ctx, sketchPath...) -} - -func tryPreprocessWithContext(t *testing.T, ctx *types.Context, sketchPath ...string) { - sketchLocation := paths.New(sketchPath...) - ctx.SketchLocation = sketchLocation - - err := builder.RunPreprocess(ctx) - NoError(t, err, "Build error for "+sketchLocation.String()) -} diff --git a/test/unique_string_queue_test.go b/test/unique_string_queue_test.go deleted file mode 100644 index e6e92bb4..00000000 --- a/test/unique_string_queue_test.go +++ /dev/null @@ -1,48 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" - "testing" -) - -func TestUniqueStringQueue(t *testing.T) { - queue := types.UniqueStringQueue{} - queue.Push("hello") - queue.Push("world") - queue.Push("hello") - queue.Push("world") - - require.Equal(t, "hello", queue.Pop()) - require.Equal(t, "world", queue.Pop()) - require.True(t, queue.Empty()) -} diff --git a/test/unquote_test.go b/test/unquote_test.go deleted file mode 100644 index 88233424..00000000 --- a/test/unquote_test.go +++ /dev/null @@ -1,54 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/gohasissues" - "github.com/stretchr/testify/require" - "testing" -) - -func TestStrConvUnquote(t *testing.T) { - s, err := gohasissues.Unquote("ciao") - NoError(t, err) - require.Equal(t, "ciao", s) - - s, err = gohasissues.Unquote("arduino:avr:uno") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) - - s, err = gohasissues.Unquote("\"arduino:avr:uno\"") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) - - s, err = gohasissues.Unquote("'arduino:avr:uno'") - NoError(t, err) - require.Equal(t, "arduino:avr:uno", s) -} diff --git a/test/unused_compiled_libraries_remover_test.go b/test/unused_compiled_libraries_remover_test.go deleted file mode 100644 index 08cfbc05..00000000 --- a/test/unused_compiled_libraries_remover_test.go +++ /dev/null @@ -1,106 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/libraries" - paths "github.com/arduino/go-paths-helper" - "github.com/stretchr/testify/require" -) - -func TestUnusedCompiledLibrariesRemover(t *testing.T) { - temp, err := paths.MkTempDir("", "test") - NoError(t, err) - defer temp.RemoveAll() - - NoError(t, temp.Join("SPI").MkdirAll()) - NoError(t, temp.Join("Bridge").MkdirAll()) - NoError(t, temp.Join("dummy_file").WriteFile([]byte{})) - - ctx := &types.Context{} - ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*libraries.Library{&libraries.Library{Name: "Bridge"}} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err = cmd.Run(ctx) - NoError(t, err) - - exist, err := temp.Join("SPI").ExistCheck() - require.NoError(t, err) - require.False(t, exist) - exist, err = temp.Join("Bridge").ExistCheck() - NoError(t, err) - require.True(t, exist) - exist, err = temp.Join("dummy_file").ExistCheck() - NoError(t, err) - require.True(t, exist) -} - -func TestUnusedCompiledLibrariesRemoverLibDoesNotExist(t *testing.T) { - ctx := &types.Context{} - ctx.LibrariesBuildPath = paths.TempDir().Join("test") - ctx.ImportedLibraries = []*libraries.Library{&libraries.Library{Name: "Bridge"}} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err := cmd.Run(ctx) - NoError(t, err) -} - -func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) { - temp, err := paths.MkTempDir("", "test") - NoError(t, err) - defer temp.RemoveAll() - - NoError(t, temp.Join("SPI").MkdirAll()) - NoError(t, temp.Join("Bridge").MkdirAll()) - NoError(t, temp.Join("dummy_file").WriteFile([]byte{})) - - ctx := &types.Context{} - ctx.LibrariesBuildPath = temp - ctx.ImportedLibraries = []*libraries.Library{} - - cmd := builder.UnusedCompiledLibrariesRemover{} - err = cmd.Run(ctx) - NoError(t, err) - - exist, err := temp.Join("SPI").ExistCheck() - require.NoError(t, err) - require.False(t, exist) - exist, err = temp.Join("Bridge").ExistCheck() - require.NoError(t, err) - require.False(t, exist) - exist, err = temp.Join("dummy_file").ExistCheck() - NoError(t, err) - require.True(t, exist) -} diff --git a/test/user_hardware/arduino/avr/.gitkeep b/test/user_hardware/arduino/avr/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/test/user_hardware/my_avr_platform/avr/boards.txt b/test/user_hardware/my_avr_platform/avr/boards.txt deleted file mode 100644 index 35bd3548..00000000 --- a/test/user_hardware/my_avr_platform/avr/boards.txt +++ /dev/null @@ -1,85 +0,0 @@ -custom_yun.name=Arduino Yún -custom_yun.upload.via_ssh=true - -custom_yun.build.core=arduino:arduino -custom_yun.bootloader.tool=arduino:avrdude -custom_yun.upload.tool=arduino:avrdude - -custom_yun.vid.0=0x2341 -custom_yun.pid.0=0x0041 -custom_yun.vid.1=0x2341 -custom_yun.pid.1=0x8041 -custom_yun.upload.protocol=avr109 -custom_yun.upload.maximum_size=28672 -custom_yun.upload.maximum_data_size=2560 -custom_yun.upload.speed=57600 -custom_yun.upload.disable_flushing=true -custom_yun.upload.use_1200bps_touch=true -custom_yun.upload.wait_for_upload_port=true - -custom_yun.bootloader.low_fuses=0xff -custom_yun.bootloader.high_fuses=0xd8 -custom_yun.bootloader.extended_fuses=0xfb -custom_yun.bootloader.file=caterina/Caterina-custom_yun.hex -custom_yun.bootloader.unlock_bits=0x3F -custom_yun.bootloader.lock_bits=0x2F - -custom_yun.build.mcu=atmega32u4 -custom_yun.build.f_cpu=16000000L -custom_yun.build.vid=0x2341 -custom_yun.build.pid=0x8041 -custom_yun.build.usb_product="Arduino My" -custom_yun.build.board=AVR_YUN -custom_yun.build.variant=arduino:yun -custom_yun.build.extra_flags={build.usb_flags} - -mymega.name=Arduino Mega or Mega 2560 - -mymega.vid.0=0x2341 -mymega.pid.0=0x0010 -mymega.vid.1=0x2341 -mymega.pid.1=0x0042 -mymega.vid.2=0x2A03 -mymega.pid.2=0x0010 -mymega.vid.3=0x2A03 -mymega.pid.3=0x0042 - -mymega.upload.tool=avrdude -mymega.upload.maximum_data_size=8192 - -mymega.bootloader.tool=avrdude -mymega.bootloader.low_fuses=0xFF -mymega.bootloader.unlock_bits=0x3F -mymega.bootloader.lock_bits=0x0F - -mymega.build.f_cpu=16000000L -mymega.build.core=arduino -mymega.build.variant=mega - -mymega.menu.cpu.atmega2560=ATmega2560 (Mega 2560) - -mymega.menu.cpu.atmega2560.upload.protocol=wiring -mymega.menu.cpu.atmega2560.upload.maximum_size=253952 -mymega.menu.cpu.atmega2560.upload.speed=115200 - -mymega.menu.cpu.atmega2560.bootloader._folder=stk500v2 -mymega.menu.cpu.atmega2560.bootloader.high_fuses=0xD8 -mymega.menu.cpu.atmega2560.bootloader.extended_fuses=0xFD -mymega.menu.cpu.atmega2560.bootloader.file={bootloader._folder}/stk500boot_v2_mega2560.hex - -mymega.menu.cpu.atmega2560.build.mcu=atmega2560 -mymega.menu.cpu.atmega2560.build.board=AVR_MYMEGA2560 - -mymega.menu.cpu.atmega1280=ATmega1280 - -mymega.menu.cpu.atmega1280.upload.protocol=arduino -mymega.menu.cpu.atmega1280.upload.maximum_size=126976 -mymega.menu.cpu.atmega1280.upload.speed=57600 - -mymega.menu.cpu.atmega1280.bootloader._folder=atmega -mymega.menu.cpu.atmega1280.bootloader.high_fuses=0xDA -mymega.menu.cpu.atmega1280.bootloader.extended_fuses=0xF5 -mymega.menu.cpu.atmega1280.bootloader.file={bootloader._folder}/ATmegaBOOT_168_atmega1280.hex - -mymega.menu.cpu.atmega1280.build.mcu=atmega1280 -mymega.menu.cpu.atmega1280.build.board=AVR_MYMEGA diff --git a/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex b/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex deleted file mode 100644 index c52e690a..00000000 --- a/test/user_hardware/my_avr_platform/avr/bootloaders/stk500v2/stk500boot_v2_mega2560.hex +++ /dev/null @@ -1,469 +0,0 @@ -:020000023000CC -:10E000000D9489F10D94B2F10D94B2F10D94B2F129 -:10E010000D94B2F10D94B2F10D94B2F10D94B2F1F0 -:10E020000D94B2F10D94B2F10D94B2F10D94B2F1E0 -:10E030000D94B2F10D94B2F10D94B2F10D94B2F1D0 -:10E040000D94B2F10D94B2F10D94B2F10D94B2F1C0 -:10E050000D94B2F10D94B2F10D94B2F10D94B2F1B0 -:10E060000D94B2F10D94B2F10D94B2F10D94B2F1A0 -:10E070000D94B2F10D94B2F10D94B2F10D94B2F190 -:10E080000D94B2F10D94B2F10D94B2F10D94B2F180 -:10E090000D94B2F10D94B2F10D94B2F10D94B2F170 -:10E0A0000D94B2F10D94B2F10D94B2F10D94B2F160 -:10E0B0000D94B2F10D94B2F10D94B2F10D94B2F150 -:10E0C0000D94B2F10D94B2F10D94B2F10D94B2F140 -:10E0D0000D94B2F10D94B2F10D94B2F10D94B2F130 -:10E0E0000D94B2F141546D656761323536300041AF -:10E0F000726475696E6F206578706C6F72657220DE -:10E1000073746B3530305632206279204D4C530099 -:10E11000426F6F746C6F616465723E004875683F52 -:10E1200000436F6D70696C6564206F6E203D200048 -:10E130004350552054797065202020203D20005FF9 -:10E140005F4156525F415243485F5F3D2000415658 -:10E1500052204C696243205665723D20004743437C -:10E160002056657273696F6E203D20004350552024 -:10E1700049442020202020203D20004C6F7720663D -:10E18000757365202020203D20004869676820665F -:10E190007573652020203D200045787420667573D6 -:10E1A00065202020203D20004C6F636B2066757336 -:10E1B000652020203D20004D617220203720323024 -:10E1C000313300312E362E3800342E332E350056A2 -:10E1D00023202020414444522020206F7020636F70 -:10E1E00064652020202020696E73747275637469E1 -:10E1F0006F6E2061646472202020496E74657272B3 -:10E20000757074006E6F20766563746F7200726A49 -:10E210006D702020006A6D70200057686174207056 -:10E220006F72743A00506F7274206E6F7420737541 -:10E2300070706F72746564004D7573742062652030 -:10E2400061206C6574746572002000577269747483 -:10E25000696E672045450052656164696E672045B7 -:10E26000450045452065727220636E743D00504F35 -:10E27000525400303D5A65726F2061646472003FF1 -:10E280003D43505520737461747300403D454550C3 -:10E29000524F4D207465737400423D426C696E6B41 -:10E2A000204C454400453D44756D70204545505215 -:10E2B0004F4D00463D44756D7020464C415348001B -:10E2C000483D48656C70004C3D4C69737420492F83 -:10E2D0004F20506F72747300513D51756974005234 -:10E2E0003D44756D702052414D00563D73686F7707 -:10E2F00020696E7465727275707420566563746FF0 -:10E30000727300593D506F727420626C696E6B00BD -:10E310002A0011241FBECFEFD1E2DEBFCDBF01E046 -:10E320000CBF12E0A0E0B2E0EEE1FDEF03E00BBFB6 -:10E3300002C007900D92A030B107D9F712E0A0E01B -:10E34000B2E001C01D92AE30B107E1F70F9460F367 -:10E350000D948DFE01E20EBF0FEF0DBF11241FBE05 -:10E360000D9460F30D9400F020E030E040ED57E0B4 -:10E3700005C0FA013197F1F72F5F3F4F2817390792 -:10E38000C0F308959C01260F311DC901A0E0B0E043 -:10E390002F5F3F4FABBFFC018791882361F08093D3 -:10E3A000C6008091C00086FFFCCF8091C0008064D1 -:10E3B0008093C000EACF08958DE08093C6008091DD -:10E3C000C00086FFFCCF8091C00080648093C000B5 -:10E3D0008AE08093C6008091C00086FFFCCF8091C8 -:10E3E000C00080648093C00008950F94C2F10F9420 -:10E3F000DCF10895FC019081992359F09093C600B7 -:10E400008091C00086FFFCCF8091C0008064809323 -:10E41000C0003196992379F70895282F982F929567 -:10E420009F70892F805D8A3308F0895F8093C600D2 -:10E430008091C00086FFFCCF8091C00080648093F3 -:10E44000C000822F8F70982F905D9A3308F0995FEB -:10E450009093C6008091C00086FFFCCF8091C000E1 -:10E4600080648093C00008959C01FB01853691056E -:10E470001CF46330710594F0C90164E670E00F94F8 -:10E480002EFE605D7F4F6093C6008091C00086FFC6 -:10E49000FCCF8091C00080648093C0002B30310598 -:10E4A00014F43297B4F0C90164E670E00F942EFEC4 -:10E4B0006AE070E00F942EFE605D7F4F6093C600AF -:10E4C0008091C00086FFFCCF8091C0008064809363 -:10E4D000C000C9016AE070E00F942EFEC0968093E0 -:10E4E000C6008091C00086FFFCCF8091C000806490 -:10E4F0008093C00008951F93182F8EE692EE60E07F -:10E500000F94C2F11093C6008091C00086FFFCCF2B -:10E510008091C00080648093C0000F94DCF11F9153 -:10E5200008952F923F924F925F926F927F928F92B7 -:10E530009F92AF92BF92CF92DF92EF92FF920F9392 -:10E540001F93DF93CF93CDB7DEB762970FB6F894E2 -:10E55000DEBF0FBECDBF382E622ECA01DB015C01CB -:10E560006D01772420E2222E2E010894411C511CBB -:10E570008BC081E0A81680E0B80681E0C80680E084 -:10E58000D80628F0C601AA27BB270F940DF2BB2797 -:10E59000AD2D9C2D8B2D0F940DF28A2D0F940DF225 -:10E5A0002092C6008091C00086FFFCCF8091C00001 -:10E5B00080648093C0009DE29093C6008091C0006B -:10E5C00086FFFCCF8091C00080648093C0002092C1 -:10E5D000C6008091C00086FFFCCF8091C00080649F -:10E5E0008093C00019828601750188249924A1E0D6 -:10E5F0003A1651F03A1620F0B2E03B1661F409C029 -:10E600000BBFF701779007C0C7010F9477FE782EF4 -:10E6100002C0F7017080872D0F940DF22092C60082 -:10E620008091C00086FFFCCF8091C0008064809301 -:10E63000C000872D8052F401EF70F0708F3520F408 -:10E64000E40DF51D708204C0E40DF51D8EE280839B -:10E650000894E11CF11C011D111D0894811C911CE2 -:10E6600090E18916910409F0C2CF80E190E0A0E02A -:10E67000B0E0A80EB91ECA1EDB1E198AC2010F9493 -:10E68000FAF10F94DCF16A94662009F072CF629679 -:10E690000FB6F894DEBF0FBECDBFCF91DF911F91B3 -:10E6A0000F91FF90EF90DF90CF90BF90AF909F9031 -:10E6B0008F907F906F905F904F903F902F90089534 -:10E6C0002F923F924F925F926F927F928F929F9282 -:10E6D000AF92BF92CF92DF92EF92FF920F931F9370 -:10E6E000DF93CF93CDB7DEB7CD53D1400FB6F894BB -:10E6F000DEBF0FBECDBF01E20EBF0FEF0DBF94B75F -:10E70000F894A89514BE80916000886180936000A1 -:10E7100010926000789493FF05C0E0910002F091A0 -:10E7200001021995279A2F9A8091C00082608093E8 -:10E73000C00080E18093C40088E18093C1000000A4 -:10E74000EE24FF24870144E0A42EB12CCC24DD2448 -:10E7500024C0C5010197F1F70894E11CF11C011DCB -:10E76000111D21E2E2162EE4F20620E0020720E06D -:10E77000120718F031E0C32ED12CC801B70127ECE5 -:10E780003BE140E050E00F9441FE611571058105C9 -:10E79000910519F485B1805885B98091C00087FD35 -:10E7A00003C0C114D104A9F2A6014F5F5F4FC25E3E -:10E7B000DE4F59834883CE51D140C25EDE4F8881FF -:10E7C0009981CE51D140019711F00D9410FEC05D9A -:10E7D000DE4F19821882C053D14060E0C15DDE4F28 -:10E7E0001882CF52D14088249924C35DDE4F19820C -:10E7F0001882CD52D140C05EDE4F188219821A8233 -:10E800001B82C052D140CE5CDE4F188219821A8220 -:10E810001B82C253D140EE24FF2487010BBFF701B6 -:10E8200007911691C45CDE4F19830883CC53D14005 -:10E830000D940BFEC25EDE4F28813981CE51D1404E -:10E840002130310509F52091C600C25EDE4F1982E4 -:10E850001882CE51D14022C02F5F3F4F4F4F5F4FA4 -:10E86000213082E138078AE7480780E0580780F0C6 -:10E87000C45CDE4FE881F981CC53D140EF5FFF4F9C -:10E8800019F0EE27FF27099420E030E040E050E047 -:10E890008091C00087FFE0CF2091C600C35DDE4FAE -:10E8A00048815981CD52D1404F5F5F4FC35DDE4FEC -:10E8B00059834883CD52D140213209F063C64A3092 -:10E8C000510508F05FC60894811C911C53E0851621 -:10E8D000910409F059C600E010E018C081E280936D -:10E8E000C6008091C00086FFFCCF8091C00080648C -:10E8F0008093C0002F5F3F4F2931310579F70F9486 -:10E90000DCF10F5F1F4F0530110519F020E030E0FA -:10E91000E5CF10920A0210920B0210920C02109294 -:10E920000D02109206021092070210920802109235 -:10E930000902109202021092030210920402109235 -:10E9400005028FEE90EE60E00F94F5F180E191EE1C -:10E9500060E00F94C2F18091C00087FFFCCF9091DE -:10E96000C600903608F09F759032B8F09093C600BC -:10E970008091C00086FFFCCF8091C00080648093AE -:10E98000C000A0E2A093C6008091C00086FFFCCF2B -:10E990008091C00080648093C000983409F4D7C18E -:10E9A0009934B8F4923409F459C1933458F490333B -:10E9B00019F1903308F4E3C59F33A1F1903409F0C5 -:10E9C000DEC5BDC0953409F470C1963409F0D7C5D1 -:10E9D00098C1923509F42BC2933538F49C3409F46C -:10E9E000F5C1913509F0CBC518C2963509F445C279 -:10E9F000993509F0C4C567C483E792EE62E00F94CD -:10EA0000F5F110920602109207021092080210927D -:10EA1000090210920A0210920B0210920C0210923C -:10EA20000D0213C18FE792EE62E00F94F5F18FEEC5 -:10EA300090EE60E00F94F5F181E291EE60E00F94CA -:10EA4000C2F187EB91EE60E00F94F5F180E391EE77 -:10EA500060E00F94C2F184EE90EE60E00F94F5F167 -:10EA60008FE391EE60E00F94C2F186E090E061E008 -:10EA700070E00F9434F20F94DCF18DE591EE60E0DC -:10EA80000F94C2F189EC91EE60E00F94F5F18EE401 -:10EA900091EE60E00F94C2F183EC91EE60E00F9490 -:10EAA000F5F18CE691EE60E00F94C2F18EE10F94E7 -:10EAB0000DF288E90F940DF281E00F940DF20F949E -:10EAC000DCF18BE791EE60E00F94C2F119E0E0E039 -:10EAD000F0E010935700E4918E2F0F940DF20F94F5 -:10EAE000DCF18AE891EE60E00F94C2F1E3E0F0E03F -:10EAF00010935700E4918E2F0F940DF20F94DCF1D8 -:10EB000089E991EE60E00F94C2F1E2E0F0E0109349 -:10EB10005700E4918E2F0F940DF20F94DCF188EAE8 -:10EB200091EE60E00F94C2F1E1E0F0E01093570045 -:10EB30001491812F0F940DF20F94DCF107CF8BE825 -:10EB400092EE62E00F94F5F18BE492EE60E00F94A8 -:10EB5000F5F10F94DCF100E010E019C0C8016F2D51 -:10EB60000F947FFEFF2031F489E492EE60E00F9471 -:10EB7000C2F10BC0F092C6008091C00086FFFCCFAE -:10EB80008091C00080648093C0000F5F1F4FC80158 -:10EB900081519F41A0E0B0E0ABBFFC01F790BAE229 -:10EBA000FB1621F0E2E000301E07C1F60F94DCF105 -:10EBB0000F94DCF187E592EE60E00F94F5F10F948D -:10EBC000DCF1CC24DD2400E010E01EC0C8010F946D -:10EBD00077FEF82E882331F489E492EE60E00F94FA -:10EBE000C2F10BC08093C6008091C00086FFFCCFAD -:10EBF0008091C00080648093C000FE1419F00894D6 -:10EC0000C11CD11C0F5F1F4FC80181519F41A0E063 -:10EC1000B0E0ABBFFC01E790FAE2EF1621F022E092 -:10EC20000030120799F60F94DCF10F94DCF182E6C4 -:10EC300092EE60E00F94C2F1C60161E070E00F94C3 -:10EC400034F20F94DCF10F94DCF110920202109276 -:10EC50000302109204021092050278CE89E992EE26 -:10EC600062E00F94F5F1279A2F9A16C02F9880E052 -:10EC700090E0E0EDF7E03197F1F7019684369105E9 -:10EC8000C1F72F9A80E090E0E0EDF7E03197F1F7DF -:10EC9000019684369105C1F78091C00087FFE6CFC9 -:10ECA0008091C00087FFFCCF64C485EA92EE62E0E9 -:10ECB0000F94F5F140910202509103026091040219 -:10ECC0007091050281E020E10F9491F2809102029F -:10ECD00090910302A0910402B091050280509F4FD1 -:10ECE000AF4FBF4F8093020290930302A0930402A0 -:10ECF000B093050280509041A040B04008F426CE69 -:10ED0000A4CF83EB92EE62E00F94F5F140910602FE -:10ED100050910702609108027091090280E020E1A1 -:10ED20000F9491F28091060290910702A09108023F -:10ED3000B091090280509F4FAF4FBF4F80930602A2 -:10ED400090930702A0930802B0930902FFCD80ECD4 -:10ED500092EE62E00F94F5F183E792EE60E00F949B -:10ED6000F5F18FE792EE60E00F94F5F18BE892EE0B -:10ED700060E00F94F5F189E992EE60E00F94F5F10F -:10ED800085EA92EE60E00F94F5F183EB92EE60E09D -:10ED90000F94F5F180EC92EE60E00F94F5F187ECC2 -:10EDA00092EE60E00F94F5F188ED92EE60E00F9442 -:10EDB000F5F18FED92EE60E00F94F5F18AEE92EEB0 -:10EDC00060E00F94F5F183E093EEBDCD87EC92EE19 -:10EDD00062E00F94F5F181E40F947BF282E40F94EA -:10EDE0007BF283E40F947BF284E40F947BF285E45E -:10EDF0000F947BF286E40F947BF287E40F947BF20E -:10EE000088E40F947BF28AE40F947BF28BE40F94F6 -:10EE10007BF28CE40F947BF299CD88ED92EE62E068 -:10EE20000F94F5F1772473948824992409C48FED05 -:10EE300092EE62E00F94F5F140910A0250910B02BC -:10EE400060910C0270910D0282E020E10F9491F22A -:10EE500080910A0290910B02A0910C02B0910D02D8 -:10EE600080509F4FAF4FBF4F80930A0290930B0289 -:10EE7000A0930C02B0930D0269CD8AEE92EE62E08F -:10EE80000F94F5F184EE90EE60E00F94F5F18FECC5 -:10EE900091EE60E00F94F5F1662477244301CC5D98 -:10EEA000DE4F19821882C452D140D401C301B695F5 -:10EEB000A79597958795CA5DDE4F88839983AA8326 -:10EEC000BB83C652D140CC5DDE4FA881B981C4520C -:10EED000D1401196CC5DDE4FB983A883C452D14096 -:10EEE000CD0162E070E00F9434F2B0E2B093C6005E -:10EEF0008091C00086FFFCCF8091C0008064809329 -:10EF0000C000EDE2E093C6008091C00086FFFCCF18 -:10EF10008091C00080648093C000F0E2F093C6004E -:10EF20008091C00086FFFCCF8091C00080648093F8 -:10EF3000C000CA5DDE4FE880F9800A811B81C6529D -:10EF4000D140BB27A12F902F8F2D0F940DF2CA5DBA -:10EF5000DE4F8881C652D1400F940DF2B0E2FB2EF5 -:10EF6000F092C6008091C00086FFFCCF8091C00067 -:10EF700080648093C0000DE30093C6008091C000C0 -:10EF800086FFFCCF8091C00080648093C00010E2B7 -:10EF90001093C6008091C00086FFFCCF8091C00016 -:10EFA00080648093C0008BBEF3012791C65DDE4F65 -:10EFB0002883CA52D140A22EBB24CC24DD2408943D -:10EFC000611C711C811C911C8BBEF3018791282E42 -:10EFD0003324442455240894611C711C811C911C09 -:10EFE0008BBEF3013791C55DDE4F3883CB52D140E4 -:10EFF0000894611C711C811C911C8BBEF30147910C -:10F00000C45DDE4F4883CC52D140ADEFEA2EAFEF66 -:10F01000FA2EAFEF0A2FAFEF1A2F6E0C7F1C801E57 -:10F02000911E142D032DF22CEE24EA0CFB1C0C1D5A -:10F030001D1D0F940DF220E22093C6008091C000A8 -:10F0400086FFFCCF8091C00080648093C000C65DC5 -:10F05000DE4F8881CA52D1400F940DF230E23093D6 -:10F06000C6008091C00086FFFCCF8091C000806404 -:10F070008093C000C45DDE4F8881CC52D1400F9494 -:10F080000DF240E24093C6008091C00086FFFCCFA5 -:10F090008091C00080648093C000C55DDE4F888190 -:10F0A000CB52D1400F940DF250E25093C6008091A4 -:10F0B000C00086FFFCCF8091C00080648093C000B8 -:10F0C0008FEFE8168FEFF80680E0080780E018075A -:10F0D00031F484E092EE60E00F94C2F1DFC0D80119 -:10F0E000C7018070907CA070B0708050904CA040A0 -:10F0F000B040D1F52FEF3FE340E050E0E222F322B1 -:10F1000004231523CA5DDE4FA880B980CA80DB8046 -:10F11000C652D140AE0CBF1CC01ED11EAA0CBB1CD7 -:10F12000CC1CDD1C8EE092EE60E00F94C2F1BB2798 -:10F13000A12F902F8F2D0F940DF28E2D0F940DF285 -:10F1400030E23093C6008091C00086FFFCCF8091F2 -:10F15000C00080648093C0004EE34093C60080915D -:10F16000C00086FFFCCF87C08EE09EEFA0E0B0E03D -:10F17000E822F9220A231B239CE0E91694E9F90608 -:10F1800090E0090790E0190709F088C0C45DDE4FE0 -:10F19000A881CC52D140EA2EFF2400E010E0102FCD -:10F1A0000F2DFE2CEE24C55DDE4FB881CB52D14031 -:10F1B000EB0EF11C011D111DD601C501817090706F -:10F1C000A070B070DC0199278827E80EF91E0A1F8D -:10F1D0001B1F20EF30E040E050E0A222B322C42207 -:10F1E000D52241E1AA0CBB1CCC1CDD1C4A95D1F7F1 -:10F1F000EA0CFB1C0C1D1D1D81E090E0A0E0B0E0BE -:10F20000282239224A225B2235E1220C331C441C7D -:10F21000551C3A95D1F7E20CF31C041D151D57013E -:10F220006801AA0CBB1CCC1CDD1C85E192EE60E0E1 -:10F230000F94C2F1C801AA27BB270F940DF2BB2778 -:10F24000A12F902F8F2D0F940DF28E2D0F940DF274 -:10F2500090E29093C6008091C00086FFFCCF809121 -:10F26000C00080648093C000AEE3A093C60080918C -:10F27000C00086FFFCCF8091C00080648093C000F6 -:10F28000C601AA27BB270F940DF2BB27AD2D9C2DDD -:10F290008B2D0F940DF28A2D0F940DF20F94DCF14B -:10F2A000CC5DDE4FE881F981C452D140F99709F471 -:10F2B0004DCBF4E0EF2EF12C012D112D6E0C7F1CA7 -:10F2C000801E911EF2CD83E093EE62E00F94F5F183 -:10F2D0008AE192EE60E00F94C2F18091C00087FF56 -:10F2E000FCCF1091C6001F751093C6008091C0001E -:10F2F00086FFFCCF8091C00080648093C0000F9493 -:10F30000DCF1812F81548A3108F036C1163409F4BA -:10F3100095C0173490F4133409F44EC0143430F40B -:10F320001134F1F0123409F01DC130C0143409F465 -:10F3300059C0153409F016C16BC01A3409F4C4C0A1 -:10F340001B3438F4173409F48FC0183409F00AC19B -:10F35000A1C01B3409F4D2C01C3409F003C1E8C0B9 -:10F360008FEF81B90DC082B1809582B980E090E0C5 -:10F37000E0EDF7E03197F1F70196883C9105C1F790 -:10F380008091C00087FFEFCF12B8EFC08FEF84B934 -:10F390000DC085B1809585B980E090E0E0EDF7E0A3 -:10F3A0003197F1F70196883C9105C1F78091C00033 -:10F3B00087FFEFCF15B8D9C08FEF87B90DC088B1DF -:10F3C000809588B980E090E0E0EDF7E03197F1F7C3 -:10F3D0000196883C9105C1F78091C00087FFEFCF6F -:10F3E00018B8C3C08FEF8AB90DC08BB180958BB9A7 -:10F3F00080E090E0E0EDF7E03197F1F70196883C8E -:10F400009105C1F78091C00087FFEFCF1BB8ADC059 -:10F410008FEF8DB90DC08EB180958EB980E090E0F0 -:10F42000E0EDF7E03197F1F70196883C9105C1F7DF -:10F430008091C00087FFEFCF1EB897C08FEF80BBD1 -:10F440000DC081B3809581BB80E090E0E0EDF7E0F6 -:10F450003197F1F70196883C9105C1F78091C00082 -:10F4600087FFEFCF11BA81C08FEF83BB0DC084B38C -:10F47000809584BB80E090E0E0EDF7E03197F1F714 -:10F480000196883C9105C1F78091C00087FFEFCFBE -:10F4900014BA6BC08FEF809301010FC080910201FD -:10F4A00080958093020180E090E0E0EDF7E03197F5 -:10F4B000F1F70196883C9105C1F78091C00087FF64 -:10F4C000EDCF1092020151C08FEF809304010FC065 -:10F4D0008091050180958093050180E090E0E0ED4A -:10F4E000F7E03197F1F70196883C9105C1F78091DB -:10F4F000C00087FFEDCF1092050137C08FEF8093DA -:10F5000007010FC08091080180958093080180E079 -:10F5100090E0E0EDF7E03197F1F70196883C910536 -:10F52000C1F78091C00087FFEDCF109208011DC088 -:10F530008FEF80930A010FC080910B01809580931B -:10F540000B0180E090E0E0EDF7E03197F1F70196F4 -:10F55000883C9105C1F78091C00087FFEDCF1092E4 -:10F560000B0103C085E292EEEEC98091C00087FFD7 -:10F57000FCCF8091C600EAC988E392EEE4C98CE131 -:10F5800091EEE1C988249924933011F1943028F444 -:10F59000913089F09230B8F408C0953061F195301F -:10F5A000F0F0963009F048C043C02B3109F042C951 -:10F5B00091E06BE13FC96227C15DDE4F2883CF52E6 -:10F5C000D14092E037C9B22FA0E0622793E032C960 -:10F5D000822F90E0A82BB92B622794E02BC92E3004 -:10F5E00009F039C3622795E0C05DDE4F19821882A9 -:10F5F000C053D1401FC9E1E0F0E0EC0FFD1FC05D3A -:10F60000DE4F08811981C053D140E00FF11F2083E4 -:10F610000F5F1F4FC05DDE4F19830883C053D14079 -:10F6200062270A171B0709F005C9D80196E002C92D -:10F63000261709F010C303C0973009F0FBC87724E0 -:10F640009981933109F412C19431C8F4963009F4C8 -:10F65000D8C0973050F4923009F406C1933009F4C1 -:10F660006DC0913009F059C253C0913109F477C08F -:10F67000923108F0BBC0903109F04FC2F5C098310B -:10F6800009F487C0993150F4953109F4EFC09531F0 -:10F6900008F4C6C1963109F040C2C2C19A3109F4DA -:10F6A0006CC09A3108F491C09B3109F45BC09D3164 -:10F6B00009F033C29D81903359F48F81882311F46E -:10F6C0009EE11CC0813011F091E018C098E916C08D -:10F6D000892F807591F0903539F4E0E0F0E089E011 -:10F6E0008093570094910AC0983539F4E3E0F0E034 -:10F6F00089E080935700949101C090E01A821B82A8 -:10F700008D818C831D829E831F8227E030E009C299 -:10F710001A8288E08B8381E48C8386E58D8382E581 -:10F720008E8389E48F8383E5888780E589878FE5E9 -:10F730008A8782E38B872BE030E0F3C18A818139AD -:10F7400041F0823941F0803911F48FE005C080E04A -:10F7500003C082E001C08AE01A828B8344C0772410 -:10F76000739482C08D81882311F48EE12CC0813086 -:10F7700011F081E028C088E926C01A82E1E0F0E0BB -:10F7800089E08093570084918B831C8224E030E0D1 -:10F79000C8C18B81803589F48C81883039F4E2E0EE -:10F7A000F0E089E08093570084910DC0E0E0F0E044 -:10F7B00089E080935700849106C0E3E0F0E089E09F -:10F7C0008093570084911A82DFCF8D81836C99E0FA -:10F7D000E1E0F0E0082E90935700E89507B600FCB2 -:10F7E000FDCF1A821B8223E030E09BC180EC8A832C -:10F7F000CE5CDE4F188219821A821B82C253D1401E -:10F800008EC18A8190E0A0E0B0E0582F44273327D2 -:10F8100022278B8190E0A0E0B0E0DC0199278827C7 -:10F82000282B392B4A2B5B2B8D8190E0A0E0B0E098 -:10F83000282B392B4A2B5B2B8C8190E0A0E0B0E089 -:10F84000BA2FA92F982F8827282B392B4A2B5B2BCF -:10F85000220F331F441F551FC05EDE4F288339839C -:10F860004A835B83C052D1401A8259C13A81C95C34 -:10F87000DE4F3883C753D140CA5CDE4F1882C6536F -:10F88000D1408B81C82EDD24CA5CDE4F488159816E -:10F89000C653D140C42AD52A933109F082C0CE5C28 -:10F8A000DE4F88819981AA81BB81C253D1408050AB -:10F8B000904CA340B04030F583E0CE5CDE4FE88052 -:10F8C000F9800A811B81C253D140F70100935B008C -:10F8D00080935700E89507B600FCFDCFCE5CDE4F65 -:10F8E000088119812A813B81C253D14000501F4FAA -:10F8F0002F4F3F4FCE5CDE4F088319832A833B8313 -:10F90000C253D140C05EDE4F488159816A817B81FC -:10F91000C052D140DE011B9631E08C9111962C91A2 -:10F9200011971296C75CDE4F2883C953D140C85C3B -:10F93000DE4F1882C853D14090E0C85CDE4FE881AA -:10F94000F981C853D1408E2B9F2B0C01FA01609393 -:10F950005B0030935700E89511244E5F5F4F6F4F67 -:10F960007F4F0EEFE02E0FEFF02ECE0CDF1CC114F8 -:10F97000D10499F685E0C05EDE4F088119812A81A5 -:10F980003B81C052D140F80120935B008093570027 -:10F99000E89507B600FCFDCF81E180935700E8951C -:10F9A00035C0C05EDE4F88819981AA81BB81C0527B -:10F9B000D140B695A795979587957C018601ABE0D8 -:10F9C000AA2EB12CAC0EBD1E0BC0D5016D915D01F0 -:10F9D000C7010F947FFE0894E11CF11C01501040F8 -:10F9E0000115110591F7A60160E070E0440F551F65 -:10F9F000661F771FC05EDE4FE880F9800A811B8199 -:10FA0000C052D1404E0D5F1D601F711F1A82C05E33 -:10FA1000DE4F488359836A837B83C052D1407FC0C5 -:10FA2000FA80C55CDE4FF882CB53D140C65CDE4F16 -:10FA30001882CA53D1408B81C82EDD24C65CDE4FAC -:10FA400008811981CA53D140C02AD12A1A828981DA -:10FA5000BE016D5F7F4F843121F59601C05EDE4FA0 -:10FA6000E880F9800A811B81C052D1400BBFF701A9 -:10FA700087919691DB018C9311969C936E5F7F4FDB -:10FA8000D801C7010296A11DB11DC05EDE4F88835B -:10FA90009983AA83BB83C052D14022503040F1F6F3 -:10FAA00036C0C05EDE4F288139814A815B81C052F9 -:10FAB000D1400894C108D108760100E010E0089414 -:10FAC000C11CD11C0894E11CF11C011D111DE20E8A -:10FAD000F31E041F151F21BDBB27A52F942F832FB5 -:10FAE00082BD2F5F3F4F4F4F5F4FF89A80B5DB01CC -:10FAF0008D93BD012E153F054007510761F7C05E8C -:10FB0000DE4F288339834A835B83C052D1409601FC -:10FB10002D5F3F4FFB01108204C080EC8A8322E0FE -:10FB200030E08BE18093C6008091C00086FFFCCF5F -:10FB30008091C00080648093C000C15DDE4FF88179 -:10FB4000CF52D140F093C6008091C00086FFFCCF19 -:10FB50008091C00080648093C000432F3093C60022 -:10FB60008091C00086FFFCCF8091C00080648093AC -:10FB7000C000922F2093C6008091C00086FFFCCF6A -:10FB80008091C00080648093C0008EE08093C600A6 -:10FB90008091C00086FFFCCF8091C000806480937C -:10FBA000C00065E1C15DDE4FE880CF52D1406E25D7 -:10FBB00069276427FE01319610C090819093C6009A -:10FBC0008091C00086FFFCCF31968091C000806498 -:10FBD0008093C0006927215030402115310569F715 -:10FBE0006093C6008091C00086FFFCCF8091C0006A -:10FBF00080648093C00085B1805885B9772081F4F6 -:10FC0000C15DDE4F0881CF52D1400F5FC15DDE4F35 -:10FC10000883CF52D14090E0A0E0B0E00D941AF4F8 -:10FC200027982F9880E090E020ED37E0F901319798 -:10FC3000F1F7019684369105C9F700008091C00064 -:10FC40008D7F8093C00081E180935700E895EE2777 -:10FC5000FF270994FFCF90E00D941AF497FB092E2B -:10FC600007260AD077FD04D02ED006D000201AF443 -:10FC7000709561957F4F0895F6F7909581959F4F08 -:10FC80000895A1E21A2EAA1BBB1BFD010DC0AA1FDD -:10FC9000BB1FEE1FFF1FA217B307E407F50720F0F5 -:10FCA000A21BB30BE40BF50B661F771F881F991F70 -:10FCB0001A9469F760957095809590959B01AC01B9 -:10FCC000BD01CF010895AA1BBB1B51E107C0AA1FAC -:10FCD000BB1FA617B70710F0A61BB70B881F991FED -:10FCE0005A95A9F780959095BC01CD010895F99991 -:10FCF000FECF92BD81BDF89A992780B50895262F31 -:10FD0000F999FECF1FBA92BD81BD20BD0FB6F89400 -:0EFD1000FA9AF99A0FBE01960895F894FFCF63 -:040000033000E000E9 -:00000001FF diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp b/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp deleted file mode 100644 index af14e07b..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/SPI.cpp +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright (c) 2010 by Cristian Maglie - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#include "SPI.h" - -SPIClass SPI; - -uint8_t SPIClass::initialized = 0; -uint8_t SPIClass::interruptMode = 0; -uint8_t SPIClass::interruptMask = 0; -uint8_t SPIClass::interruptSave = 0; -#ifdef SPI_TRANSACTION_MISMATCH_LED -uint8_t SPIClass::inTransactionFlag = 0; -#endif - -void SPIClass::begin() -{ - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - if (!initialized) { - // Set SS to high so a connected chip will be "deselected" by default - uint8_t port = digitalPinToPort(SS); - uint8_t bit = digitalPinToBitMask(SS); - volatile uint8_t *reg = portModeRegister(port); - - // if the SS pin is not already configured as an output - // then set it high (to enable the internal pull-up resistor) - if(!(*reg & bit)){ - digitalWrite(SS, HIGH); - } - - // When the SS pin is set as OUTPUT, it can be used as - // a general purpose output port (it doesn't influence - // SPI operations). - pinMode(SS, OUTPUT); - - // Warning: if the SS pin ever becomes a LOW INPUT then SPI - // automatically switches to Slave, so the data direction of - // the SS pin MUST be kept as OUTPUT. - SPCR |= _BV(MSTR); - SPCR |= _BV(SPE); - - // Set direction register for SCK and MOSI pin. - // MISO pin automatically overrides to INPUT. - // By doing this AFTER enabling SPI, we avoid accidentally - // clocking in a single bit since the lines go directly - // from "input" to SPI control. - // http://code.google.com/p/arduino/issues/detail?id=888 - pinMode(SCK, OUTPUT); - pinMode(MOSI, OUTPUT); - } - initialized++; // reference count - SREG = sreg; -} - -void SPIClass::end() { - uint8_t sreg = SREG; - noInterrupts(); // Protect from a scheduler and prevent transactionBegin - // Decrease the reference counter - if (initialized) - initialized--; - // If there are no more references disable SPI - if (!initialized) { - SPCR &= ~_BV(SPE); - interruptMode = 0; - #ifdef SPI_TRANSACTION_MISMATCH_LED - inTransactionFlag = 0; - #endif - } - SREG = sreg; -} - -// mapping of interrupt numbers to bits within SPI_AVR_EIMSK -#if defined(__AVR_ATmega32U4__) - #define SPI_INT0_MASK (1< - * Copyright (c) 2014 by Paul Stoffregen (Transaction API) - * Copyright (c) 2014 by Matthijs Kooijman (SPISettings AVR) - * Copyright (c) 2014 by Andrew J. Kroll (atomicity fixes) - * SPI Master library for arduino. - * - * This file is free software; you can redistribute it and/or modify - * it under the terms of either the GNU General Public License version 2 - * or the GNU Lesser General Public License version 2.1, both as - * published by the Free Software Foundation. - */ - -#ifndef _SPI_H_INCLUDED -#define _SPI_H_INCLUDED - -#include - -// SPI_HAS_TRANSACTION means SPI has beginTransaction(), endTransaction(), -// usingInterrupt(), and SPISetting(clock, bitOrder, dataMode) -#define SPI_HAS_TRANSACTION 1 - -// SPI_HAS_NOTUSINGINTERRUPT means that SPI has notUsingInterrupt() method -#define SPI_HAS_NOTUSINGINTERRUPT 1 - -// SPI_ATOMIC_VERSION means that SPI has atomicity fixes and what version. -// This way when there is a bug fix you can check this define to alert users -// of your code if it uses better version of this library. -// This also implies everything that SPI_HAS_TRANSACTION as documented above is -// available too. -#define SPI_ATOMIC_VERSION 1 - -// Uncomment this line to add detection of mismatched begin/end transactions. -// A mismatch occurs if other libraries fail to use SPI.endTransaction() for -// each SPI.beginTransaction(). Connect an LED to this pin. The LED will turn -// on if any mismatch is ever detected. -//#define SPI_TRANSACTION_MISMATCH_LED 5 - -#ifndef LSBFIRST -#define LSBFIRST 0 -#endif -#ifndef MSBFIRST -#define MSBFIRST 1 -#endif - -#define SPI_CLOCK_DIV4 0x00 -#define SPI_CLOCK_DIV16 0x01 -#define SPI_CLOCK_DIV64 0x02 -#define SPI_CLOCK_DIV128 0x03 -#define SPI_CLOCK_DIV2 0x04 -#define SPI_CLOCK_DIV8 0x05 -#define SPI_CLOCK_DIV32 0x06 - -#define SPI_MODE0 0x00 -#define SPI_MODE1 0x04 -#define SPI_MODE2 0x08 -#define SPI_MODE3 0x0C - -#define SPI_MODE_MASK 0x0C // CPOL = bit 3, CPHA = bit 2 on SPCR -#define SPI_CLOCK_MASK 0x03 // SPR1 = bit 1, SPR0 = bit 0 on SPCR -#define SPI_2XCLOCK_MASK 0x01 // SPI2X = bit 0 on SPSR - -// define SPI_AVR_EIMSK for AVR boards with external interrupt pins -#if defined(EIMSK) - #define SPI_AVR_EIMSK EIMSK -#elif defined(GICR) - #define SPI_AVR_EIMSK GICR -#elif defined(GIMSK) - #define SPI_AVR_EIMSK GIMSK -#endif - -class SPISettings { -public: - SPISettings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - if (__builtin_constant_p(clock)) { - init_AlwaysInline(clock, bitOrder, dataMode); - } else { - init_MightInline(clock, bitOrder, dataMode); - } - } - SPISettings() { - init_AlwaysInline(4000000, MSBFIRST, SPI_MODE0); - } -private: - void init_MightInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) { - init_AlwaysInline(clock, bitOrder, dataMode); - } - void init_AlwaysInline(uint32_t clock, uint8_t bitOrder, uint8_t dataMode) - __attribute__((__always_inline__)) { - // Clock settings are defined as follows. Note that this shows SPI2X - // inverted, so the bits form increasing numbers. Also note that - // fosc/64 appears twice - // SPR1 SPR0 ~SPI2X Freq - // 0 0 0 fosc/2 - // 0 0 1 fosc/4 - // 0 1 0 fosc/8 - // 0 1 1 fosc/16 - // 1 0 0 fosc/32 - // 1 0 1 fosc/64 - // 1 1 0 fosc/64 - // 1 1 1 fosc/128 - - // We find the fastest clock that is less than or equal to the - // given clock rate. The clock divider that results in clock_setting - // is 2 ^^ (clock_div + 1). If nothing is slow enough, we'll use the - // slowest (128 == 2 ^^ 7, so clock_div = 6). - uint8_t clockDiv; - - // When the clock is known at compiletime, use this if-then-else - // cascade, which the compiler knows how to completely optimize - // away. When clock is not known, use a loop instead, which generates - // shorter code. - if (__builtin_constant_p(clock)) { - if (clock >= F_CPU / 2) { - clockDiv = 0; - } else if (clock >= F_CPU / 4) { - clockDiv = 1; - } else if (clock >= F_CPU / 8) { - clockDiv = 2; - } else if (clock >= F_CPU / 16) { - clockDiv = 3; - } else if (clock >= F_CPU / 32) { - clockDiv = 4; - } else if (clock >= F_CPU / 64) { - clockDiv = 5; - } else { - clockDiv = 6; - } - } else { - uint32_t clockSetting = F_CPU / 2; - clockDiv = 0; - while (clockDiv < 6 && clock < clockSetting) { - clockSetting /= 2; - clockDiv++; - } - } - - // Compensate for the duplicate fosc/64 - if (clockDiv == 6) - clockDiv = 7; - - // Invert the SPI2X bit - clockDiv ^= 0x1; - - // Pack into the SPISettings class - spcr = _BV(SPE) | _BV(MSTR) | ((bitOrder == LSBFIRST) ? _BV(DORD) : 0) | - (dataMode & SPI_MODE_MASK) | ((clockDiv >> 1) & SPI_CLOCK_MASK); - spsr = clockDiv & SPI_2XCLOCK_MASK; - } - uint8_t spcr; - uint8_t spsr; - friend class SPIClass; -}; - - -class SPIClass { -public: - // Initialize the SPI library - static void begin(); - - // If SPI is used from within an interrupt, this function registers - // that interrupt with the SPI library, so beginTransaction() can - // prevent conflicts. The input interruptNumber is the number used - // with attachInterrupt. If SPI is used from a different interrupt - // (eg, a timer), interruptNumber should be 255. - static void usingInterrupt(uint8_t interruptNumber); - // And this does the opposite. - static void notUsingInterrupt(uint8_t interruptNumber); - // Note: the usingInterrupt and notUsingInterrupt functions should - // not to be called from ISR context or inside a transaction. - // For details see: - // https://github.com/arduino/Arduino/pull/2381 - // https://github.com/arduino/Arduino/pull/2449 - - // Before using SPI.transfer() or asserting chip select pins, - // this function is used to gain exclusive access to the SPI bus - // and configure the correct settings. - inline static void beginTransaction(SPISettings settings) { - if (interruptMode > 0) { - uint8_t sreg = SREG; - noInterrupts(); - - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - interruptSave = SPI_AVR_EIMSK; - SPI_AVR_EIMSK &= ~interruptMask; - SREG = sreg; - } else - #endif - { - interruptSave = sreg; - } - } - - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 1; - #endif - - SPCR = settings.spcr; - SPSR = settings.spsr; - } - - // Write to the SPI bus (MOSI pin) and also receive (MISO pin) - inline static uint8_t transfer(uint8_t data) { - SPDR = data; - /* - * The following NOP introduces a small delay that can prevent the wait - * loop form iterating when running at the maximum speed. This gives - * about 10% more speed, even if it seems counter-intuitive. At lower - * speeds it is unnoticed. - */ - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; // wait - return SPDR; - } - inline static uint16_t transfer16(uint16_t data) { - union { uint16_t val; struct { uint8_t lsb; uint8_t msb; }; } in, out; - in.val = data; - if (!(SPCR & _BV(DORD))) { - SPDR = in.msb; - asm volatile("nop"); // See transfer(uint8_t) function - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - } else { - SPDR = in.lsb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.lsb = SPDR; - SPDR = in.msb; - asm volatile("nop"); - while (!(SPSR & _BV(SPIF))) ; - out.msb = SPDR; - } - return out.val; - } - inline static void transfer(void *buf, size_t count) { - if (count == 0) return; - uint8_t *p = (uint8_t *)buf; - SPDR = *p; - while (--count > 0) { - uint8_t out = *(p + 1); - while (!(SPSR & _BV(SPIF))) ; - uint8_t in = SPDR; - SPDR = out; - *p++ = in; - } - while (!(SPSR & _BV(SPIF))) ; - *p = SPDR; - } - // After performing a group of transfers and releasing the chip select - // signal, this function allows others to access the SPI bus - inline static void endTransaction(void) { - #ifdef SPI_TRANSACTION_MISMATCH_LED - if (!inTransactionFlag) { - pinMode(SPI_TRANSACTION_MISMATCH_LED, OUTPUT); - digitalWrite(SPI_TRANSACTION_MISMATCH_LED, HIGH); - } - inTransactionFlag = 0; - #endif - - if (interruptMode > 0) { - #ifdef SPI_AVR_EIMSK - uint8_t sreg = SREG; - #endif - noInterrupts(); - #ifdef SPI_AVR_EIMSK - if (interruptMode == 1) { - SPI_AVR_EIMSK = interruptSave; - SREG = sreg; - } else - #endif - { - SREG = interruptSave; - } - } - } - - // Disable the SPI bus - static void end(); - - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setBitOrder(uint8_t bitOrder) { - if (bitOrder == LSBFIRST) SPCR |= _BV(DORD); - else SPCR &= ~(_BV(DORD)); - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setDataMode(uint8_t dataMode) { - SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode; - } - // This function is deprecated. New applications should use - // beginTransaction() to configure SPI settings. - inline static void setClockDivider(uint8_t clockDiv) { - SPCR = (SPCR & ~SPI_CLOCK_MASK) | (clockDiv & SPI_CLOCK_MASK); - SPSR = (SPSR & ~SPI_2XCLOCK_MASK) | ((clockDiv >> 2) & SPI_2XCLOCK_MASK); - } - // These undocumented functions should not be used. SPI.transfer() - // polls the hardware flag which is automatically cleared as the - // AVR responds to SPI's interrupt - inline static void attachInterrupt() { SPCR |= _BV(SPIE); } - inline static void detachInterrupt() { SPCR &= ~_BV(SPIE); } - -private: - static uint8_t initialized; - static uint8_t interruptMode; // 0=none, 1=mask, 2=global - static uint8_t interruptMask; // which interrupts to mask - static uint8_t interruptSave; // temp storage, to restore state - #ifdef SPI_TRANSACTION_MISMATCH_LED - static uint8_t inTransactionFlag; - #endif -}; - -extern SPIClass SPI; - -#endif diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino b/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino deleted file mode 100644 index 8104fcbc..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/BarometricPressureSensor/BarometricPressureSensor.ino +++ /dev/null @@ -1,143 +0,0 @@ -/* - SCP1000 Barometric Pressure Sensor Display - - Shows the output of a Barometric Pressure Sensor on a - Uses the SPI library. For details on the sensor, see: - http://www.sparkfun.com/commerce/product_info.php?products_id=8161 - http://www.vti.fi/en/support/obsolete_products/pressure_sensors/ - - This sketch adapted from Nathan Seidle's SCP1000 example for PIC: - http://www.sparkfun.com/datasheets/Sensors/SCP1000-Testing.zip - - Circuit: - SCP1000 sensor attached to pins 6, 7, 10 - 13: - DRDY: pin 6 - CSB: pin 7 - MOSI: pin 11 - MISO: pin 12 - SCK: pin 13 - - created 31 July 2010 - modified 14 August 2010 - by Tom Igoe - */ - -// the sensor communicates using SPI, so include the library: -#include - -//Sensor's memory register addresses: -const int PRESSURE = 0x1F; //3 most significant bits of pressure -const int PRESSURE_LSB = 0x20; //16 least significant bits of pressure -const int TEMPERATURE = 0x21; //16 bit temperature reading -const byte READ = 0b11111100; // SCP1000's read command -const byte WRITE = 0b00000010; // SCP1000's write command - -// pins used for the connection with the sensor -// the other you need are controlled by the SPI library): -const int dataReadyPin = 6; -const int chipSelectPin = 7; - -void setup() { - Serial.begin(9600); - - // start the SPI library: - SPI.begin(); - - // initalize the data ready and chip select pins: - pinMode(dataReadyPin, INPUT); - pinMode(chipSelectPin, OUTPUT); - - //Configure SCP1000 for low noise configuration: - writeRegister(0x02, 0x2D); - writeRegister(0x01, 0x03); - writeRegister(0x03, 0x02); - // give the sensor time to set up: - delay(100); -} - -void loop() { - //Select High Resolution Mode - writeRegister(0x03, 0x0A); - - // don't do anything until the data ready pin is high: - if (digitalRead(dataReadyPin) == HIGH) { - //Read the temperature data - int tempData = readRegister(0x21, 2); - - // convert the temperature to celsius and display it: - float realTemp = (float)tempData / 20.0; - Serial.print("Temp[C]="); - Serial.print(realTemp); - - - //Read the pressure data highest 3 bits: - byte pressure_data_high = readRegister(0x1F, 1); - pressure_data_high &= 0b00000111; //you only needs bits 2 to 0 - - //Read the pressure data lower 16 bits: - unsigned int pressure_data_low = readRegister(0x20, 2); - //combine the two parts into one 19-bit number: - long pressure = ((pressure_data_high << 16) | pressure_data_low) / 4; - - // display the temperature: - Serial.println("\tPressure [Pa]=" + String(pressure)); - } -} - -//Read from or write to register from the SCP1000: -unsigned int readRegister(byte thisRegister, int bytesToRead ) { - byte inByte = 0; // incoming byte from the SPI - unsigned int result = 0; // result to return - Serial.print(thisRegister, BIN); - Serial.print("\t"); - // SCP1000 expects the register name in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the address and the command into one byte - byte dataToSend = thisRegister & READ; - Serial.println(thisRegister, BIN); - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - // send the device the register you want to read: - SPI.transfer(dataToSend); - // send a value of 0 to read the first byte returned: - result = SPI.transfer(0x00); - // decrement the number of bytes left to read: - bytesToRead--; - // if you still have another byte to read: - if (bytesToRead > 0) { - // shift the first byte left, then get the second byte: - result = result << 8; - inByte = SPI.transfer(0x00); - // combine the byte you just got with the previous one: - result = result | inByte; - // decrement the number of bytes left to read: - bytesToRead--; - } - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); - // return the result: - return(result); -} - - -//Sends a write command to SCP1000 - -void writeRegister(byte thisRegister, byte thisValue) { - - // SCP1000 expects the register address in the upper 6 bits - // of the byte. So shift the bits left by two bits: - thisRegister = thisRegister << 2; - // now combine the register address and the command into one byte: - byte dataToSend = thisRegister | WRITE; - - // take the chip select low to select the device: - digitalWrite(chipSelectPin, LOW); - - SPI.transfer(dataToSend); //Send register location - SPI.transfer(thisValue); //Send value to record into register - - // take the chip select high to de-select: - digitalWrite(chipSelectPin, HIGH); -} - diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino b/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino deleted file mode 100644 index b135a74f..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/examples/DigitalPotControl/DigitalPotControl.ino +++ /dev/null @@ -1,71 +0,0 @@ -/* - Digital Pot Control - - This example controls an Analog Devices AD5206 digital potentiometer. - The AD5206 has 6 potentiometer channels. Each channel's pins are labeled - A - connect this to voltage - W - this is the pot's wiper, which changes when you set it - B - connect this to ground. - - The AD5206 is SPI-compatible,and to command it, you send two bytes, - one with the channel number (0 - 5) and one with the resistance value for the - channel (0 - 255). - - The circuit: - * All A pins of AD5206 connected to +5V - * All B pins of AD5206 connected to ground - * An LED and a 220-ohm resisor in series connected from each W pin to ground - * CS - to digital pin 10 (SS pin) - * SDI - to digital pin 11 (MOSI pin) - * CLK - to digital pin 13 (SCK pin) - - created 10 Aug 2010 - by Tom Igoe - - Thanks to Heather Dewey-Hagborg for the original tutorial, 2005 - -*/ - - -// inslude the SPI library: -#include - - -// set pin 10 as the slave select for the digital pot: -const int slaveSelectPin = 10; - -void setup() { - // set the slaveSelectPin as an output: - pinMode (slaveSelectPin, OUTPUT); - // initialize SPI: - SPI.begin(); -} - -void loop() { - // go through the six channels of the digital pot: - for (int channel = 0; channel < 6; channel++) { - // change the resistance on this channel from min to max: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, level); - delay(10); - } - // wait a second at the top: - delay(100); - // change the resistance on this channel from max to min: - for (int level = 0; level < 255; level++) { - digitalPotWrite(channel, 255 - level); - delay(10); - } - } - -} - -void digitalPotWrite(int address, int value) { - // take the SS pin low to select the chip: - digitalWrite(slaveSelectPin, LOW); - // send in the address and value via SPI: - SPI.transfer(address); - SPI.transfer(value); - // take the SS pin high to de-select the chip: - digitalWrite(slaveSelectPin, HIGH); -} diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt b/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt deleted file mode 100644 index fa761658..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/keywords.txt +++ /dev/null @@ -1,36 +0,0 @@ -####################################### -# Syntax Coloring Map SPI -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -SPI KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 -transfer KEYWORD2 -setBitOrder KEYWORD2 -setDataMode KEYWORD2 -setClockDivider KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### -SPI_CLOCK_DIV4 LITERAL1 -SPI_CLOCK_DIV16 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_CLOCK_DIV128 LITERAL1 -SPI_CLOCK_DIV2 LITERAL1 -SPI_CLOCK_DIV8 LITERAL1 -SPI_CLOCK_DIV32 LITERAL1 -SPI_CLOCK_DIV64 LITERAL1 -SPI_MODE0 LITERAL1 -SPI_MODE1 LITERAL1 -SPI_MODE2 LITERAL1 -SPI_MODE3 LITERAL1 \ No newline at end of file diff --git a/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties b/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties deleted file mode 100644 index 07af8696..00000000 --- a/test/user_hardware/my_avr_platform/avr/libraries/SPI/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=SPI -version=1.0 -author=Arduino -maintainer=Arduino -sentence=Enables the communication with devices that use the Serial Peripheral Interface (SPI) Bus. For all Arduino boards, BUT Arduino DUE. -paragraph= -url=http://arduino.cc/en/Reference/SPI -architectures=avr -types=Arduino - diff --git a/test/user_hardware/my_avr_platform/avr/platform.txt b/test/user_hardware/my_avr_platform/avr/platform.txt deleted file mode 100644 index cc0be0a0..00000000 --- a/test/user_hardware/my_avr_platform/avr/platform.txt +++ /dev/null @@ -1,9 +0,0 @@ - -# Arduino AVR Core and platform. -# ------------------------------ - -# For more info: -# https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5---3rd-party-Hardware-specification - -name=My AVR Boards -version=9.9.9 \ No newline at end of file diff --git a/test/user_hardware/my_avr_platform/platform.txt b/test/user_hardware/my_avr_platform/platform.txt deleted file mode 100644 index 4c1664e5..00000000 --- a/test/user_hardware/my_avr_platform/platform.txt +++ /dev/null @@ -1 +0,0 @@ -example=hello world diff --git a/test/user_hardware/my_symlinked_avr_platform b/test/user_hardware/my_symlinked_avr_platform deleted file mode 120000 index 8f67ba7e..00000000 --- a/test/user_hardware/my_symlinked_avr_platform +++ /dev/null @@ -1 +0,0 @@ -my_avr_platform \ No newline at end of file diff --git a/test/utils_test.go b/test/utils_test.go deleted file mode 100644 index 6ada0c29..00000000 --- a/test/utils_test.go +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/utils" - "github.com/stretchr/testify/require" - "strings" - "testing" -) - -func TestCommandLineParser(t *testing.T) { - command := "\"/home/federico/materiale/works_Arduino/Arduino/build/hardware/tools/coan\" source -m -E -P -kb -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=atmega32u4 -DF_CPU=16000000L -DARDUINO=010600 -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=0x2341 -DUSB_PID=0x8036 '-DUSB_MANUFACTURER=' '-DUSB_PRODUCT=\"Arduino Leonardo\"' \"/tmp/sketch321469072.cpp\"" - - parts, err := utils.ParseCommandLine(command, i18n.HumanLogger{}) - NoError(t, err) - - require.Equal(t, 23, len(parts)) - - require.Equal(t, "/home/federico/materiale/works_Arduino/Arduino/build/hardware/tools/coan", parts[0]) - require.Equal(t, "source", parts[1]) - require.Equal(t, "-m", parts[2]) - require.Equal(t, "-E", parts[3]) - require.Equal(t, "-P", parts[4]) - require.Equal(t, "-kb", parts[5]) - require.Equal(t, "-c", parts[6]) - require.Equal(t, "-g", parts[7]) - require.Equal(t, "-Os", parts[8]) - require.Equal(t, "-w", parts[9]) - require.Equal(t, "-ffunction-sections", parts[10]) - require.Equal(t, "-fdata-sections", parts[11]) - require.Equal(t, "-MMD", parts[12]) - require.Equal(t, "-mmcu=atmega32u4", parts[13]) - require.Equal(t, "-DF_CPU=16000000L", parts[14]) - require.Equal(t, "-DARDUINO=010600", parts[15]) - require.Equal(t, "-DARDUINO_AVR_LEONARDO", parts[16]) - require.Equal(t, "-DARDUINO_ARCH_AVR", parts[17]) - require.Equal(t, "-DUSB_VID=0x2341", parts[18]) - require.Equal(t, "-DUSB_PID=0x8036", parts[19]) - require.Equal(t, "-DUSB_MANUFACTURER=", parts[20]) - require.Equal(t, "-DUSB_PRODUCT=\"Arduino Leonardo\"", parts[21]) - require.Equal(t, "/tmp/sketch321469072.cpp", parts[22]) -} - -func TestPrintableCommand(t *testing.T) { - parts := []string{ - "/path/to/dir with spaces/cmd", - "arg1", - "arg-\"with\"-quotes", - "specialchar-`~!@#$%^&*()-_=+[{]}\\|;:'\",<.>/?-argument", - "arg with spaces", - "arg\twith\t\ttabs", - "lastarg", - } - correct := "\"/path/to/dir with spaces/cmd\"" + - " arg1 \"arg-\\\"with\\\"-quotes\"" + - " \"specialchar-`~!@#$%^&*()-_=+[{]}\\\\|;:'\\\",<.>/?-argument\"" + - " \"arg with spaces\" \"arg\twith\t\ttabs\"" + - " lastarg" - result := utils.PrintableCommand(parts) - require.Equal(t, correct, result) -} - -func TestCommandLineParserError(t *testing.T) { - command := "\"command missing quote" - - _, err := utils.ParseCommandLine(command, i18n.HumanLogger{}) - require.Error(t, err) -} - -func TestMapTrimSpace(t *testing.T) { - value := "hello, world , how are,you? " - parts := utils.Map(strings.Split(value, ","), utils.TrimSpace) - - require.Equal(t, 4, len(parts)) - require.Equal(t, "hello", parts[0]) - require.Equal(t, "world", parts[1]) - require.Equal(t, "how are", parts[2]) - require.Equal(t, "you?", parts[3]) -} - -func TestQuoteCppString(t *testing.T) { - cases := map[string]string{ - `foo`: `"foo"`, - `foo\bar`: `"foo\\bar"`, - `foo "is" quoted and \\bar"" escaped\`: `"foo \"is\" quoted and \\\\bar\"\" escaped\\"`, - // ASCII 0x20 - 0x7e, excluding ` - ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~`: `" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~"`, - } - for input, expected := range cases { - require.Equal(t, expected, utils.QuoteCppString(input)) - } -} - -func TestParseCppString(t *testing.T) { - str, rest, ok := utils.ParseCppString(`foo`) - require.Equal(t, false, ok) - - str, rest, ok = utils.ParseCppString(`"foo`) - require.Equal(t, false, ok) - - str, rest, ok = utils.ParseCppString(`"foo"`) - require.Equal(t, true, ok) - require.Equal(t, `foo`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"foo\\bar"`) - require.Equal(t, true, ok) - require.Equal(t, `foo\bar`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"foo \"is\" quoted and \\\\bar\"\" escaped\\" and "then" some`) - require.Equal(t, true, ok) - require.Equal(t, `foo "is" quoted and \\bar"" escaped\`, str) - require.Equal(t, ` and "then" some`, rest) - - str, rest, ok = utils.ParseCppString(`" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~"`) - require.Equal(t, true, ok) - require.Equal(t, ` !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"/home/ççç/"`) - require.Equal(t, true, ok) - require.Equal(t, `/home/ççç/`, str) - require.Equal(t, ``, rest) - - str, rest, ok = utils.ParseCppString(`"/home/ççç/ /$sdsdd\\"`) - require.Equal(t, true, ok) - require.Equal(t, `/home/ççç/ /$sdsdd\`, str) - require.Equal(t, ``, rest) -} diff --git a/test/wipeout_build_path_if_build_options_changed_test.go b/test/wipeout_build_path_if_build_options_changed_test.go deleted file mode 100644 index 64212fa0..00000000 --- a/test/wipeout_build_path_if_build_options_changed_test.go +++ /dev/null @@ -1,104 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package test - -import ( - "testing" - - "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/types" - "github.com/stretchr/testify/require" -) - -func TestWipeoutBuildPathIfBuildOptionsChanged(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - ctx.BuildOptionsJsonPrevious = "{ \"old\":\"old\" }" - ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - - buildPath.Join("should_be_deleted.txt").Truncate() - - commands := []types.Command{ - &builder.WipeoutBuildPathIfBuildOptionsChanged{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - exist, err := buildPath.ExistCheck() - NoError(t, err) - require.True(t, exist) - - files, err := gohasissues.ReadDir(buildPath.String()) - NoError(t, err) - require.Equal(t, 0, len(files)) - - exist, err = buildPath.Join("should_be_deleted.txt").ExistCheck() - require.NoError(t, err) - require.False(t, exist) -} - -func TestWipeoutBuildPathIfBuildOptionsChangedNoPreviousBuildOptions(t *testing.T) { - ctx := &types.Context{} - - buildPath := SetupBuildPath(t, ctx) - defer buildPath.RemoveAll() - - ctx.BuildOptionsJson = "{ \"new\":\"new\" }" - - require.NoError(t, buildPath.Join("should_not_be_deleted.txt").Truncate()) - - commands := []types.Command{ - &builder.WipeoutBuildPathIfBuildOptionsChanged{}, - } - - for _, command := range commands { - err := command.Run(ctx) - NoError(t, err) - } - - exist, err := buildPath.ExistCheck() - NoError(t, err) - require.True(t, exist) - - files, err := gohasissues.ReadDir(buildPath.String()) - NoError(t, err) - require.Equal(t, 1, len(files)) - - exist, err = buildPath.Join("should_not_be_deleted.txt").ExistCheck() - NoError(t, err) - require.True(t, exist) -} diff --git a/tools_loader.go b/tools_loader.go deleted file mode 100644 index 05c2ec18..00000000 --- a/tools_loader.go +++ /dev/null @@ -1,87 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "fmt" - "strings" - - "github.com/arduino/arduino-builder/types" - "github.com/arduino/go-paths-helper" -) - -type ToolsLoader struct{} - -func (s *ToolsLoader) Run(ctx *types.Context) error { - if ctx.CanUseCachedTools { - //fmt.Println("no fs modification, can use cached ctx") - return nil - } - - folders := paths.NewPathList() - builtinFolders := paths.NewPathList() - - if ctx.BuiltInToolsDirs != nil || len(ctx.BuiltInLibrariesDirs) == 0 { - folders = ctx.ToolsDirs - builtinFolders = ctx.BuiltInToolsDirs - } else { - // Auto-detect built-in tools folders (for arduino-builder backward compatibility) - // this is a deprecated feature and will be removed in the future - builtinHardwareFolder, err := ctx.BuiltInLibrariesDirs[0].Join("..").Abs() - - if err != nil { - fmt.Println("Error detecting ") - } - - for _, folder := range ctx.ToolsDirs { - if !strings.Contains(folder.String(), builtinHardwareFolder.String()) { // TODO: make a function to check for subfolders - folders = append(folders, folder) - } else { - builtinFolders = append(builtinFolders, folder) - } - } - } - - pm := ctx.PackageManager - pm.LoadToolsFromBundleDirectories(builtinFolders) - - ctx.CanUseCachedTools = true - ctx.AllTools = pm.GetAllInstalledToolsReleases() - - if ctx.TargetBoard != nil { - requiredTools, err := pm.FindToolsRequiredForBoard(ctx.TargetBoard) - if err != nil { - return err - } - ctx.RequiredTools = requiredTools - } - - return nil -} diff --git a/types/accessories.go b/types/accessories.go deleted file mode 100644 index 4c87c30c..00000000 --- a/types/accessories.go +++ /dev/null @@ -1,110 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -import ( - "bytes" - "sync" -) - -type UniqueStringQueue []string - -func (queue UniqueStringQueue) Len() int { return len(queue) } -func (queue UniqueStringQueue) Less(i, j int) bool { return false } -func (queue UniqueStringQueue) Swap(i, j int) { panic("Who called me?!?") } - -func (queue *UniqueStringQueue) Push(value string) { - if !sliceContains(*queue, value) { - *queue = append(*queue, value) - } -} - -func (queue *UniqueStringQueue) Pop() interface{} { - old := *queue - x := old[0] - *queue = old[1:] - return x -} - -func (queue *UniqueStringQueue) Empty() bool { - return queue.Len() == 0 -} - -type UniqueSourceFileQueue []SourceFile - -func (queue UniqueSourceFileQueue) Len() int { return len(queue) } -func (queue UniqueSourceFileQueue) Less(i, j int) bool { return false } -func (queue UniqueSourceFileQueue) Swap(i, j int) { panic("Who called me?!?") } - -func (queue *UniqueSourceFileQueue) Push(value SourceFile) { - if !sliceContainsSourceFile(*queue, value) { - *queue = append(*queue, value) - } -} - -func (queue *UniqueSourceFileQueue) Pop() SourceFile { - old := *queue - x := old[0] - *queue = old[1:] - return x -} - -func (queue *UniqueSourceFileQueue) Empty() bool { - return queue.Len() == 0 -} - -type BufferedUntilNewLineWriter struct { - PrintFunc PrintFunc - Buffer bytes.Buffer - lock sync.Mutex -} - -type PrintFunc func([]byte) - -func (w *BufferedUntilNewLineWriter) Write(p []byte) (n int, err error) { - w.lock.Lock() - defer w.lock.Unlock() - - writtenToBuffer, err := w.Buffer.Write(p) - return writtenToBuffer, err -} - -func (w *BufferedUntilNewLineWriter) Flush() { - w.lock.Lock() - defer w.lock.Unlock() - - remainingBytes := w.Buffer.Bytes() - if len(remainingBytes) > 0 { - if remainingBytes[len(remainingBytes)-1] != '\n' { - remainingBytes = append(remainingBytes, '\n') - } - w.PrintFunc(remainingBytes) - } -} diff --git a/types/context.go b/types/context.go deleted file mode 100644 index d263908e..00000000 --- a/types/context.go +++ /dev/null @@ -1,169 +0,0 @@ -package types - -import ( - "io" - "strings" - - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-cli/arduino/cores" - "github.com/arduino/arduino-cli/arduino/cores/packagemanager" - "github.com/arduino/arduino-cli/arduino/libraries" - "github.com/arduino/arduino-cli/arduino/libraries/librariesmanager" - "github.com/arduino/arduino-cli/arduino/libraries/librariesresolver" - paths "github.com/arduino/go-paths-helper" - properties "github.com/arduino/go-properties-orderedmap" -) - -type ProgressStruct struct { - PrintEnabled bool - Steps float64 - Progress float64 -} - -// Context structure -type Context struct { - // Build options - HardwareDirs paths.PathList - ToolsDirs paths.PathList - BuiltInToolsDirs paths.PathList - BuiltInLibrariesDirs paths.PathList - OtherLibrariesDirs paths.PathList - SketchLocation *paths.Path - WatchedLocations paths.PathList - ArduinoAPIVersion string - FQBN *cores.FQBN - CodeCompleteAt string - - // Build options are serialized here - BuildOptionsJson string - BuildOptionsJsonPrevious string - - PackageManager *packagemanager.PackageManager - Hardware *cores.Packages - AllTools []*cores.ToolRelease - RequiredTools []*cores.ToolRelease - TargetBoard *cores.Board - TargetPackage *cores.Package - TargetPlatform *cores.PlatformRelease - ActualPlatform *cores.PlatformRelease - USBVidPid string - - PlatformKeyRewrites PlatforKeysRewrite - HardwareRewriteResults map[*cores.PlatformRelease][]PlatforKeyRewrite - - BuildProperties *properties.Map - BuildCore string - BuildPath *paths.Path - BuildCachePath *paths.Path - SketchBuildPath *paths.Path - CoreBuildPath *paths.Path - CoreBuildCachePath *paths.Path - CoreArchiveFilePath *paths.Path - CoreObjectsFiles paths.PathList - LibrariesBuildPath *paths.Path - LibrariesObjectFiles paths.PathList - PreprocPath *paths.Path - SketchObjectFiles paths.PathList - - CollectedSourceFiles *UniqueSourceFileQueue - - Sketch *Sketch - Source string - SourceGccMinusE string - CodeCompletions string - - WarningsLevel string - - // Libraries handling - LibrariesManager *librariesmanager.LibrariesManager - LibrariesResolver *librariesresolver.Cpp - ImportedLibraries libraries.List - LibrariesResolutionResults map[string]LibraryResolutionResult - IncludeFolders paths.PathList - //OutputGccMinusM string - - // C++ Parsing - CTagsOutput string - CTagsTargetFile *paths.Path - CTagsOfPreprocessedSource []*CTag - IncludeSection string - LineOffset int - PrototypesSection string - PrototypesLineWhereToInsert int - Prototypes []*Prototype - - // Verbosity settings - Verbose bool - DebugPreprocessor bool - - // Dry run, only create progress map - Progress ProgressStruct - - // 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 - - // Experimental: use arduino-preprocessor to create prototypes - UseArduinoPreprocessor bool - - // Out and Err stream to redirect all Exec commands - ExecStdout io.Writer - ExecStderr io.Writer -} - -func (ctx *Context) ExtractBuildOptions() *properties.Map { - opts := properties.NewMap() - opts.Set("hardwareFolders", strings.Join(ctx.HardwareDirs.AsStrings(), ",")) - opts.Set("toolsFolders", strings.Join(ctx.ToolsDirs.AsStrings(), ",")) - opts.Set("builtInLibrariesFolders", strings.Join(ctx.BuiltInLibrariesDirs.AsStrings(), ",")) - opts.Set("otherLibrariesFolders", strings.Join(ctx.OtherLibrariesDirs.AsStrings(), ",")) - opts.SetPath("sketchLocation", ctx.SketchLocation) - var additionalFilesRelative []string - if ctx.Sketch != nil { - for _, sketch := range ctx.Sketch.AdditionalFiles { - absPath := ctx.SketchLocation.Parent() - relPath, err := sketch.Name.RelTo(absPath) - if err != nil { - continue // ignore - } - additionalFilesRelative = append(additionalFilesRelative, relPath.String()) - } - } - opts.Set("fqbn", ctx.FQBN.String()) - opts.Set("runtime.ide.version", ctx.ArduinoAPIVersion) - opts.Set("customBuildProperties", strings.Join(ctx.CustomBuildProperties, ",")) - opts.Set("additionalFiles", strings.Join(additionalFilesRelative, ",")) - return opts -} - -func (ctx *Context) InjectBuildOptions(opts *properties.Map) { - ctx.HardwareDirs = paths.NewPathList(strings.Split(opts.Get("hardwareFolders"), ",")...) - ctx.ToolsDirs = paths.NewPathList(strings.Split(opts.Get("toolsFolders"), ",")...) - ctx.BuiltInLibrariesDirs = paths.NewPathList(strings.Split(opts.Get("builtInLibrariesFolders"), ",")...) - ctx.OtherLibrariesDirs = paths.NewPathList(strings.Split(opts.Get("otherLibrariesFolders"), ",")...) - ctx.SketchLocation = opts.GetPath("sketchLocation") - fqbn, err := cores.ParseFQBN(opts.Get("fqbn")) - if err != nil { - i18n.ErrorfWithLogger(ctx.GetLogger(), "Error in FQBN: %s", err) - } - ctx.FQBN = fqbn - ctx.ArduinoAPIVersion = opts.Get("runtime.ide.version") - ctx.CustomBuildProperties = strings.Split(opts.Get("customBuildProperties"), ",") -} - -func (ctx *Context) GetLogger() i18n.Logger { - if ctx.logger == nil { - return &i18n.HumanLogger{} - } - return ctx.logger -} - -func (ctx *Context) SetLogger(l i18n.Logger) { - ctx.logger = l -} diff --git a/types/types.go b/types/types.go deleted file mode 100644 index 14c95bc0..00000000 --- a/types/types.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -import ( - "fmt" - "strconv" - - "github.com/arduino/arduino-cli/arduino/libraries" - paths "github.com/arduino/go-paths-helper" -) - -type SourceFile struct { - // Sketch or Library pointer that this source file lives in - Origin interface{} - // Path to the source file within the sketch/library root folder - RelativePath *paths.Path -} - -// Create a SourceFile containing the given source file path within the -// given origin. The given path can be absolute, or relative within the -// origin's root source folder -func MakeSourceFile(ctx *Context, origin interface{}, path *paths.Path) (SourceFile, error) { - if path.IsAbs() { - var err error - path, err = sourceRoot(ctx, origin).RelTo(path) - if err != nil { - return SourceFile{}, err - } - } - return SourceFile{Origin: origin, RelativePath: path}, nil -} - -// Return the build root for the given origin, where build products will -// be placed. Any directories inside SourceFile.RelativePath will be -// appended here. -func buildRoot(ctx *Context, origin interface{}) *paths.Path { - switch o := origin.(type) { - case *Sketch: - return ctx.SketchBuildPath - case *libraries.Library: - return ctx.LibrariesBuildPath.Join(o.Name) - default: - panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) - } -} - -// Return the source root for the given origin, where its source files -// can be found. Prepending this to SourceFile.RelativePath will give -// the full path to that source file. -func sourceRoot(ctx *Context, origin interface{}) *paths.Path { - switch o := origin.(type) { - case *Sketch: - return ctx.SketchBuildPath - case *libraries.Library: - return o.SourceDir - default: - panic("Unexpected origin for SourceFile: " + fmt.Sprint(origin)) - } -} - -func (f *SourceFile) SourcePath(ctx *Context) *paths.Path { - return sourceRoot(ctx, f.Origin).JoinPath(f.RelativePath) -} - -func (f *SourceFile) ObjectPath(ctx *Context) *paths.Path { - return buildRoot(ctx, f.Origin).Join(f.RelativePath.String() + ".o") -} - -func (f *SourceFile) DepfilePath(ctx *Context) *paths.Path { - return buildRoot(ctx, f.Origin).Join(f.RelativePath.String() + ".d") -} - -type SketchFile struct { - Name *paths.Path - Source string -} - -type SketchFileSortByName []SketchFile - -func (s SketchFileSortByName) Len() int { - return len(s) -} - -func (s SketchFileSortByName) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} - -func (s SketchFileSortByName) Less(i, j int) bool { - return s[i].Name.String() < s[j].Name.String() -} - -type Sketch struct { - MainFile SketchFile - OtherSketchFiles []SketchFile - AdditionalFiles []SketchFile -} - -type PlatforKeysRewrite struct { - Rewrites []PlatforKeyRewrite -} - -func (p *PlatforKeysRewrite) Empty() bool { - return len(p.Rewrites) == 0 -} - -type PlatforKeyRewrite struct { - Key string - OldValue string - NewValue string -} - -type Prototype struct { - FunctionName string - File string - Prototype string - Modifiers string - Line int -} - -func (proto *Prototype) String() string { - return proto.Modifiers + " " + proto.Prototype + " @ " + strconv.Itoa(proto.Line) -} - -type LibraryResolutionResult struct { - Library *libraries.Library - NotUsedLibraries []*libraries.Library -} - -type CTag struct { - FunctionName string - Kind string - Line int - Code string - Class string - Struct string - Namespace string - Filename string - Typeref string - SkipMe bool - Signature string - - Prototype string - PrototypeModifiers string -} - -type Command interface { - Run(ctx *Context) error -} diff --git a/types/utils.go b/types/utils.go deleted file mode 100644 index 4016a69b..00000000 --- a/types/utils.go +++ /dev/null @@ -1,49 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package types - -// duplication of utils.SliceContains! Thanks golang! Why? Because with golang you can't have import cycles -func sliceContains(slice []string, target string) bool { - for _, value := range slice { - if value == target { - return true - } - } - return false -} - -func sliceContainsSourceFile(slice []SourceFile, target SourceFile) bool { - for _, elem := range slice { - if elem.Origin == target.Origin && elem.RelativePath.EqualsTo(target.RelativePath) { - return true - } - } - return false -} diff --git a/unused_compiled_libraries_remover.go b/unused_compiled_libraries_remover.go deleted file mode 100644 index 7a940859..00000000 --- a/unused_compiled_libraries_remover.go +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-builder/utils" - "github.com/arduino/arduino-cli/arduino/libraries" -) - -type UnusedCompiledLibrariesRemover struct{} - -func (s *UnusedCompiledLibrariesRemover) Run(ctx *types.Context) error { - librariesBuildPath := ctx.LibrariesBuildPath - - if librariesBuildPath.NotExist() { - return nil - } - - libraryNames := toLibraryNames(ctx.ImportedLibraries) - - files, err := librariesBuildPath.ReadDir() - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - if file.IsDir() { - if !utils.SliceContains(libraryNames, file.Base()) { - if err := file.RemoveAll(); err != nil { - return i18n.WrapError(err) - } - } - } - } - - return nil -} - -func toLibraryNames(libraries []*libraries.Library) []string { - libraryNames := []string{} - for _, library := range libraries { - libraryNames = append(libraryNames, library.Name) - } - return libraryNames -} diff --git a/utils/utils.go b/utils/utils.go deleted file mode 100644 index 55a61b21..00000000 --- a/utils/utils.go +++ /dev/null @@ -1,624 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package utils - -import ( - "bytes" - "crypto/md5" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "unicode" - "unicode/utf8" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - paths "github.com/arduino/go-paths-helper" - "golang.org/x/text/transform" - "golang.org/x/text/unicode/norm" -) - -func PrettyOSName() string { - switch osName := runtime.GOOS; osName { - case "darwin": - return "macosx" - case "freebsd": - return "freebsd" - case "linux": - return "linux" - case "windows": - return "windows" - default: - return "other" - } -} - -func ParseCommandLine(input string, logger i18n.Logger) ([]string, error) { - var parts []string - escapingChar := constants.EMPTY_STRING - escapedArg := constants.EMPTY_STRING - for _, inputPart := range strings.Split(input, constants.SPACE) { - inputPart = strings.TrimSpace(inputPart) - if len(inputPart) == 0 { - continue - } - - if escapingChar == constants.EMPTY_STRING { - if inputPart[0] != '"' && inputPart[0] != '\'' { - parts = append(parts, inputPart) - continue - } - - escapingChar = string(inputPart[0]) - inputPart = inputPart[1:] - escapedArg = constants.EMPTY_STRING - } - - if inputPart[len(inputPart)-1] != '"' && inputPart[len(inputPart)-1] != '\'' { - escapedArg = escapedArg + inputPart + " " - continue - } - - escapedArg = escapedArg + inputPart[:len(inputPart)-1] - escapedArg = strings.TrimSpace(escapedArg) - if len(escapedArg) > 0 { - parts = append(parts, escapedArg) - } - escapingChar = constants.EMPTY_STRING - } - - if escapingChar != constants.EMPTY_STRING { - return nil, i18n.ErrorfWithLogger(logger, constants.MSG_INVALID_QUOTING, escapingChar) - } - - return parts, nil -} - -type filterFiles func([]os.FileInfo) []os.FileInfo - -func ReadDirFiltered(folder string, fn filterFiles) ([]os.FileInfo, error) { - files, err := gohasissues.ReadDir(folder) - if err != nil { - return nil, i18n.WrapError(err) - } - return fn(files), nil -} - -func FilterDirs(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, info := range files { - if info.IsDir() { - filtered = append(filtered, info) - } - } - return filtered -} - -func FilterFilesWithExtensions(extensions ...string) filterFiles { - return func(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, file := range files { - if !file.IsDir() && SliceContains(extensions, filepath.Ext(file.Name())) { - filtered = append(filtered, file) - } - } - return filtered - } -} - -func FilterFiles() filterFiles { - return func(files []os.FileInfo) []os.FileInfo { - var filtered []os.FileInfo - for _, file := range files { - if !file.IsDir() { - filtered = append(filtered, file) - } - } - return filtered - } -} - -var SOURCE_CONTROL_FOLDERS = map[string]bool{"CVS": true, "RCS": true, ".git": true, ".github": true, ".svn": true, ".hg": true, ".bzr": true, ".vscode": true, ".settings": true} - -func IsSCCSOrHiddenFile(file os.FileInfo) bool { - return IsSCCSFile(file) || IsHiddenFile(file) -} - -func IsHiddenFile(file os.FileInfo) bool { - name := filepath.Base(file.Name()) - - if name[0] == '.' { - return true - } - - return false -} - -func IsSCCSFile(file os.FileInfo) bool { - name := filepath.Base(file.Name()) - - if SOURCE_CONTROL_FOLDERS[name] { - return true - } - - return false -} - -func SliceContains(slice []string, target string) bool { - for _, value := range slice { - if value == target { - return true - } - } - return false -} - -type mapFunc func(string) string - -func Map(slice []string, fn mapFunc) []string { - newSlice := []string{} - for _, elem := range slice { - newSlice = append(newSlice, fn(elem)) - } - return newSlice -} - -type filterFunc func(string) bool - -func Filter(slice []string, fn filterFunc) []string { - newSlice := []string{} - for _, elem := range slice { - if fn(elem) { - newSlice = append(newSlice, elem) - } - } - return newSlice -} - -func WrapWithHyphenI(value string) string { - return "\"-I" + value + "\"" -} - -func TrimSpace(value string) string { - return strings.TrimSpace(value) -} - -type argFilterFunc func(int, string, []string) bool - -func PrepareCommandFilteredArgs(pattern string, filter argFilterFunc, logger i18n.Logger, relativePath string) (*exec.Cmd, error) { - parts, err := ParseCommandLine(pattern, logger) - if err != nil { - return nil, i18n.WrapError(err) - } - command := parts[0] - parts = parts[1:] - var args []string - for idx, part := range parts { - if filter(idx, part, parts) { - // if relativePath is specified, the overall commandline is too long for the platform - // try reducing the length by making the filenames relative - // and changing working directory to build.path - if relativePath != "" { - if _, err := os.Stat(part); !os.IsNotExist(err) { - tmp, err := filepath.Rel(relativePath, part) - if err == nil { - part = tmp - } - } - } - args = append(args, part) - } - } - - cmd := exec.Command(command, args...) - - if relativePath != "" { - cmd.Dir = relativePath - } - - return cmd, nil -} - -func filterEmptyArg(_ int, arg string, _ []string) bool { - return arg != constants.EMPTY_STRING -} - -func PrepareCommand(pattern string, logger i18n.Logger, relativePath string) (*exec.Cmd, error) { - return PrepareCommandFilteredArgs(pattern, filterEmptyArg, logger, relativePath) -} - -func printableArgument(arg string) string { - if strings.ContainsAny(arg, "\"\\ \t") { - arg = strings.Replace(arg, "\\", "\\\\", -1) - arg = strings.Replace(arg, "\"", "\\\"", -1) - return "\"" + arg + "\"" - } else { - return arg - } -} - -// Convert a command and argument slice back to a printable string. -// This adds basic escaping which is sufficient for debug output, but -// probably not for shell interpretation. This essentially reverses -// ParseCommandLine. -func PrintableCommand(parts []string) string { - return strings.Join(Map(parts, printableArgument), " ") -} - -const ( - Ignore = 0 // Redirect to null - Show = 1 // Show on stdout/stderr as normal - ShowIfVerbose = 2 // Show if verbose is set, Ignore otherwise - Capture = 3 // Capture into buffer -) - -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.ExecStderr == nil { - ctx.ExecStderr = os.Stderr - } - - if ctx.Verbose { - ctx.GetLogger().UnformattedFprintln(os.Stdout, PrintableCommand(command.Args)) - } - - if stdout == Capture { - buffer := &bytes.Buffer{} - command.Stdout = buffer - } else if stdout == Show || stdout == ShowIfVerbose && ctx.Verbose { - command.Stdout = ctx.ExecStdout - } - - if stderr == Capture { - buffer := &bytes.Buffer{} - command.Stderr = buffer - } else if stderr == Show || stderr == ShowIfVerbose && ctx.Verbose { - command.Stderr = ctx.ExecStderr - } - - err := command.Start() - if err != nil { - return nil, nil, i18n.WrapError(err) - } - - err = command.Wait() - - var outbytes, errbytes []byte - if buf, ok := command.Stdout.(*bytes.Buffer); ok { - outbytes = buf.Bytes() - } - if buf, ok := command.Stderr.(*bytes.Buffer); ok { - errbytes = buf.Bytes() - } - - return outbytes, errbytes, i18n.WrapError(err) -} - -func AbsolutizePaths(files []string) ([]string, error) { - for idx, file := range files { - if file == "" { - continue - } - absFile, err := filepath.Abs(file) - if err != nil { - return nil, i18n.WrapError(err) - } - files[idx] = absFile - } - - return files, nil -} - -type CheckExtensionFunc func(ext string) bool - -func FindAllSubdirectories(folder string, output *[]string) error { - walkFunc := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - // Skip source control and hidden files and directories - if IsSCCSOrHiddenFile(info) { - if info.IsDir() { - return filepath.SkipDir - } - return nil - } - - // Skip directories unless recurse is on, or this is the - // root directory - if info.IsDir() { - *output = AppendIfNotPresent(*output, path) - } - return nil - } - return gohasissues.Walk(folder, walkFunc) -} - -func FindFilesInFolder(files *[]string, folder string, extensions CheckExtensionFunc, recurse bool) error { - walkFunc := func(path string, info os.FileInfo, err error) error { - if err != nil { - return err - } - - // Skip source control and hidden files and directories - if IsSCCSOrHiddenFile(info) { - if info.IsDir() { - return filepath.SkipDir - } - return nil - } - - // Skip directories unless recurse is on, or this is the - // root directory - if info.IsDir() { - if recurse || path == folder { - return nil - } else { - return filepath.SkipDir - } - } - - // Check (lowercased) extension against list of extensions - if extensions != nil && !extensions(strings.ToLower(filepath.Ext(path))) { - return nil - } - - // See if the file is readable by opening it - currentFile, err := os.Open(path) - if err != nil { - return nil - } - currentFile.Close() - - *files = append(*files, path) - return nil - } - return gohasissues.Walk(folder, walkFunc) -} - -func AppendIfNotPresent(target []string, elements ...string) []string { - for _, element := range elements { - if !SliceContains(target, element) { - target = append(target, element) - } - } - return target -} - -func MD5Sum(data []byte) string { - md5sumBytes := md5.Sum(data) - return hex.EncodeToString(md5sumBytes[:]) -} - -type loggerAction struct { - onlyIfVerbose bool - level string - format string - args []interface{} -} - -func (l *loggerAction) Run(ctx *types.Context) error { - if !l.onlyIfVerbose || ctx.Verbose { - ctx.GetLogger().Println(l.level, l.format, l.args...) - } - return nil -} - -func LogIfVerbose(level string, format string, args ...interface{}) types.Command { - return &loggerAction{true, level, format, args} -} - -// Returns the given string as a quoted string for use with the C -// preprocessor. This adds double quotes around it and escapes any -// double quotes and backslashes in the string. -func QuoteCppString(str string) string { - str = strings.Replace(str, "\\", "\\\\", -1) - str = strings.Replace(str, "\"", "\\\"", -1) - return "\"" + str + "\"" -} - -func QuoteCppPath(path *paths.Path) string { - return QuoteCppString(path.String()) -} - -// Parse a C-preprocessor string as emitted by the preprocessor. This -// is a string contained in double quotes, with any backslashes or -// quotes escaped with a backslash. If a valid string was present at the -// start of the given line, returns the unquoted string contents, the -// remaineder of the line (everything after the closing "), and true. -// Otherwise, returns the empty string, the entire line and false. -func ParseCppString(line string) (string, string, bool) { - // For details about how these strings are output by gcc, see: - // https://github.com/gcc-mirror/gcc/blob/a588355ab948cf551bc9d2b89f18e5ae5140f52c/libcpp/macro.c#L491-L511 - // Note that the documentaiton suggests all non-printable - // characters are also escaped, but the implementation does not - // actually do this. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51259 - if len(line) < 1 || line[0] != '"' { - return "", line, false - } - - i := 1 - res := "" - for { - if i >= len(line) { - return "", line, false - } - - c, width := utf8.DecodeRuneInString(line[i:]) - - switch c { - // Backslash, next character is used unmodified - case '\\': - i += width - if i >= len(line) { - return "", line, false - } - res += string(line[i]) - break - // Quote, end of string - case '"': - return res, line[i+width:], true - default: - res += string(c) - break - } - - i += width - } -} - -func isMn(r rune) bool { - return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks -} - -// Normalizes an UTF8 byte slice -// TODO: use it more often troughout all the project (maybe on logger interface?) -func NormalizeUTF8(buf []byte) []byte { - t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC) - result, _, _ := transform.Bytes(t, buf) - return result -} - -// CopyFile copies the contents of the file named src to the file named -// by dst. The file will be created if it does not already exist. If the -// destination file exists, all it's contents will be replaced by the contents -// of the source file. The file mode will be copied from the source and -// the copied data is synced/flushed to stable storage. -func CopyFile(src, dst string) (err error) { - in, err := os.Open(src) - if err != nil { - return - } - defer in.Close() - - out, err := os.Create(dst) - if err != nil { - return - } - defer func() { - if e := out.Close(); e != nil { - err = e - } - }() - - _, err = io.Copy(out, in) - if err != nil { - return - } - - err = out.Sync() - if err != nil { - return - } - - si, err := os.Stat(src) - if err != nil { - return - } - err = os.Chmod(dst, si.Mode()) - if err != nil { - return - } - - return -} - -// CopyDir recursively copies a directory tree, attempting to preserve permissions. -// Source directory must exist, destination directory must *not* exist. -// Symlinks are ignored and skipped. -func CopyDir(src string, dst string, extensions CheckExtensionFunc) (err error) { - src = filepath.Clean(src) - dst = filepath.Clean(dst) - - si, err := os.Stat(src) - if err != nil { - return err - } - if !si.IsDir() { - return fmt.Errorf("source is not a directory") - } - - _, err = os.Stat(dst) - if err != nil && !os.IsNotExist(err) { - return - } - if err == nil { - return fmt.Errorf("destination already exists") - } - - err = os.MkdirAll(dst, si.Mode()) - if err != nil { - return - } - - entries, err := ioutil.ReadDir(src) - if err != nil { - return - } - - for _, entry := range entries { - srcPath := filepath.Join(src, entry.Name()) - dstPath := filepath.Join(dst, entry.Name()) - - if entry.IsDir() { - err = CopyDir(srcPath, dstPath, extensions) - if err != nil { - return - } - } else { - // Skip symlinks. - if entry.Mode()&os.ModeSymlink != 0 { - continue - } - - if extensions != nil && !extensions(strings.ToLower(filepath.Ext(srcPath))) { - continue - } - - err = CopyFile(srcPath, dstPath) - if err != nil { - return - } - } - } - - return -} diff --git a/warn_about_arch_incompatible_libraries.go b/warn_about_arch_incompatible_libraries.go deleted file mode 100644 index 32b80fd1..00000000 --- a/warn_about_arch_incompatible_libraries.go +++ /dev/null @@ -1,66 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - "strings" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" -) - -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 { - archs = append(archs, strings.Split(overrides, ",")...) - } - - for _, importedLibrary := range ctx.ImportedLibraries { - if !importedLibrary.SupportsAnyArchitectureIn(archs...) { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, constants.MSG_LIBRARY_INCOMPATIBLE_ARCH, - importedLibrary.Name, - strings.Join(importedLibrary.Architectures, ", "), - strings.Join(archs, ", ")) - } - } - - return nil -} diff --git a/warn_about_platform_rewrites.go b/warn_about_platform_rewrites.go deleted file mode 100644 index f6e39810..00000000 --- a/warn_about_platform_rewrites.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "os" - - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/types" - "github.com/arduino/arduino-cli/arduino/cores" -) - -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 - - platforms := []*cores.PlatformRelease{targetPlatform} - if actualPlatform != targetPlatform { - platforms = append(platforms, actualPlatform) - } - - for _, platform := range platforms { - if hardwareRewriteResults[platform] != nil { - for _, rewrite := range hardwareRewriteResults[platform] { - logger.Fprintln(os.Stdout, constants.LOG_LEVEL_WARN, - constants.MSG_WARNING_PLATFORM_OLD_VALUES, - platform.Properties.Get(constants.PLATFORM_NAME), - rewrite.Key+"="+rewrite.OldValue, - rewrite.Key+"="+rewrite.NewValue) - } - } - } - - return nil -} diff --git a/wipeout_build_path_if_build_options_changed.go b/wipeout_build_path_if_build_options_changed.go deleted file mode 100644 index 48c26b9e..00000000 --- a/wipeout_build_path_if_build_options_changed.go +++ /dev/null @@ -1,94 +0,0 @@ -/* - * This file is part of Arduino Builder. - * - * Arduino Builder is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * As a special exception, you may use this file as part of a free software - * library without restriction. Specifically, if other files instantiate - * templates or use macros or inline functions from this file, or you compile - * this file and link it with other files to produce an executable, this - * file does not by itself cause the resulting executable to be covered by - * the GNU General Public License. This exception does not however - * invalidate any other reasons why the executable file might be covered by - * the GNU General Public License. - * - * Copyright 2015 Arduino LLC (http://www.arduino.cc/) - */ - -package builder - -import ( - "encoding/json" - "path/filepath" - - "github.com/arduino/arduino-builder/builder_utils" - "github.com/arduino/arduino-builder/constants" - "github.com/arduino/arduino-builder/gohasissues" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" - properties "github.com/arduino/go-properties-orderedmap" -) - -type WipeoutBuildPathIfBuildOptionsChanged struct{} - -func (s *WipeoutBuildPathIfBuildOptionsChanged) Run(ctx *types.Context) error { - if ctx.BuildOptionsJsonPrevious == "" { - return nil - } - buildOptionsJson := ctx.BuildOptionsJson - previousBuildOptionsJson := ctx.BuildOptionsJsonPrevious - logger := ctx.GetLogger() - - var opts *properties.Map - var prevOpts *properties.Map - json.Unmarshal([]byte(buildOptionsJson), &opts) - json.Unmarshal([]byte(previousBuildOptionsJson), &prevOpts) - - // If SketchLocation path is different but filename is the same, consider it equal - if filepath.Base(opts.Get("sketchLocation")) == filepath.Base(prevOpts.Get("sketchLocation")) { - opts.Remove("sketchLocation") - prevOpts.Remove("sketchLocation") - } - - // If options are not changed check if core has - if opts.Equals(prevOpts) { - // check if any of the files contained in the core folders has changed - // since the json was generated - like platform.txt or similar - // if so, trigger a "safety" wipe - buildProperties := ctx.BuildProperties - targetCoreFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_RUNTIME_PLATFORM_PATH) - coreFolder := buildProperties.GetPath(constants.BUILD_PROPERTIES_BUILD_CORE_PATH) - realCoreFolder := coreFolder.Parent().Parent() - jsonPath := ctx.BuildPath.Join(constants.BUILD_OPTIONS_FILE) - coreHasChanged := builder_utils.TXTBuildRulesHaveChanged(realCoreFolder, targetCoreFolder, jsonPath) - - if !coreHasChanged { - return nil - } - } - - logger.Println(constants.LOG_LEVEL_INFO, constants.MSG_BUILD_OPTIONS_CHANGED) - - buildPath := ctx.BuildPath - files, err := gohasissues.ReadDir(buildPath.String()) - if err != nil { - return i18n.WrapError(err) - } - for _, file := range files { - buildPath.Join(file.Name()).RemoveAll() - } - - return nil -} From 6c01fcc0fa08938dbee0d37bff52432b074db888 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 May 2019 10:26:16 +0200 Subject: [PATCH 54/57] Fixed imports --- main.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index d074f397..53aceb57 100644 --- a/main.go +++ b/main.go @@ -43,11 +43,11 @@ import ( "strings" "syscall" - builder "github.com/arduino/arduino-builder" - "github.com/arduino/arduino-builder/gohasissues" - jsonrpc "github.com/arduino/arduino-builder/grpc" - "github.com/arduino/arduino-builder/i18n" - "github.com/arduino/arduino-builder/types" + "github.com/arduino/arduino-cli/legacy/builder" + "github.com/arduino/arduino-cli/legacy/builder/gohasissues" + jsonrpc "github.com/arduino/arduino-cli/legacy/builder/grpc" + "github.com/arduino/arduino-cli/legacy/builder/i18n" + "github.com/arduino/arduino-cli/legacy/builder/types" "github.com/arduino/arduino-cli/arduino/cores" paths "github.com/arduino/go-paths-helper" properties "github.com/arduino/go-properties-orderedmap" From d64e8c78c4b8d2e006d3a4d9306e1fe1c1e2ffc3 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 31 May 2019 11:23:25 +0200 Subject: [PATCH 55/57] Added go.mod --- .travis.yml | 35 +++---------- go.mod | 11 ++++ go.sum | 147 ++++++++++++++++++++++++++++++++++++++++++++++++++++ main.go | 2 +- 4 files changed, 165 insertions(+), 30 deletions(-) create mode 100644 go.mod create mode 100644 go.sum diff --git a/.travis.yml b/.travis.yml index 61733890..d19ffca0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,36 +5,13 @@ os: - osx go: - - 1.11.x + - 1.12.x -install: - - go get github.com/go-errors/errors - - go get github.com/stretchr/testify - - go get github.com/jstemmer/go-junit-report - - go get github.com/arduino/go-paths-helper - - go get github.com/arduino/go-properties-orderedmap - - go get github.com/arduino/go-timeutils - - go get google.golang.org/grpc - - go get github.com/golang/protobuf/proto - - go get golang.org/x/net/context - - go get github.com/fsnotify/fsnotify - - go get github.com/arduino/arduino-cli - - go get golang.org/x/tools/cmd/cover - - go get github.com/mattn/goveralls - - go get github.com/wadey/gocovmerge +env: + - GO111MODULE=on -script: - - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-paths-helper - - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-properties-orderedmap - - rm -r $GOPATH/src/github.com/arduino/arduino-cli/vendor/github.com/arduino/go-timeutils - - go build -o $HOME/arduino-builder -v github.com/arduino/arduino-builder/arduino-builder - - export TEST_PACKAGES=`go list github.com/arduino/arduino-builder/...` - - RES=0; I=0; for PKG in $TEST_PACKAGES; do go test -v -timeout 30m -covermode=count -coverprofile=coverage.$I.out $PKG; ((RES=RES+$?)); ((I++)); done; ( exit $RES ) +install: true -after_success: - - $GOPATH/bin/gocovmerge coverage.*.out > coverage.out - - $GOPATH/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken $COVERALLS_TOKEN +script: + - go build -env: - global: - secure: mm7X+dFQD4tUYwXxeVOJzereC04KdpTe6vrho1g6zmWgnMEqBe/gnX16Hv1LeQRzTnMVUxpcTXMkh4Nj16WL2IFAnizWiiMfFb6wUBBOM0dFhYJR7EzSzKMu7/CuhxIqT5ps/Ls3UUnpzUoI9ImygiLJCaNJCSjJxQ+hwnxyyEZD0FHvlQQcv3kiKAd8sg9oWKqTSBGIwBnn9ZGT9G2uykv+XU2B5B+dW9IoXaDR3SfUGlANldorD4T6S9QNs+JdwhX1NDDd7rOqF92qu2RA0TFf2Ljy1STimLXvVhGgcfetsUhVgkmDGKxp1/iax4jlJ8wRU7faqeFAt1WvJpBaOnsK8OcsNqf7iqmYxWxHKavFHfGKgc7L+dMP9gWIqgtzmfqG94/49IN8lPMpB29J8sfZfrb4nKNu66S9GqQCr/jgGD1uTXzC6SggoL6ro2di0bAvAlb6zgpv5zChqKkTzhHE/6rVA6EZG/JIIx5lXaDvkD+yp3o2LNKNknpwRPEY0KpReRivvajucDwiPqQD79gkKWOGtoo5034SGSGCUmXvAydJNVPJt6c5ADKpVgyiT065Gja4/n+n4GhjT6QKc2WRGQRQZGtkYkNh95tKUvgZiZ1G7+EAuRCotoKiqLPkLgUpzCoD7kZpo/Ai5xU2aRcKpMsAHEHSRP9F06F+zp4= diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..9fad4b33 --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +module github.com/arduino/arduino-builder + +go 1.12 + +require ( + github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f + github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 + github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 + github.com/go-errors/errors v1.0.1 + github.com/juju/errors v0.0.0-20190207033735-e65537c515d7 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..d3c0ea8e --- /dev/null +++ b/go.sum @@ -0,0 +1,147 @@ +bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f h1:rQbnOvfmy84Bsb1+d3UuLK6aL1qGlJx74qShTn6DxAI= +github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f/go.mod h1:2CSFNWBo2zdqv6tafP/U/2zH/JQadKTigXP5KH49Lfo= +github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c/go.mod h1:HK7SpkEax/3P+0w78iRQx1sz1vCDYYw9RXwHjQTB5i8= +github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 h1:S0NpDSqjlkNA510vmRCP5Cq9mPgu3rWDSdeN4SI1Mwc= +github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1/go.mod h1:OGL+FS3aTrS01YsBAJJhkGuxtEGsFRSgZYo8b3vefdc= +github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 h1:aWZoiBr2fCXtZzY4e/TOyQHEFyFpsF9eph7rEDZRv0Y= +github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3/go.mod h1:kiSuHm7yz3chiy8rb2MphC7ECn3MlkQFAIe4SXmQg6o= +github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b h1:9hDi4F2st6dbLC3y4i02zFT5quS4X6iioWifGlVwfy4= +github.com/arduino/go-timeutils v0.0.0-20171220113728-d1dd9e313b1b/go.mod h1:uwGy5PpN4lqW97FiLnbcx+xx8jly5YuPMJWfVwwjJiQ= +github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b h1:3PjgYG5gVPA7cipp7vIR2lF96KkEJIFBJ+ANnuv6J20= +github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b/go.mod h1:iIPnclBMYm1g32Q5kXoqng4jLhMStReIP7ZxaoUC2y8= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cmaglie/pb v1.0.27/go.mod h1:GilkKZMXYjBA4NxItWFfO+lwkp59PLHQ+IOW/b/kmZI= +github.com/codeclysm/cc v1.2.2/go.mod h1:XtW4ArCNgQwFphcRGG9+sPX5WM1J6/u0gMy5ZdV3obA= +github.com/codeclysm/extract v2.2.0+incompatible h1:q3wyckoA30bhUSiwdQezMqVhwd8+WGE64/GL//LtUhI= +github.com/codeclysm/extract v2.2.0+incompatible/go.mod h1:2nhFMPHiU9At61hz+12bfrlpXSUrOnK+wR+KlGO4Uks= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/goselect v0.0.0-20180328191401-176c667f75aa/go.mod h1:gHrIcH/9UZDn2qgeTUeW5K9eZsVYCH6/60J/FHysWyE= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fluxio/iohelpers v0.0.0-20160419043813-3a4dd67a94d2/go.mod h1:c7sGIpDbBo0JZZ1tKyC1p5smWf8QcUjK4bFtZjHAecg= +github.com/fluxio/multierror v0.0.0-20160419044231-9c68d39025e5/go.mod h1:BEUDl7FG1cc76sM0J0x8dqr6RhiL4uqvk6oFkwuNyuM= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gosuri/uitable v0.0.0-20160404203958-36ee7e946282/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= +github.com/h2non/filetype v1.0.8 h1:le8gpf+FQA0/DlDABbtisA1KiTS0Xi+YSC/E8yY3Y14= +github.com/h2non/filetype v1.0.8/go.mod h1:isekKqOuhMj+s/7r3rIeTErIRy4Rub5uBWHfvMusLMU= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/juju/errors v0.0.0-20181118221551-089d3ea4e4d5/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/errors v0.0.0-20190207033735-e65537c515d7 h1:dMIPRDg6gi7CUp0Kj2+HxqJ5kTr1iAdzsXYIrLCNSmU= +github.com/juju/errors v0.0.0-20190207033735-e65537c515d7/go.mod h1:W54LbzXuIE0boCoNJfwqpmkKJ1O4TCTZMetAt6jGk7Q= +github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8 h1:UUHMLvzt/31azWTN/ifGWef4WUqvXk0iRqdhdy/2uzI= +github.com/juju/loggo v0.0.0-20190526231331-6e530bcce5d8/go.mod h1:vgyd7OREkbtVEN/8IXZe5Ooef3LQePvuBm9UWj6ZL8U= +github.com/juju/testing v0.0.0-20190429233213-dfc56b8c09fc h1:5xUWujf6ES9tEpFHFzI34vcHm8U07lGjxAuJML3qwqM= +github.com/juju/testing v0.0.0-20190429233213-dfc56b8c09fc/go.mod h1:63prj8cnj0tU0S9OHjGJn+b1h0ZghCndfnbQolrYTwA= +github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/miekg/dns v1.0.5/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/oleksandr/bonjour v0.0.0-20160508152359-5dcf00d8b228/go.mod h1:MGuVJ1+5TX1SCoO2Sx0eAnjpdRytYla2uC1YIZfkC9c= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583 h1:ogHi8YLNeIxABOaH6UgtbwkODheuAK+ErP8gWXYQVj0= +github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583/go.mod h1:sFPiU/UgDcsQVu3vkqpZLCXWFwUoQRpHGu9ATihPAl0= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk= +github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +go.bug.st/cleanup v1.0.0 h1:XVj1HZxkBXeq3gMT7ijWUpHyIC1j8XAoNSyQ06CskgA= +go.bug.st/cleanup v1.0.0/go.mod h1:EqVmTg2IBk4znLbPD28xne3abjsJftMdqqJEjhn70bk= +go.bug.st/downloader v1.1.0 h1:LipC9rqRCe8kwa+ah3ZDfCqneVaf34cB/TKjXZiZt54= +go.bug.st/downloader v1.1.0/go.mod h1:l+RPbNbrTB+MoAIp8nrZsP22nRPDy26XJZQqmm4gNT4= +go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852 h1:NimumSJtLf9QOiV8/LKi0IelbgbaSUGK/NTfKXc/gU8= +go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852/go.mod h1:WWVH9tve4kargu9fsX18qW/UHxE37QcgPXRtE/xSvxY= +go.bug.st/serial.v1 v0.0.0-20180827123349-5f7892a7bb45/go.mod h1:dRSl/CVCTf56CkXgJMDOdSwNfo2g1orOGE/gBGdvjZw= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a h1:oWX7TPOiFAMXLq8o0ikBYfCJVlRHBcsciT5bXOrH628= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d h1:XB2jc5XQ9uhizGTS2vWcN01bc4dI6z3C4KY5MQm8SS8= +google.golang.org/genproto v0.0.0-20190327125643-d831d65fe17d/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.21.1 h1:j6XxA85m/6txkUCHvzlV5f+HBNl/1r5cZ2A/3IEFOO8= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce h1:xcEWjVhvbDy+nHP67nPDDpbYrY+ILlfndk4bRioVHaU= +gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/main.go b/main.go index 53aceb57..4913bc73 100644 --- a/main.go +++ b/main.go @@ -43,12 +43,12 @@ import ( "strings" "syscall" + "github.com/arduino/arduino-cli/arduino/cores" "github.com/arduino/arduino-cli/legacy/builder" "github.com/arduino/arduino-cli/legacy/builder/gohasissues" jsonrpc "github.com/arduino/arduino-cli/legacy/builder/grpc" "github.com/arduino/arduino-cli/legacy/builder/i18n" "github.com/arduino/arduino-cli/legacy/builder/types" - "github.com/arduino/arduino-cli/arduino/cores" paths "github.com/arduino/go-paths-helper" properties "github.com/arduino/go-properties-orderedmap" "github.com/go-errors/errors" From 35e015ff7e8545db0fa33c7ce050f45a9cbcc579 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 27 Aug 2019 12:04:17 +0200 Subject: [PATCH 56/57] Set correct verbosity on logrus module --- go.mod | 1 + main.go | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/go.mod b/go.mod index 9fad4b33..065a89c1 100644 --- a/go.mod +++ b/go.mod @@ -8,4 +8,5 @@ require ( github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 github.com/go-errors/errors v1.0.1 github.com/juju/errors v0.0.0-20190207033735-e65537c515d7 // indirect + github.com/sirupsen/logrus v1.4.2 ) diff --git a/main.go b/main.go index 2e2fa073..2b7dba33 100644 --- a/main.go +++ b/main.go @@ -52,6 +52,7 @@ import ( paths "github.com/arduino/go-paths-helper" properties "github.com/arduino/go-properties-orderedmap" "github.com/go-errors/errors" + "github.com/sirupsen/logrus" ) const VERSION = "1.4.5" @@ -373,6 +374,9 @@ func main() { if *debugLevelFlag > -1 { ctx.DebugLevel = *debugLevelFlag } + if ctx.DebugLevel < 10 { + logrus.SetOutput(ioutil.Discard) + } if *quietFlag { ctx.SetLogger(i18n.NoopLogger{}) From 7568a1726acfa2b3378138f7985b8a96a0e327c0 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Tue, 27 Aug 2019 12:05:03 +0200 Subject: [PATCH 57/57] Update arduino-cli deps --- go.mod | 2 +- go.sum | 26 ++++++++++++++++++++++---- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/go.mod b/go.mod index 065a89c1..7e464b40 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/arduino/arduino-builder go 1.12 require ( - github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f + github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366 github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 github.com/arduino/go-properties-orderedmap v0.0.0-20181003091528-89278049acd3 github.com/go-errors/errors v1.0.1 diff --git a/go.sum b/go.sum index d3c0ea8e..074ef4a0 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,9 @@ bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= -github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f h1:rQbnOvfmy84Bsb1+d3UuLK6aL1qGlJx74qShTn6DxAI= -github.com/arduino/arduino-cli v0.0.0-20190710073039-d06244211d3f/go.mod h1:2CSFNWBo2zdqv6tafP/U/2zH/JQadKTigXP5KH49Lfo= +github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366 h1:W7aS1f8JsCCLvHzj4UiSzYIdbRnIK1Hu/fHXKmvbaCI= +github.com/arduino/arduino-cli v0.0.0-20190826144620-ce6c1878d366/go.mod h1:XFDg7LwMgVGiJAkVLQ0AM3Gei5LjfuDIKwOcrU9rnsI= +github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c h1:agh2JT96G8egU7FEb13L4dq3fnCN7lxXhJ86t69+W7s= github.com/arduino/board-discovery v0.0.0-20180823133458-1ba29327fb0c/go.mod h1:HK7SpkEax/3P+0w78iRQx1sz1vCDYYw9RXwHjQTB5i8= github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1 h1:S0NpDSqjlkNA510vmRCP5Cq9mPgu3rWDSdeN4SI1Mwc= github.com/arduino/go-paths-helper v0.0.0-20190214132331-c3c98d1bf2e1/go.mod h1:OGL+FS3aTrS01YsBAJJhkGuxtEGsFRSgZYo8b3vefdc= @@ -14,20 +15,27 @@ github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b h1:3PjgYG5g github.com/arduino/go-win32-utils v0.0.0-20180330194947-ed041402e83b/go.mod h1:iIPnclBMYm1g32Q5kXoqng4jLhMStReIP7ZxaoUC2y8= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cmaglie/pb v1.0.27 h1:ynGj8vBXR+dtj4B7Q/W/qGt31771Ux5iFfRQBnwdQiA= github.com/cmaglie/pb v1.0.27/go.mod h1:GilkKZMXYjBA4NxItWFfO+lwkp59PLHQ+IOW/b/kmZI= +github.com/codeclysm/cc v1.2.2 h1:1ChS4EvWTjw6bH2sd6QiMcmih0itVVrWdh9MmOliX/I= github.com/codeclysm/cc v1.2.2/go.mod h1:XtW4ArCNgQwFphcRGG9+sPX5WM1J6/u0gMy5ZdV3obA= github.com/codeclysm/extract v2.2.0+incompatible h1:q3wyckoA30bhUSiwdQezMqVhwd8+WGE64/GL//LtUhI= github.com/codeclysm/extract v2.2.0+incompatible/go.mod h1:2nhFMPHiU9At61hz+12bfrlpXSUrOnK+wR+KlGO4Uks= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/cpuguy83/go-md2man v1.0.10 h1:BSKMNlYxDvnunlTymqtgONjNnaRV1sTpcovwwjF22jk= github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/creack/goselect v0.0.0-20180328191401-176c667f75aa h1:tIUhmTixVssck4oJ9jKcqaNOF8ua4YxN3UHP0ymBHuQ= github.com/creack/goselect v0.0.0-20180328191401-176c667f75aa/go.mod h1:gHrIcH/9UZDn2qgeTUeW5K9eZsVYCH6/60J/FHysWyE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fluxio/iohelpers v0.0.0-20160419043813-3a4dd67a94d2 h1:C6sOwknxwWfLBEQ91zhmptlfxf7pVEs5s6wOnDxNpS4= github.com/fluxio/iohelpers v0.0.0-20160419043813-3a4dd67a94d2/go.mod h1:c7sGIpDbBo0JZZ1tKyC1p5smWf8QcUjK4bFtZjHAecg= +github.com/fluxio/multierror v0.0.0-20160419044231-9c68d39025e5 h1:R8jFW6G/bjoXjWPFrEfw9G5YQDlYhwV4AC+Eonu6wmk= github.com/fluxio/multierror v0.0.0-20160419044231-9c68d39025e5/go.mod h1:BEUDl7FG1cc76sM0J0x8dqr6RhiL4uqvk6oFkwuNyuM= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= @@ -37,10 +45,11 @@ github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekf github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= -github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gosuri/uitable v0.0.0-20160404203958-36ee7e946282 h1:KFqmdzEPbU7Uck2tn50t+HQXZNVkxe8M9qRb/ZoSHaE= github.com/gosuri/uitable v0.0.0-20160404203958-36ee7e946282/go.mod h1:tKR86bXuXPZazfOTG1FIzvjIdXzd0mo4Vtn16vt0PJo= github.com/h2non/filetype v1.0.8 h1:le8gpf+FQA0/DlDABbtisA1KiTS0Xi+YSC/E8yY3Y14= github.com/h2non/filetype v1.0.8/go.mod h1:isekKqOuhMj+s/7r3rIeTErIRy4Rub5uBWHfvMusLMU= @@ -57,13 +66,18 @@ github.com/juju/testing v0.0.0-20190429233213-dfc56b8c09fc/go.mod h1:63prj8cnj0t github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU= github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= +github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE= github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-runewidth v0.0.2 h1:UnlwIPBGaTZfPQ6T1IGzPI0EkYAQmT9fAEJ/poFC63o= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/miekg/dns v1.0.5 h1:MQBGf2JEJDu0rg9WOpQZzeO+zW8UKwgkvP3R1dUU1Yw= github.com/miekg/dns v1.0.5/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/oleksandr/bonjour v0.0.0-20160508152359-5dcf00d8b228 h1:Cvfd2dOlXIPTeEkOT/h8PyK4phBngOM4at9/jlgy7d4= github.com/oleksandr/bonjour v0.0.0-20160508152359-5dcf00d8b228/go.mod h1:MGuVJ1+5TX1SCoO2Sx0eAnjpdRytYla2uC1YIZfkC9c= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= @@ -72,6 +86,7 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583 h1:ogHi8YLNeIxABOaH6UgtbwkODheuAK+ErP8gWXYQVj0= github.com/pmylund/sortutil v0.0.0-20120526081524-abeda66eb583/go.mod h1:sFPiU/UgDcsQVu3vkqpZLCXWFwUoQRpHGu9ATihPAl0= +github.com/russross/blackfriday v1.5.2 h1:HyvC0ARfnZBqnXwABFeSZHpKvJHJJfPz81GNueLj0oo= github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk= github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g= @@ -83,8 +98,10 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1 github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s= github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -100,6 +117,7 @@ go.bug.st/downloader v1.1.0 h1:LipC9rqRCe8kwa+ah3ZDfCqneVaf34cB/TKjXZiZt54= go.bug.st/downloader v1.1.0/go.mod h1:l+RPbNbrTB+MoAIp8nrZsP22nRPDy26XJZQqmm4gNT4= go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852 h1:NimumSJtLf9QOiV8/LKi0IelbgbaSUGK/NTfKXc/gU8= go.bug.st/relaxed-semver v0.0.0-20181022103824-0265409c5852/go.mod h1:WWVH9tve4kargu9fsX18qW/UHxE37QcgPXRtE/xSvxY= +go.bug.st/serial.v1 v0.0.0-20180827123349-5f7892a7bb45 h1:mACY1anK6HNCZtm/DK2Rf2ZPHggVqeB0+7rY9Gl6wyI= go.bug.st/serial.v1 v0.0.0-20180827123349-5f7892a7bb45/go.mod h1:dRSl/CVCTf56CkXgJMDOdSwNfo2g1orOGE/gBGdvjZw= golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=