From ca1455796fbb1e09325b4ad910b197a91935dc6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oliv=C3=A9r=20Falvai?= Date: Tue, 9 Nov 2021 11:55:44 +0100 Subject: [PATCH] Respect additional Gradle flags in every Gradle call (#33) * Respect additional Gradle flags in every Gradle call * Fix import * Commit missing vendor file --- .gitignore | 3 +- bitrise.yml | 1 + go.mod | 6 +- go.sum | 14 + main.go | 71 ++--- .../bitrise-io/go-android/cache/cache.go | 52 ++-- .../bitrise-io/go-android/cache/gradle.go | 6 +- .../bitrise-io/go-android/gradle/artifact.go | 0 .../bitrise-io/go-android/gradle/common.go | 11 +- .../bitrise-io/go-android/gradle/project.go | 12 +- .../bitrise-io/go-android/gradle/task.go | 22 +- .../bitrise-io/go-android/gradle/variant.go | 0 .../bitrise-io/go-steputils/tools/tools.go | 10 +- .../bitrise-io/go-utils/command/command.go | 270 +++++------------- .../bitrise-io/go-utils/command/file.go | 5 +- .../github.com/bitrise-io/go-utils/env/env.go | 58 ++++ .../bitrise-io/go-utils/fileutil/fileutil.go | 46 +++ .../bitrise-io/go-utils/log/defaultlogger.go | 57 ---- .../bitrise-io/go-utils/log/dummylogger.go | 30 -- .../bitrise-io/go-utils/log/json_logger.go | 33 --- .../github.com/bitrise-io/go-utils/log/log.go | 236 ++++++++++++++- .../bitrise-io/go-utils/log/logger.go | 12 - .../bitrise-io/go-utils/log/print.go | 115 -------- .../bitrise-io/go-utils/log/raw_logger.go | 33 --- .../bitrise-io/go-utils/log/severity.go | 26 +- .../bitrise-io/go-utils/pathutil/glob.go | 13 - .../go-utils/pathutil/path_filter.go | 21 ++ .../bitrise-io/go-utils/pathutil/pathutil.go | 219 +++++++------- .../go-utils/pathutil/sortable_path.go | 31 ++ .../bitrise-io/go-utils/ziputil/ziputil.go | 14 +- vendor/modules.txt | 7 +- 31 files changed, 716 insertions(+), 718 deletions(-) mode change 100755 => 100644 vendor/github.com/bitrise-io/go-android/gradle/artifact.go mode change 100755 => 100644 vendor/github.com/bitrise-io/go-android/gradle/common.go mode change 100755 => 100644 vendor/github.com/bitrise-io/go-android/gradle/project.go mode change 100755 => 100644 vendor/github.com/bitrise-io/go-android/gradle/task.go mode change 100755 => 100644 vendor/github.com/bitrise-io/go-android/gradle/variant.go create mode 100644 vendor/github.com/bitrise-io/go-utils/env/env.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/defaultlogger.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/dummylogger.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/json_logger.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/logger.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/print.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/log/raw_logger.go delete mode 100644 vendor/github.com/bitrise-io/go-utils/pathutil/glob.go diff --git a/.gitignore b/.gitignore index 84324f6..cd502ee 100755 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ .bitrise* -_tmp \ No newline at end of file +_tmp +.idea/ \ No newline at end of file diff --git a/bitrise.yml b/bitrise.yml index 0d5447c..c040d2c 100755 --- a/bitrise.yml +++ b/bitrise.yml @@ -46,6 +46,7 @@ workflows: title: Android Unit Test (monorepo projects in source dir) inputs: - is_debug: "true" + - arguments: --warn after-run: - check-artifacts diff --git a/go.mod b/go.mod index ce07c38..1ac5134 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,8 @@ module github.com/bitrise-steplib/bitrise-step-android-unit-test go 1.16 require ( - github.com/bitrise-io/go-android v0.0.0-20210527143215-3ad22ad02e2e - github.com/bitrise-io/go-steputils v0.0.0-20210527075147-910ce7a105a1 - github.com/bitrise-io/go-utils v0.0.0-20210520073355-367fa34178f5 + github.com/bitrise-io/go-android v0.0.0-20211022134605-85247bb2c5c6 + github.com/bitrise-io/go-steputils v0.0.0-20210819160244-b3962254d553 + github.com/bitrise-io/go-utils v0.0.0-20211008161027-fa11986847a0 github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 ) diff --git a/go.sum b/go.sum index b200bd2..ba38063 100644 --- a/go.sum +++ b/go.sum @@ -1,17 +1,27 @@ github.com/bitrise-io/go-android v0.0.0-20210527143215-3ad22ad02e2e h1:lkJnz+yXbIqFGpDTdRBBshqxeX0UCndJmEOp0yy2GRQ= github.com/bitrise-io/go-android v0.0.0-20210527143215-3ad22ad02e2e/go.mod h1:gGXmY8hJ1x44AC98TIvZZvxP7o+hs4VI6wgmO4JMfEg= +github.com/bitrise-io/go-android v0.0.0-20211022134605-85247bb2c5c6 h1:WJQ7dvHP7/ZtS9qw/Ng+/eh+5MPOVVKDrjjrDNiWlwA= +github.com/bitrise-io/go-android v0.0.0-20211022134605-85247bb2c5c6/go.mod h1:yTe4i6RfahvAmOChFrS9uCPmJiH0eBEV4jya30v2tTc= github.com/bitrise-io/go-steputils v0.0.0-20210514150206-5b6261447e77/go.mod h1:H0iZjgsAR5NA6pnlD/zKB6AbxEsskq55pwJ9klVmP8w= github.com/bitrise-io/go-steputils v0.0.0-20210527075147-910ce7a105a1 h1:gi29hTdxGXAGQvZckPZ9V8BAEfP3eK/tiZgTC5s6h1c= github.com/bitrise-io/go-steputils v0.0.0-20210527075147-910ce7a105a1/go.mod h1:H0iZjgsAR5NA6pnlD/zKB6AbxEsskq55pwJ9klVmP8w= +github.com/bitrise-io/go-steputils v0.0.0-20210819160244-b3962254d553 h1:W8LE5et6SN8pHIKJ3+oy6IHWzLVwL55nCAN05vDkwQo= +github.com/bitrise-io/go-steputils v0.0.0-20210819160244-b3962254d553/go.mod h1:gPr5wQVOi3wZCY1RkMzk/Ij0rmdgEIP0Og84YgHmVSU= github.com/bitrise-io/go-utils v0.0.0-20210507100250-37de47dfa6ce/go.mod h1:15EZZf02noI5nWFqXMZEoyb1CyqYRXTMz5Fyu4CWFzI= github.com/bitrise-io/go-utils v0.0.0-20210520073355-367fa34178f5 h1:kclxBfygfNK6kWUB+9xcsfPLBen8Us9gubhitfL/Z6c= github.com/bitrise-io/go-utils v0.0.0-20210520073355-367fa34178f5/go.mod h1:DRx7oFuAqk0dbKpAKCqWl0TgrowfJUb/MqYPRscxJOQ= +github.com/bitrise-io/go-utils v0.0.0-20210819105546-07a5bda18d68/go.mod h1:UprBoSn6HxcN9G7yGRSOoe9bSZLh7gLl4yA0/iqwYsI= +github.com/bitrise-io/go-utils v0.0.0-20210819143908-bbd923881fab h1:G9dwybvZJ8k2F55ntjQq/nZsZ6+nqvTzwIDjVLzpueA= +github.com/bitrise-io/go-utils v0.0.0-20210819143908-bbd923881fab/go.mod h1:UprBoSn6HxcN9G7yGRSOoe9bSZLh7gLl4yA0/iqwYsI= +github.com/bitrise-io/go-utils v0.0.0-20211008161027-fa11986847a0 h1:fT81H9m8GHazqZ0WsVq7GE5DfK4xSyXnHGJKyita2BM= +github.com/bitrise-io/go-utils v0.0.0-20211008161027-fa11986847a0/go.mod h1:Vi4MHnaZVL3PVoPPA/Yp6g2pzntkDH8LGiRSY7qw6KQ= 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/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ= github.com/hashicorp/go-retryablehttp v0.6.6/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= +github.com/hashicorp/go-retryablehttp v0.7.0/go.mod h1:vAew36LZh98gCBJNLH42IQ1ER/9wtLZZ8meHqQvEYWY= github.com/hashicorp/go-version v1.3.0 h1:McDWVJIU/y+u1BRV06dPaLfLCaT7fUTJLp5r04x7iNw= github.com/hashicorp/go-version v1.3.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= @@ -30,6 +40,7 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8= +golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -37,8 +48,11 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200219091948-cb0a6d8edb6c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210511113859-b0526f3d8744/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210819072135-bce67f096156/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210503060354-a79de5458b56/go.mod h1:tfny5GFUkzUvx4ps4ajbZsCe5lw1metzhBm9T3x7oIY= +golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/main.go b/main.go index a2c92ba..38f49d4 100755 --- a/main.go +++ b/main.go @@ -12,11 +12,13 @@ import ( "github.com/bitrise-io/go-android/gradle" utilscache "github.com/bitrise-io/go-steputils/cache" "github.com/bitrise-io/go-steputils/stepconf" + "github.com/bitrise-io/go-utils/command" + "github.com/bitrise-io/go-utils/env" "github.com/bitrise-io/go-utils/log" "github.com/bitrise-io/go-utils/pathutil" "github.com/bitrise-io/go-utils/sliceutil" "github.com/bitrise-steplib/bitrise-step-android-unit-test/testaddon" - shellquote "github.com/kballard/go-shellquote" + "github.com/kballard/go-shellquote" ) // Configs ... @@ -34,8 +36,11 @@ type Configs struct { TestResultDir string `env:"BITRISE_TEST_RESULT_DIR"` } +var cmdFactory = command.NewFactory(env.NewRepository()) +var logger = log.NewLogger() + func failf(f string, args ...interface{}) { - log.Errorf(f, args...) + logger.Errorf(f, args...) os.Exit(1) } @@ -51,13 +56,13 @@ func getArtifacts(gradleProject gradle.Project, started time.Time, pattern strin } if len(artifacts) == 0 { if t == started { - log.Warnf("No artifacts found with pattern: %s that has modification time after: %s", pattern, t) - log.Warnf("Retrying without modtime check....") + logger.Warnf("No artifacts found with pattern: %s that has modification time after: %s", pattern, t) + logger.Warnf("Retrying without modtime check....") fmt.Println() continue } - log.Warnf("No artifacts found with pattern: %s without modtime check", pattern) - log.Warnf("If you have changed default report export path in your gradle files then you might need to change ReportPathPattern accordingly.") + logger.Warnf("No artifacts found with pattern: %s without modtime check", pattern) + logger.Warnf("If you have changed default report export path in your gradle files then you might need to change ReportPathPattern accordingly.") } } return @@ -89,10 +94,10 @@ func exportArtifacts(deployDir string, artifacts []gradle.Artifact) error { src = "./" + rel } - log.Printf(" Export [ %s => $BITRISE_DEPLOY_DIR/%s ]", src, artifact.Name) + logger.Printf(" Export [ %s => $BITRISE_DEPLOY_DIR/%s ]", src, artifact.Name) if err := artifact.ExportZIP(deployDir); err != nil { - log.Warnf("failed to export artifact (%s), error: %v", artifact.Path, err) + logger.Warnf("failed to export artifact (%s), error: %v", artifact.Path, err) continue } } @@ -139,13 +144,13 @@ func tryExportTestAddonArtifact(artifactPth, outputDir string, lastOtherDirIdx i } if err := testaddon.ExportArtifact(artifactPth, outputDir, dir); err != nil { - log.Warnf("Failed to export test results for test addon: %s", err) + logger.Warnf("Failed to export test results for test addon: %s", err) } else { src := artifactPth if rel, err := workDirRel(artifactPth); err == nil { src = "./" + rel } - log.Printf(" Export [%s => %s]", src, filepath.Join("$BITRISE_TEST_RESULT_DIR", dir, filepath.Base(artifactPth))) + logger.Printf(" Export [%s => %s]", src, filepath.Join("$BITRISE_TEST_RESULT_DIR", dir, filepath.Base(artifactPth))) } return lastOtherDirIdx } @@ -160,19 +165,24 @@ func main() { stepconf.Print(config) fmt.Println() - log.SetEnableDebugLog(config.IsDebug) + logger.EnableDebugLog(config.IsDebug) - gradleProject, err := gradle.NewProject(config.ProjectLocation) + gradleProject, err := gradle.NewProject(config.ProjectLocation, cmdFactory) if err != nil { failf("Failed to open project, error: %s", err) } testTask := gradleProject.GetTask("test") - log.Infof("Variants:") + args, err := shellquote.Split(config.Arguments) + if err != nil { + failf("Failed to parse arguments, error: %s", err) + } + + logger.Infof("Variants:") fmt.Println() - variants, err := testTask.GetVariants() + variants, err := testTask.GetVariants(args...) if err != nil { failf("Failed to fetch variants, error: %s", err) } @@ -183,12 +193,12 @@ func main() { } for module, variants := range variants { - log.Printf("%s:", module) + logger.Printf("%s:", module) for _, variant := range variants { if sliceutil.IsStringInSlice(variant, filteredVariants[module]) { - log.Donef("✓ %s", strings.TrimSuffix(variant, "UnitTest")) + logger.Donef("✓ %s", strings.TrimSuffix(variant, "UnitTest")) } else { - log.Printf("- %s", strings.TrimSuffix(variant, "UnitTest")) + logger.Printf("- %s", strings.TrimSuffix(variant, "UnitTest")) } } } @@ -196,26 +206,21 @@ func main() { started := time.Now() - args, err := shellquote.Split(config.Arguments) - if err != nil { - failf("Failed to parse arguments, error: %s", err) - } - var testErr error - log.Infof("Run test:") + logger.Infof("Run test:") testCommand := testTask.GetCommand(filteredVariants, args...) fmt.Println() - log.Donef("$ " + testCommand.PrintableCommandArgs()) + logger.Donef("$ " + testCommand.PrintableCommandArgs()) fmt.Println() testErr = testCommand.Run() if testErr != nil { - log.Errorf("Test task failed, error: %v", testErr) + logger.Errorf("Test task failed, error: %v", testErr) } fmt.Println() - log.Infof("Export HTML results:") + logger.Infof("Export HTML results:") fmt.Println() reports, err := getArtifacts(gradleProject, started, config.HTMLResultDirPattern, true, true) @@ -228,7 +233,7 @@ func main() { } fmt.Println() - log.Infof("Export XML results:") + logger.Infof("Export XML results:") fmt.Println() results, err := getArtifacts(gradleProject, started, config.XMLResultDirPattern, true, true) @@ -243,7 +248,7 @@ func main() { if config.TestResultDir != "" { // Test Addon is turned on fmt.Println() - log.Infof("Export XML results for test addon:") + logger.Infof("Export XML results for test addon:") fmt.Println() xmlResultFilePattern := config.XMLResultDirPattern @@ -253,7 +258,7 @@ func main() { resultXMLs, err := getArtifacts(gradleProject, started, xmlResultFilePattern, false, false) if err != nil { - log.Warnf("Failed to find test XML test results, error: %s", err) + logger.Warnf("Failed to find test XML test results, error: %s", err) } else { lastOtherDirIdx := -1 for _, artifact := range resultXMLs { @@ -267,9 +272,9 @@ func main() { } fmt.Println() - log.Infof("Collecting cache:") - if warning := cache.Collect(config.ProjectLocation, utilscache.Level(config.CacheLevel)); warning != nil { - log.Warnf("%s", warning) + logger.Infof("Collecting cache:") + if warning := cache.Collect(config.ProjectLocation, utilscache.Level(config.CacheLevel), cmdFactory); warning != nil { + logger.Warnf("%s", warning) } - log.Donef(" Done") + logger.Donef(" Done") } diff --git a/vendor/github.com/bitrise-io/go-android/cache/cache.go b/vendor/github.com/bitrise-io/go-android/cache/cache.go index 1a282a0..2396339 100644 --- a/vendor/github.com/bitrise-io/go-android/cache/cache.go +++ b/vendor/github.com/bitrise-io/go-android/cache/cache.go @@ -6,7 +6,6 @@ import ( "io" "io/ioutil" "os" - "os/exec" "path/filepath" "strings" @@ -19,11 +18,12 @@ import ( // AndroidGradleCacheItemCollector ... type AndroidGradleCacheItemCollector struct { + cmdFactory command.Factory } // NewAndroidGradleCacheItemCollector ... -func NewAndroidGradleCacheItemCollector() cache.ItemCollector { - return AndroidGradleCacheItemCollector{} +func NewAndroidGradleCacheItemCollector(cmdFactory command.Factory) cache.ItemCollector { + return AndroidGradleCacheItemCollector{cmdFactory: cmdFactory} } // Collect ... @@ -39,12 +39,12 @@ func (c AndroidGradleCacheItemCollector) Collect(dir string, cacheLevel cache.Le return nil, nil, fmt.Errorf("cache collection skipped: failed to determine project root path") } - includePths, err := collectIncludePaths(homeDir, projectRoot, cacheLevel) + includePths, err := c.collectIncludePaths(homeDir, projectRoot, cacheLevel) if err != nil { return nil, nil, err } - excludePths := collectExcludePaths(homeDir, projectRoot) + excludePths := c.collectExcludePaths(homeDir, projectRoot) return includePths, excludePths, nil } @@ -53,8 +53,8 @@ func (c AndroidGradleCacheItemCollector) Collect(dir string, cacheLevel cache.Le // paths for caching based on the value of cacheLevel. Returns an error if there // was an underlying error that would lead to a corrupted cache file, otherwise // the given path is skipped. -func Collect(projectRoot string, cacheLevel cache.Level) error { - cacheItemCollector := NewAndroidGradleCacheItemCollector() +func Collect(projectRoot string, cacheLevel cache.Level, cmdFactory command.Factory) error { + cacheItemCollector := NewAndroidGradleCacheItemCollector(cmdFactory) includes, excludes, err := cacheItemCollector.Collect(projectRoot, cacheLevel) if err != nil { return err @@ -74,7 +74,7 @@ func Collect(projectRoot string, cacheLevel cache.Level) error { return nil } -func collectIncludePaths(homeDir, projectDir string, cacheLevel cache.Level) ([]string, error) { +func (c AndroidGradleCacheItemCollector) collectIncludePaths(homeDir, projectDir string, cacheLevel cache.Level) ([]string, error) { var includePths []string lockFilePath := filepath.Join(projectDir, "gradle.deps") @@ -93,7 +93,7 @@ func collectIncludePaths(homeDir, projectDir string, cacheLevel cache.Level) ([] return nil } - unmodified, err := prepareUnmodifiedIndicator(path) + unmodified, err := c.prepareUnmodifiedIndicator(path) if err != nil { log.Debugf(err.Error()) unmodified = path @@ -148,21 +148,21 @@ func collectIncludePaths(homeDir, projectDir string, cacheLevel cache.Level) ([] /* If the indicator is version controlled in git and has changes, we create a copy of it with its original content. */ -func prepareUnmodifiedIndicator(indicator string) (unmodified string, err error) { +func (c AndroidGradleCacheItemCollector) prepareUnmodifiedIndicator(indicator string) (unmodified string, err error) { indicatorDir := filepath.Dir(indicator) indicatorFile := filepath.Base(indicator) + opts := command.Opts{Dir: indicatorDir} - cmd := exec.Command("git", "ls-files", "--error-unmatch", indicatorFile) - cmd.Dir = indicatorDir - m := command.NewWithCmd(cmd) - code, err := m.RunAndReturnExitCode() + lsArgs := []string{"ls-files", "--error-unmatch", indicatorFile} + lsCmd := c.cmdFactory.Create("git", lsArgs, &opts) + code, err := lsCmd.RunAndReturnExitCode() if code != 0 { return "", fmt.Errorf("%s is not under git version control", indicator) } - cmd = exec.Command("git", "diff", "-s", "--exit-code", indicatorFile) - cmd.Dir = indicatorDir - m = command.NewWithCmd(cmd) - code, err = m.RunAndReturnExitCode() + + diffArgs := []string{"diff", "-s", "--exit-code", indicatorFile} + diffCmd := c.cmdFactory.Create("git", diffArgs, &opts) + code, err = diffCmd.RunAndReturnExitCode() if code == 0 { return "", fmt.Errorf("%s has not modification compared to HEAD", indicator) } @@ -178,10 +178,14 @@ func prepareUnmodifiedIndicator(indicator string) (unmodified string, err error) } }() - cmd = exec.Command("git", "show", "HEAD:"+indicatorFile) - cmd.Dir = indicatorDir - m = command.NewWithCmd(cmd).SetStdout(file).SetStderr(os.Stderr) - code, err = m.RunAndReturnExitCode() + showArgs := []string{"show", "HEAD:" + indicatorFile} + showOpts := command.Opts{ + Stdout: file, + Stderr: os.Stderr, + Dir: indicatorDir, + } + showCmd := c.cmdFactory.Create("git", showArgs, &showOpts) + code, err = showCmd.RunAndReturnExitCode() if err != nil || code != 0 { return "", err } @@ -207,7 +211,7 @@ func computeMD5String(filePath string) (string, error) { return fmt.Sprintf("%x", h.Sum(nil)), nil } -func collectExcludePaths(homeDir, projectDir string) []string { +func (c AndroidGradleCacheItemCollector) collectExcludePaths(homeDir, projectDir string) []string { excludePths := []string{ "!~/.gradle/daemon/*/daemon-*.out.log", // excludes Gradle daemon logs, like: ~/.gradle/daemon/6.1.1/daemon-3122.out.log "~/.android/build-cache/**", @@ -225,7 +229,7 @@ func collectExcludePaths(homeDir, projectDir string) []string { "!*.apk", } - ver, err := projectGradleVersion(projectDir) + ver, err := projectGradleVersion(projectDir, c.cmdFactory) if err != nil { log.Warnf("Failed to get project gradle version: %s", err) return nil diff --git a/vendor/github.com/bitrise-io/go-android/cache/gradle.go b/vendor/github.com/bitrise-io/go-android/cache/gradle.go index f34d3f7..4a72392 100644 --- a/vendor/github.com/bitrise-io/go-android/cache/gradle.go +++ b/vendor/github.com/bitrise-io/go-android/cache/gradle.go @@ -38,7 +38,7 @@ func parseGradleVersion(out string) (string, error) { return matches[1], nil } -func projectGradleVersion(projectPth string) (string, error) { +func projectGradleVersion(projectPth string, cmdFactory command.Factory) (string, error) { gradlewPth := filepath.Join(projectPth, "gradlew") exist, err := pathutil.IsPathExists(gradlewPth) if err != nil { @@ -48,8 +48,8 @@ func projectGradleVersion(projectPth string) (string, error) { return "", fmt.Errorf("no gradlew found at: %s", gradlewPth) } - versionCmd := command.New("./gradlew", "-version") - versionCmd.SetDir(filepath.Dir(gradlewPth)) + versionCmdOpts := command.Opts{Dir: filepath.Dir(gradlewPth)} + versionCmd := cmdFactory.Create("./gradlew", []string{"-version"}, &versionCmdOpts) out, err := versionCmd.RunAndReturnTrimmedCombinedOutput() if err != nil { if errorutil.IsExitStatusError(err) { diff --git a/vendor/github.com/bitrise-io/go-android/gradle/artifact.go b/vendor/github.com/bitrise-io/go-android/gradle/artifact.go old mode 100755 new mode 100644 diff --git a/vendor/github.com/bitrise-io/go-android/gradle/common.go b/vendor/github.com/bitrise-io/go-android/gradle/common.go old mode 100755 new mode 100644 index 1f60bf4..22a0ff2 --- a/vendor/github.com/bitrise-io/go-android/gradle/common.go +++ b/vendor/github.com/bitrise-io/go-android/gradle/common.go @@ -1,27 +1,18 @@ package gradle import ( - "path/filepath" "strings" - - "github.com/bitrise-io/go-utils/command" ) // If we parse tasks that starts with lint, we will have tasks that starts // with lintVital also. So list here each conflicting tasks. (only overlapping ones) var conflicts = map[string][]string{ - "lint": []string{ + "lint": { "lintVital", "lintFix", }, } -func getGradleOutput(projPath string, tasks ...string) (string, error) { - c := command.New(filepath.Join(projPath, "gradlew"), tasks...) - c.SetDir(projPath) - return c.RunAndReturnTrimmedCombinedOutput() -} - func cleanStringSlice(in []string) (out []string) { for _, s := range in { s = strings.TrimSpace(s) diff --git a/vendor/github.com/bitrise-io/go-android/gradle/project.go b/vendor/github.com/bitrise-io/go-android/gradle/project.go old mode 100755 new mode 100644 index 6f7c4ca..4746e58 --- a/vendor/github.com/bitrise-io/go-android/gradle/project.go +++ b/vendor/github.com/bitrise-io/go-android/gradle/project.go @@ -2,6 +2,7 @@ package gradle import ( "fmt" + "github.com/bitrise-io/go-utils/command" "io/ioutil" "os" "path/filepath" @@ -15,12 +16,13 @@ import ( // Project ... type Project struct { - location string - monoRepo bool + location string + monoRepo bool + cmdFactory command.Factory } // NewProject ... -func NewProject(location string) (Project, error) { +func NewProject(location string, cmdFactory command.Factory) (Project, error) { var err error location, err = filepath.Abs(location) if err != nil { @@ -42,7 +44,7 @@ func NewProject(location string) (Project, error) { } if location == "/" { - return Project{location: location, monoRepo: false}, nil + return Project{location: location, monoRepo: false, cmdFactory: cmdFactory}, nil } root := filepath.Join(location, "..") @@ -65,7 +67,7 @@ func NewProject(location string) (Project, error) { } } - return Project{location: location, monoRepo: (projectsCount > 1)}, nil + return Project{location: location, monoRepo: projectsCount > 1, cmdFactory: cmdFactory}, nil } // GetTask ... diff --git a/vendor/github.com/bitrise-io/go-android/gradle/task.go b/vendor/github.com/bitrise-io/go-android/gradle/task.go old mode 100755 new mode 100644 index e557202..8d89805 --- a/vendor/github.com/bitrise-io/go-android/gradle/task.go +++ b/vendor/github.com/bitrise-io/go-android/gradle/task.go @@ -2,6 +2,7 @@ package gradle import ( "fmt" + "os" "path/filepath" "strings" @@ -15,8 +16,11 @@ type Task struct { } // GetVariants ... -func (task *Task) GetVariants() (Variants, error) { - tasksOutput, err := getGradleOutput(task.project.location, "tasks", "--all", "--console=plain", "--quiet") +func (task *Task) GetVariants(args ...string) (Variants, error) { + opts := command.Opts{Dir: task.project.location} + args = append([]string{"tasks", "--all", "--console=plain", "--quiet"}, args...) + cmd := task.project.cmdFactory.Create(filepath.Join(task.project.location, "gradlew"), args, &opts) + tasksOutput, err := cmd.RunAndReturnTrimmedCombinedOutput() if err != nil { return nil, fmt.Errorf("%s, %s", tasksOutput, err) } @@ -46,8 +50,8 @@ lines: split := strings.Split(l, ":") size := len(split) if size > 1 { - module = strings.Join(split[:size - 1], ":") - l = split[size - 1] + module = strings.Join(split[:size-1], ":") + l = split[size-1] } // module removed if any if strings.HasPrefix(l, task.name) { @@ -84,13 +88,17 @@ func cleanModuleName(s string) string { } // GetCommand ... -func (task *Task) GetCommand(v Variants, args ...string) *command.Model { +func (task *Task) GetCommand(v Variants, args ...string) command.Command { var a []string for module, variants := range v { for _, variant := range variants { a = append(a, cleanModuleName(module)+task.name+variant) } } - return command.NewWithStandardOuts(filepath.Join(task.project.location, "gradlew"), append(a, args...)...). - SetDir(task.project.location) + cmdOpts := command.Opts{ + Dir: task.project.location, + Stdout: os.Stdout, + Stderr: os.Stderr, + } + return task.project.cmdFactory.Create(filepath.Join(task.project.location, "gradlew"), append(a, args...), &cmdOpts) } diff --git a/vendor/github.com/bitrise-io/go-android/gradle/variant.go b/vendor/github.com/bitrise-io/go-android/gradle/variant.go old mode 100755 new mode 100644 diff --git a/vendor/github.com/bitrise-io/go-steputils/tools/tools.go b/vendor/github.com/bitrise-io/go-steputils/tools/tools.go index 3372b16..f665afa 100644 --- a/vendor/github.com/bitrise-io/go-steputils/tools/tools.go +++ b/vendor/github.com/bitrise-io/go-steputils/tools/tools.go @@ -1,14 +1,16 @@ package tools import ( - "strings" - "github.com/bitrise-io/go-utils/command" + "github.com/bitrise-io/go-utils/env" + "strings" ) +// TODO remove +var temporaryFactory = command.NewFactory(env.NewRepository()) + // ExportEnvironmentWithEnvman ... func ExportEnvironmentWithEnvman(key, value string) error { - cmd := command.New("envman", "add", "--key", key) - cmd.SetStdin(strings.NewReader(value)) + cmd := temporaryFactory.Create("envman", []string{"add", "--key", key}, &command.Opts{Stdin: strings.NewReader(value)}) return cmd.Run() } diff --git a/vendor/github.com/bitrise-io/go-utils/command/command.go b/vendor/github.com/bitrise-io/go-utils/command/command.go index c068490..0ef8af3 100644 --- a/vendor/github.com/bitrise-io/go-utils/command/command.go +++ b/vendor/github.com/bitrise-io/go-utils/command/command.go @@ -1,129 +1,113 @@ package command import ( - "errors" "io" - "os" "os/exec" "strconv" "strings" -) - -// ---------- -// Model ... -type Model struct { - cmd *exec.Cmd -} + "github.com/bitrise-io/go-utils/env" +) -// New ... -func New(name string, args ...string) *Model { - return &Model{ - cmd: exec.Command(name, args...), - } +// Opts ... +type Opts struct { + Stdout io.Writer + Stderr io.Writer + Stdin io.Reader + Env []string + Dir string } -// NewWithStandardOuts - same as NewCommand, but sets the command's -// stdout and stderr to the standard (OS) out (os.Stdout) and err (os.Stderr) -func NewWithStandardOuts(name string, args ...string) *Model { - return New(name, args...).SetStdout(os.Stdout).SetStderr(os.Stderr) +// Factory ... +type Factory interface { + Create(name string, args []string, opts *Opts) Command } -// NewWithParams ... -func NewWithParams(params ...string) (*Model, error) { - if len(params) == 0 { - return nil, errors.New("no command provided") - } else if len(params) == 1 { - return New(params[0]), nil - } - - return New(params[0], params[1:]...), nil +type defaultFactory struct { + envRepository env.Repository } -// NewFromSlice ... -func NewFromSlice(slice []string) (*Model, error) { - return NewWithParams(slice...) +// NewFactory ... +func NewFactory(envRepository env.Repository) Factory { + return defaultFactory{envRepository: envRepository} } -// NewWithCmd ... -func NewWithCmd(cmd *exec.Cmd) *Model { - return &Model{ - cmd: cmd, +// Create ... +func (f defaultFactory) Create(name string, args []string, opts *Opts) Command { + cmd := exec.Command(name, args...) + if opts != nil { + cmd.Stdout = opts.Stdout + cmd.Stderr = opts.Stderr + cmd.Stdin = opts.Stdin + + // If Env is nil, the new process uses the current process's + // environment. + // If we pass env vars we want to append them to the + // current process's environment. + cmd.Env = append(f.envRepository.List(), opts.Env...) + cmd.Dir = opts.Dir } + return defaultCommand{cmd} } -// GetCmd ... -func (m *Model) GetCmd() *exec.Cmd { - return m.cmd +// Command ... +type Command interface { + PrintableCommandArgs() string + Run() error + RunAndReturnExitCode() (int, error) + RunAndReturnTrimmedOutput() (string, error) + RunAndReturnTrimmedCombinedOutput() (string, error) + Start() error + Wait() error } -// SetDir ... -func (m *Model) SetDir(dir string) *Model { - m.cmd.Dir = dir - return m -} - -// SetEnvs ... -func (m *Model) SetEnvs(envs ...string) *Model { - m.cmd.Env = envs - return m -} - -// AppendEnvs - appends the envs to the current os.Environ() -// Calling this multiple times will NOT appens the envs one by one, -// only the last "envs" set will be appended to os.Environ()! -func (m *Model) AppendEnvs(envs ...string) *Model { - return m.SetEnvs(append(os.Environ(), envs...)...) -} - -// SetStdin ... -func (m *Model) SetStdin(in io.Reader) *Model { - m.cmd.Stdin = in - return m -} - -// SetStdout ... -func (m *Model) SetStdout(out io.Writer) *Model { - m.cmd.Stdout = out - return m +type defaultCommand struct { + cmd *exec.Cmd } -// SetStderr ... -func (m *Model) SetStderr(err io.Writer) *Model { - m.cmd.Stderr = err - return m +// PrintableCommandArgs ... +func (c defaultCommand) PrintableCommandArgs() string { + return printableCommandArgs(false, c.cmd.Args) } // Run ... -func (m Model) Run() error { - return m.cmd.Run() +func (c defaultCommand) Run() error { + return c.cmd.Run() } // RunAndReturnExitCode ... -func (m Model) RunAndReturnExitCode() (int, error) { - return RunCmdAndReturnExitCode(m.cmd) +func (c defaultCommand) RunAndReturnExitCode() (int, error) { + err := c.cmd.Run() + exitCode := c.cmd.ProcessState.ExitCode() + return exitCode, err } // RunAndReturnTrimmedOutput ... -func (m Model) RunAndReturnTrimmedOutput() (string, error) { - return RunCmdAndReturnTrimmedOutput(m.cmd) +func (c defaultCommand) RunAndReturnTrimmedOutput() (string, error) { + outBytes, err := c.cmd.Output() + outStr := string(outBytes) + return strings.TrimSpace(outStr), err } // RunAndReturnTrimmedCombinedOutput ... -func (m Model) RunAndReturnTrimmedCombinedOutput() (string, error) { - return RunCmdAndReturnTrimmedCombinedOutput(m.cmd) +func (c defaultCommand) RunAndReturnTrimmedCombinedOutput() (string, error) { + outBytes, err := c.cmd.CombinedOutput() + outStr := string(outBytes) + return strings.TrimSpace(outStr), err } -// PrintableCommandArgs ... -func (m Model) PrintableCommandArgs() string { - return PrintableCommandArgs(false, m.cmd.Args) +// Start ... +func (c defaultCommand) Start() error { + return c.cmd.Start() } -// ---------- +// Wait ... +func (c defaultCommand) Wait() error { + return c.cmd.Wait() +} -// PrintableCommandArgs ... -func PrintableCommandArgs(isQuoteFirst bool, fullCommandArgs []string) string { - cmdArgsDecorated := []string{} +func printableCommandArgs(isQuoteFirst bool, fullCommandArgs []string) string { + var cmdArgsDecorated []string for idx, anArg := range fullCommandArgs { quotedArg := strconv.Quote(anArg) if idx == 0 && !isQuoteFirst { @@ -134,119 +118,3 @@ func PrintableCommandArgs(isQuoteFirst bool, fullCommandArgs []string) string { return strings.Join(cmdArgsDecorated, " ") } - -// RunCmdAndReturnExitCode ... -func RunCmdAndReturnExitCode(cmd *exec.Cmd) (exitCode int, err error) { - err = cmd.Run() - exitCode = cmd.ProcessState.ExitCode() - return -} - -// RunCmdAndReturnTrimmedOutput ... -func RunCmdAndReturnTrimmedOutput(cmd *exec.Cmd) (string, error) { - outBytes, err := cmd.Output() - outStr := string(outBytes) - return strings.TrimSpace(outStr), err -} - -// RunCmdAndReturnTrimmedCombinedOutput ... -func RunCmdAndReturnTrimmedCombinedOutput(cmd *exec.Cmd) (string, error) { - outBytes, err := cmd.CombinedOutput() - outStr := string(outBytes) - return strings.TrimSpace(outStr), err -} - -// RunCommandWithReaderAndWriters ... -func RunCommandWithReaderAndWriters(inReader io.Reader, outWriter, errWriter io.Writer, name string, args ...string) error { - cmd := exec.Command(name, args...) - cmd.Stdin = inReader - cmd.Stdout = outWriter - cmd.Stderr = errWriter - return cmd.Run() -} - -// RunCommandWithWriters ... -func RunCommandWithWriters(outWriter, errWriter io.Writer, name string, args ...string) error { - cmd := exec.Command(name, args...) - cmd.Stdout = outWriter - cmd.Stderr = errWriter - return cmd.Run() -} - -// RunCommandInDirWithEnvsAndReturnExitCode ... -func RunCommandInDirWithEnvsAndReturnExitCode(envs []string, dir, name string, args ...string) (int, error) { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if dir != "" { - cmd.Dir = dir - } - if len(envs) > 0 { - cmd.Env = envs - } - - return RunCmdAndReturnExitCode(cmd) -} - -// RunCommandInDirAndReturnExitCode ... -func RunCommandInDirAndReturnExitCode(dir, name string, args ...string) (int, error) { - return RunCommandInDirWithEnvsAndReturnExitCode([]string{}, dir, name, args...) -} - -// RunCommandWithEnvsAndReturnExitCode ... -func RunCommandWithEnvsAndReturnExitCode(envs []string, name string, args ...string) (int, error) { - return RunCommandInDirWithEnvsAndReturnExitCode(envs, "", name, args...) -} - -// RunCommandInDir ... -func RunCommandInDir(dir, name string, args ...string) error { - cmd := exec.Command(name, args...) - cmd.Stdin = os.Stdin - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if dir != "" { - cmd.Dir = dir - } - return cmd.Run() -} - -// RunCommand ... -func RunCommand(name string, args ...string) error { - return RunCommandInDir("", name, args...) -} - -// RunCommandAndReturnStdout .. -func RunCommandAndReturnStdout(name string, args ...string) (string, error) { - cmd := exec.Command(name, args...) - return RunCmdAndReturnTrimmedOutput(cmd) -} - -// RunCommandInDirAndReturnCombinedStdoutAndStderr ... -func RunCommandInDirAndReturnCombinedStdoutAndStderr(dir, name string, args ...string) (string, error) { - cmd := exec.Command(name, args...) - if dir != "" { - cmd.Dir = dir - } - return RunCmdAndReturnTrimmedCombinedOutput(cmd) -} - -// RunCommandAndReturnCombinedStdoutAndStderr .. -func RunCommandAndReturnCombinedStdoutAndStderr(name string, args ...string) (string, error) { - return RunCommandInDirAndReturnCombinedStdoutAndStderr("", name, args...) -} - -// RunBashCommand ... -func RunBashCommand(cmdStr string) error { - return RunCommand("bash", "-c", cmdStr) -} - -// RunBashCommandLines ... -func RunBashCommandLines(cmdLines []string) error { - for _, aLine := range cmdLines { - if err := RunCommand("bash", "-c", aLine); err != nil { - return err - } - } - return nil -} diff --git a/vendor/github.com/bitrise-io/go-utils/command/file.go b/vendor/github.com/bitrise-io/go-utils/command/file.go index 6b22172..be29aa1 100644 --- a/vendor/github.com/bitrise-io/go-utils/command/file.go +++ b/vendor/github.com/bitrise-io/go-utils/command/file.go @@ -2,6 +2,7 @@ package command import ( "errors" + "github.com/bitrise-io/go-utils/env" "os" "strings" @@ -20,7 +21,7 @@ func CopyFile(src, dst string) error { return errors.New("Source is a directory: " + src) } args := []string{src, dst} - return RunCommand("rsync", args...) + return NewFactory(env.NewRepository()).Create("rsync", args, &Opts{Stderr: os.Stderr, Stdout: os.Stdout}).Run() } // CopyDir ... @@ -29,7 +30,7 @@ func CopyDir(src, dst string, isOnlyContent bool) error { src = src + "/" } args := []string{"-ar", src, dst} - return RunCommand("rsync", args...) + return NewFactory(env.NewRepository()).Create("rsync", args, &Opts{Stderr: os.Stderr, Stdout: os.Stdout}).Run() } // RemoveDir ... diff --git a/vendor/github.com/bitrise-io/go-utils/env/env.go b/vendor/github.com/bitrise-io/go-utils/env/env.go new file mode 100644 index 0000000..221f27d --- /dev/null +++ b/vendor/github.com/bitrise-io/go-utils/env/env.go @@ -0,0 +1,58 @@ +package env + +import ( + "os" + "os/exec" +) + +// CommandLocator ... +type CommandLocator interface { + LookPath(file string) (string, error) +} + +type commandLocator struct{} + +// NewCommandLocator ... +func NewCommandLocator() CommandLocator { + return commandLocator{} +} + +// LookPath ... +func (l commandLocator) LookPath(file string) (string, error) { + return exec.LookPath(file) +} + +// Repository ... +type Repository interface { + List() []string + Unset(key string) error + Get(key string) string + Set(key, value string) error +} + +// NewRepository ... +func NewRepository() Repository { + return defaultRepository{} +} + +type defaultRepository struct{} + +// Get ... +func (d defaultRepository) Get(key string) string { + return os.Getenv(key) +} + +// Set ... +func (d defaultRepository) Set(key, value string) error { + return os.Setenv(key, value) +} + +// Unset ... +func (d defaultRepository) Unset(key string) error { + return os.Unsetenv(key) +} + +// List ... +func (d defaultRepository) List() []string { + return os.Environ() +} diff --git a/vendor/github.com/bitrise-io/go-utils/fileutil/fileutil.go b/vendor/github.com/bitrise-io/go-utils/fileutil/fileutil.go index 80c913b..3633e28 100644 --- a/vendor/github.com/bitrise-io/go-utils/fileutil/fileutil.go +++ b/vendor/github.com/bitrise-io/go-utils/fileutil/fileutil.go @@ -7,10 +7,56 @@ import ( "io/ioutil" "log" "os" + "path/filepath" "github.com/bitrise-io/go-utils/pathutil" ) +// FileManager ... +type FileManager interface { + Remove(path string) error + RemoveAll(path string) error + Write(path string, value string, mode os.FileMode) error +} + +type fileManager struct{} + +// NewFileManager ... +func NewFileManager() FileManager { + return fileManager{} +} + +// Remove ... +func (fileManager) Remove(path string) error { + return os.Remove(path) +} + +// RemoveAll ... +func (fileManager) RemoveAll(path string) error { + return os.RemoveAll(path) +} + +// Write ... +func (fileManager) Write(path string, value string, mode os.FileMode) error { + if err := ensureSavePath(path); err != nil { + return err + } + + if err := WriteStringToFile(path, value); err != nil { + return err + } + + if err := os.Chmod(path, mode); err != nil { + return err + } + return nil +} + +func ensureSavePath(savePath string) error { + dirPath := filepath.Dir(savePath) + return os.MkdirAll(dirPath, 0700) +} + // WriteStringToFile ... func WriteStringToFile(pth string, fileCont string) error { return WriteBytesToFile(pth, []byte(fileCont)) diff --git a/vendor/github.com/bitrise-io/go-utils/log/defaultlogger.go b/vendor/github.com/bitrise-io/go-utils/log/defaultlogger.go deleted file mode 100644 index 0d2a307..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/defaultlogger.go +++ /dev/null @@ -1,57 +0,0 @@ -package log - -// DefaultLogger ... -type DefaultLogger struct { - ts bool -} - -// NewDefaultLogger ... -func NewDefaultLogger(withTimestamp bool) DefaultLogger { - return DefaultLogger{withTimestamp} -} - -// Donef ... -func (dl DefaultLogger) Donef(format string, v ...interface{}) { - fSelect(dl.ts, TDonef, Donef)(format, v...) -} - -// Successf ... -func (dl DefaultLogger) Successf(format string, v ...interface{}) { - fSelect(dl.ts, TSuccessf, Successf)(format, v...) -} - -// Infof ... -func (dl DefaultLogger) Infof(format string, v ...interface{}) { - fSelect(dl.ts, TInfof, Infof)(format, v...) -} - -// Printf ... -func (dl DefaultLogger) Printf(format string, v ...interface{}) { - fSelect(dl.ts, TPrintf, Printf)(format, v...) -} - -// Warnf ... -func (dl DefaultLogger) Warnf(format string, v ...interface{}) { - fSelect(dl.ts, TWarnf, Warnf)(format, v...) -} - -// Errorf ... -func (dl DefaultLogger) Errorf(format string, v ...interface{}) { - fSelect(dl.ts, TErrorf, Errorf)(format, v...) -} - -// Debugf ... -func (dl DefaultLogger) Debugf(format string, v ...interface{}) { - if enableDebugLog { - fSelect(dl.ts, TDebugf, Debugf)(format, v...) - } -} - -type logfunc func(string, ...interface{}) - -func fSelect(t bool, tf logfunc, f logfunc) logfunc { - if t { - return tf - } - return f -} diff --git a/vendor/github.com/bitrise-io/go-utils/log/dummylogger.go b/vendor/github.com/bitrise-io/go-utils/log/dummylogger.go deleted file mode 100644 index 54b0bb9..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/dummylogger.go +++ /dev/null @@ -1,30 +0,0 @@ -package log - -// DummyLogger ... -type DummyLogger struct{} - -// NewDummyLogger ... -func NewDummyLogger() DummyLogger { - return DummyLogger{} -} - -// Donef ... -func (dl DummyLogger) Donef(format string, v ...interface{}) {} - -// Successf ... -func (dl DummyLogger) Successf(format string, v ...interface{}) {} - -// Infof ... -func (dl DummyLogger) Infof(format string, v ...interface{}) {} - -// Printf ... -func (dl DummyLogger) Printf(format string, v ...interface{}) {} - -// Debugf ... -func (dl DummyLogger) Debugf(format string, v ...interface{}) {} - -// Warnf ... -func (dl DummyLogger) Warnf(format string, v ...interface{}) {} - -// Errorf ... -func (dl DummyLogger) Errorf(format string, v ...interface{}) {} diff --git a/vendor/github.com/bitrise-io/go-utils/log/json_logger.go b/vendor/github.com/bitrise-io/go-utils/log/json_logger.go deleted file mode 100644 index 31148b3..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/json_logger.go +++ /dev/null @@ -1,33 +0,0 @@ -package log - -import ( - "fmt" - "io" - "os" -) - -// JSONLoger ... -type JSONLoger struct { - writer io.Writer -} - -// NewJSONLoger ... -func NewJSONLoger(writer io.Writer) *JSONLoger { - return &JSONLoger{ - writer: writer, - } -} - -// NewDefaultJSONLoger ... -func NewDefaultJSONLoger() JSONLoger { - return JSONLoger{ - writer: os.Stdout, - } -} - -// Print ... -func (l JSONLoger) Print(f Formatable) { - if _, err := fmt.Fprint(l.writer, f.JSON()); err != nil { - fmt.Printf("failed to print message: %s, error: %s\n", f.JSON(), err) - } -} diff --git a/vendor/github.com/bitrise-io/go-utils/log/log.go b/vendor/github.com/bitrise-io/go-utils/log/log.go index 1b69028..84bd490 100644 --- a/vendor/github.com/bitrise-io/go-utils/log/log.go +++ b/vendor/github.com/bitrise-io/go-utils/log/log.go @@ -7,28 +7,240 @@ import ( "time" ) -var outWriter io.Writer = os.Stdout +// Logger ... +type Logger interface { + Infof(format string, v ...interface{}) + Warnf(format string, v ...interface{}) + Printf(format string, v ...interface{}) + Donef(format string, v ...interface{}) + Debugf(format string, v ...interface{}) + Errorf(format string, v ...interface{}) + TInfof(format string, v ...interface{}) + TWarnf(format string, v ...interface{}) + TPrintf(format string, v ...interface{}) + TDonef(format string, v ...interface{}) + TDebugf(format string, v ...interface{}) + TErrorf(format string, v ...interface{}) + Println() + EnableDebugLog(enable bool) +} -// SetOutWriter ... -func SetOutWriter(writer io.Writer) { - outWriter = writer +const defaultTimeStampLayout = "15:04:05" + +type defaultLogger struct { + enableDebugLog bool + timestampLayout string + stdout io.Writer +} + +// NewLogger ... +func NewLogger() Logger { + return &defaultLogger{enableDebugLog: false, timestampLayout: defaultTimeStampLayout, stdout: os.Stdout} +} + +// EnableDebugLog ... +func (l *defaultLogger) EnableDebugLog(enable bool) { + l.enableDebugLog = enable +} + +// Infof ... +func (l *defaultLogger) Infof(format string, v ...interface{}) { + l.printf(infoSeverity, false, format, v...) +} + +// Warnf ... +func (l *defaultLogger) Warnf(format string, v ...interface{}) { + l.printf(warnSeverity, false, format, v...) +} + +// Printf ... +func (l *defaultLogger) Printf(format string, v ...interface{}) { + l.printf(normalSeverity, false, format, v...) +} + +// Donef ... +func (l *defaultLogger) Donef(format string, v ...interface{}) { + l.printf(doneSeverity, false, format, v...) +} + +// Debugf ... +func (l *defaultLogger) Debugf(format string, v ...interface{}) { + if l.enableDebugLog { + l.printf(debugSeverity, false, format, v...) + } +} + +// Errorf ... +func (l *defaultLogger) Errorf(format string, v ...interface{}) { + l.printf(errorSeverity, false, format, v...) +} + +// TInfof ... +func (l *defaultLogger) TInfof(format string, v ...interface{}) { + l.printf(infoSeverity, true, format, v...) +} + +// TWarnf ... +func (l *defaultLogger) TWarnf(format string, v ...interface{}) { + l.printf(warnSeverity, true, format, v...) +} + +// TPrintf ... +func (l *defaultLogger) TPrintf(format string, v ...interface{}) { + l.printf(normalSeverity, true, format, v...) +} + +// TDonef ... +func (l *defaultLogger) TDonef(format string, v ...interface{}) { + l.printf(doneSeverity, true, format, v...) +} + +// TDebugf ... +func (l *defaultLogger) TDebugf(format string, v ...interface{}) { + if l.enableDebugLog { + l.printf(debugSeverity, true, format, v...) + } +} + +// TErrorf ... +func (l *defaultLogger) TErrorf(format string, v ...interface{}) { + l.printf(errorSeverity, true, format, v...) +} + +// Println ... +func (l *defaultLogger) Println() { + fmt.Println() +} + +func (l *defaultLogger) timestampField() string { + currentTime := time.Now() + return fmt.Sprintf("[%s]", currentTime.Format(l.timestampLayout)) +} + +func (l *defaultLogger) prefixCurrentTime(message string) string { + return fmt.Sprintf("%s %s", l.timestampField(), message) } -var enableDebugLog = false +func (l *defaultLogger) createLogMsg(severity Severity, withTime bool, format string, v ...interface{}) string { + colorFunc := severityColorFuncMap[severity] + message := colorFunc(format, v...) + if withTime { + message = l.prefixCurrentTime(message) + } + + return message +} + +func (l *defaultLogger) printf(severity Severity, withTime bool, format string, v ...interface{}) { + message := l.createLogMsg(severity, withTime, format, v...) + if _, err := fmt.Fprintln(l.stdout, message); err != nil { + fmt.Printf("failed to print message: %s, error: %s\n", message, err) + } +} + +// RInfof ... +func RInfof(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { + rprintf("info", stepID, tag, data, format, v...) +} + +// RWarnf ... +func RWarnf(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { + rprintf("warn", stepID, tag, data, format, v...) +} + +// RErrorf ... +func RErrorf(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { + rprintf("error", stepID, tag, data, format, v...) +} + +var deprecatedLogger = defaultLogger{stdout: os.Stdout, enableDebugLog: false, timestampLayout: defaultTimeStampLayout} // SetEnableDebugLog ... +// Deprecated: use Logger instead. func SetEnableDebugLog(enable bool) { - enableDebugLog = enable + deprecatedLogger.enableDebugLog = enable } -var timestampLayout = "15:04:05" - // SetTimestampLayout ... +// Deprecated: use Logger instead. func SetTimestampLayout(layout string) { - timestampLayout = layout + deprecatedLogger.timestampLayout = layout } -func timestampField() string { - currentTime := time.Now() - return fmt.Sprintf("[%s]", currentTime.Format(timestampLayout)) +// SetOutWriter ... +// Deprecated: use Logger for verification instead. +func SetOutWriter(writer io.Writer) { + deprecatedLogger.stdout = writer +} + +// Donef ... +// Deprecated: use Logger instead. +func Donef(format string, v ...interface{}) { + deprecatedLogger.Donef(format, v...) +} + +// Infof ... +// Deprecated: use Logger instead. +func Infof(format string, v ...interface{}) { + deprecatedLogger.Infof(format, v...) +} + +// Printf ... +// Deprecated: use Logger instead. +func Printf(format string, v ...interface{}) { + deprecatedLogger.Printf(format, v...) +} + +// Debugf ... +// Deprecated: use Logger instead. +func Debugf(format string, v ...interface{}) { + deprecatedLogger.Debugf(format, v...) +} + +// Warnf ... +// Deprecated: use Logger instead. +func Warnf(format string, v ...interface{}) { + deprecatedLogger.Warnf(format, v...) +} + +// Errorf ... +// Deprecated: use Logger instead. +func Errorf(format string, v ...interface{}) { + deprecatedLogger.Errorf(format, v...) +} + +// TDonef ... +// Deprecated: use Logger instead. +func TDonef(format string, v ...interface{}) { + deprecatedLogger.TDonef(format, v...) +} + +// TInfof ... +// Deprecated: use Logger instead. +func TInfof(format string, v ...interface{}) { + deprecatedLogger.TInfof(format, v...) +} + +// TPrintf ... +// Deprecated: use Logger instead. +func TPrintf(format string, v ...interface{}) { + deprecatedLogger.TPrintf(format, v...) +} + +// TDebugf ... +// Deprecated: use Logger instead. +func TDebugf(format string, v ...interface{}) { + deprecatedLogger.TDebugf(format, v...) +} + +// TWarnf ... +// Deprecated: use Logger instead. +func TWarnf(format string, v ...interface{}) { + deprecatedLogger.TWarnf(format, v...) +} + +// TErrorf ... +// Deprecated: use Logger instead. +func TErrorf(format string, v ...interface{}) { + deprecatedLogger.TErrorf(format, v...) } diff --git a/vendor/github.com/bitrise-io/go-utils/log/logger.go b/vendor/github.com/bitrise-io/go-utils/log/logger.go deleted file mode 100644 index 4691122..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/logger.go +++ /dev/null @@ -1,12 +0,0 @@ -package log - -// Logger ... -type Logger interface { - Print(f Formatable) -} - -// Formatable ... -type Formatable interface { - String() string - JSON() string -} diff --git a/vendor/github.com/bitrise-io/go-utils/log/print.go b/vendor/github.com/bitrise-io/go-utils/log/print.go deleted file mode 100644 index 1c817c4..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/print.go +++ /dev/null @@ -1,115 +0,0 @@ -package log - -import ( - "fmt" -) - -func printf(severity Severity, withTime bool, format string, v ...interface{}) { - message := createLogMsg(severity, withTime, format, v...) - if _, err := fmt.Fprintln(outWriter, message); err != nil { - fmt.Printf("failed to print message: %s, error: %s\n", message, err) - } -} - -func createLogMsg(severity Severity, withTime bool, format string, v ...interface{}) string { - colorFunc := severityColorFuncMap[severity] - message := colorFunc(format, v...) - if withTime { - message = prefixCurrentTime(message) - } - - return message -} - -func prefixCurrentTime(message string) string { - return fmt.Sprintf("%s %s", timestampField(), message) -} - -// Successf ... -func Successf(format string, v ...interface{}) { - printf(successSeverity, false, format, v...) -} - -// Donef ... -func Donef(format string, v ...interface{}) { - Successf(format, v...) -} - -// Infof ... -func Infof(format string, v ...interface{}) { - printf(infoSeverity, false, format, v...) -} - -// Printf ... -func Printf(format string, v ...interface{}) { - printf(normalSeverity, false, format, v...) -} - -// Debugf ... -func Debugf(format string, v ...interface{}) { - if enableDebugLog { - printf(debugSeverity, false, format, v...) - } -} - -// Warnf ... -func Warnf(format string, v ...interface{}) { - printf(warnSeverity, false, format, v...) -} - -// Errorf ... -func Errorf(format string, v ...interface{}) { - printf(errorSeverity, false, format, v...) -} - -// TSuccessf ... -func TSuccessf(format string, v ...interface{}) { - printf(successSeverity, true, format, v...) -} - -// TDonef ... -func TDonef(format string, v ...interface{}) { - TSuccessf(format, v...) -} - -// TInfof ... -func TInfof(format string, v ...interface{}) { - printf(infoSeverity, true, format, v...) -} - -// TPrintf ... -func TPrintf(format string, v ...interface{}) { - printf(normalSeverity, true, format, v...) -} - -// TDebugf ... -func TDebugf(format string, v ...interface{}) { - if enableDebugLog { - printf(debugSeverity, true, format, v...) - } -} - -// TWarnf ... -func TWarnf(format string, v ...interface{}) { - printf(warnSeverity, true, format, v...) -} - -// TErrorf ... -func TErrorf(format string, v ...interface{}) { - printf(errorSeverity, true, format, v...) -} - -// RInfof ... -func RInfof(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { - rprintf("info", stepID, tag, data, format, v...) -} - -// RWarnf ... -func RWarnf(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { - rprintf("warn", stepID, tag, data, format, v...) -} - -// RErrorf ... -func RErrorf(stepID string, tag string, data map[string]interface{}, format string, v ...interface{}) { - rprintf("error", stepID, tag, data, format, v...) -} diff --git a/vendor/github.com/bitrise-io/go-utils/log/raw_logger.go b/vendor/github.com/bitrise-io/go-utils/log/raw_logger.go deleted file mode 100644 index a673380..0000000 --- a/vendor/github.com/bitrise-io/go-utils/log/raw_logger.go +++ /dev/null @@ -1,33 +0,0 @@ -package log - -import ( - "fmt" - "io" - "os" -) - -// RawLogger ... -type RawLogger struct { - writer io.Writer -} - -// NewRawLogger ... -func NewRawLogger(writer io.Writer) *RawLogger { - return &RawLogger{ - writer: writer, - } -} - -// NewDefaultRawLogger ... -func NewDefaultRawLogger() RawLogger { - return RawLogger{ - writer: os.Stdout, - } -} - -// Print ... -func (l RawLogger) Print(f Formatable) { - if _, err := fmt.Fprintln(l.writer, f.String()); err != nil { - fmt.Printf("failed to print message: %s, error: %s\n", f.String(), err) - } -} diff --git a/vendor/github.com/bitrise-io/go-utils/log/severity.go b/vendor/github.com/bitrise-io/go-utils/log/severity.go index 4e7786d..fc1fc96 100644 --- a/vendor/github.com/bitrise-io/go-utils/log/severity.go +++ b/vendor/github.com/bitrise-io/go-utils/log/severity.go @@ -10,26 +10,26 @@ const ( warnSeverity normalSeverity infoSeverity - successSeverity + doneSeverity debugSeverity ) type severityColorFunc colorstring.ColorfFunc var ( - successSeverityColorFunc severityColorFunc = colorstring.Greenf - infoSeverityColorFunc severityColorFunc = colorstring.Bluef - normalSeverityColorFunc severityColorFunc = colorstring.NoColorf - debugSeverityColorFunc severityColorFunc = colorstring.Magentaf - warnSeverityColorFunc severityColorFunc = colorstring.Yellowf - errorSeverityColorFunc severityColorFunc = colorstring.Redf + doneSeverityColorFunc severityColorFunc = colorstring.Greenf + infoSeverityColorFunc severityColorFunc = colorstring.Bluef + normalSeverityColorFunc severityColorFunc = colorstring.NoColorf + debugSeverityColorFunc severityColorFunc = colorstring.Magentaf + warnSeverityColorFunc severityColorFunc = colorstring.Yellowf + errorSeverityColorFunc severityColorFunc = colorstring.Redf ) var severityColorFuncMap = map[Severity]severityColorFunc{ - successSeverity: successSeverityColorFunc, - infoSeverity: infoSeverityColorFunc, - normalSeverity: normalSeverityColorFunc, - debugSeverity: debugSeverityColorFunc, - warnSeverity: warnSeverityColorFunc, - errorSeverity: errorSeverityColorFunc, + doneSeverity: doneSeverityColorFunc, + infoSeverity: infoSeverityColorFunc, + normalSeverity: normalSeverityColorFunc, + debugSeverity: debugSeverityColorFunc, + warnSeverity: warnSeverityColorFunc, + errorSeverity: errorSeverityColorFunc, } diff --git a/vendor/github.com/bitrise-io/go-utils/pathutil/glob.go b/vendor/github.com/bitrise-io/go-utils/pathutil/glob.go deleted file mode 100644 index 232dd51..0000000 --- a/vendor/github.com/bitrise-io/go-utils/pathutil/glob.go +++ /dev/null @@ -1,13 +0,0 @@ -package pathutil - -// EscapeGlobPath escapes a partial path, determined at runtime, used as a parameter for filepath.Glob -func EscapeGlobPath(path string) string { - var escaped string - for _, ch := range path { - if ch == '[' || ch == ']' || ch == '-' || ch == '*' || ch == '?' || ch == '\\' { - escaped += "\\" - } - escaped += string(ch) - } - return escaped -} diff --git a/vendor/github.com/bitrise-io/go-utils/pathutil/path_filter.go b/vendor/github.com/bitrise-io/go-utils/pathutil/path_filter.go index 0bfd0fc..db0665d 100644 --- a/vendor/github.com/bitrise-io/go-utils/pathutil/path_filter.go +++ b/vendor/github.com/bitrise-io/go-utils/pathutil/path_filter.go @@ -9,6 +9,27 @@ import ( "strings" ) +// ListEntries filters contents of a directory using the provided filters +func ListEntries(dir string, filters ...FilterFunc) ([]string, error) { + absDir, err := filepath.Abs(dir) + if err != nil { + return []string{}, err + } + + entries, err := ioutil.ReadDir(absDir) + if err != nil { + return []string{}, err + } + + var paths []string + for _, entry := range entries { + pth := filepath.Join(absDir, entry.Name()) + paths = append(paths, pth) + } + + return FilterPaths(paths, filters...) +} + // FilterPaths ... func FilterPaths(fileList []string, filters ...FilterFunc) ([]string, error) { var filtered []string diff --git a/vendor/github.com/bitrise-io/go-utils/pathutil/pathutil.go b/vendor/github.com/bitrise-io/go-utils/pathutil/pathutil.go index db577e3..aeb8e22 100644 --- a/vendor/github.com/bitrise-io/go-utils/pathutil/pathutil.go +++ b/vendor/github.com/bitrise-io/go-utils/pathutil/pathutil.go @@ -10,47 +10,53 @@ import ( "strings" ) -// RevokableChangeDir ... -func RevokableChangeDir(dir string) (func() error, error) { - origDir, err := CurrentWorkingDirectoryAbsolutePath() - if err != nil { - return nil, err - } - - revokeFn := func() error { - return os.Chdir(origDir) - } +// +// Path provider functions - return revokeFn, os.Chdir(dir) +// PathProvider ... +type PathProvider interface { + CreateTempDir(prefix string) (string, error) } -// ChangeDirForFunction ... -func ChangeDirForFunction(dir string, fn func()) error { - revokeFn, err := RevokableChangeDir(dir) - if err != nil { - return err - } +type defaultPathProvider struct{} - fn() +// NewPathProvider ... +func NewPathProvider() PathProvider { + return defaultPathProvider{} +} - return revokeFn() +func (defaultPathProvider) CreateTempDir(prefix string) (string, error) { + return NormalizedOSTempDirPath(prefix) } -// IsRelativePath ... -func IsRelativePath(pth string) bool { - if strings.HasPrefix(pth, "./") { - return true +// NormalizedOSTempDirPath ... +// Creates a temp dir, and returns its path. +// If tmpDirNamePrefix is provided it'll be used +// as the tmp dir's name prefix. +// Normalized: it's guaranteed that the path won't end with '/'. +func NormalizedOSTempDirPath(tmpDirNamePrefix string) (retPth string, err error) { + retPth, err = ioutil.TempDir("", tmpDirNamePrefix) + if strings.HasSuffix(retPth, "/") { + retPth = retPth[:len(retPth)-1] } + return +} - if strings.HasPrefix(pth, "/") { - return false - } +// CurrentWorkingDirectoryAbsolutePath ... +func CurrentWorkingDirectoryAbsolutePath() (string, error) { + return filepath.Abs("./") +} - if strings.HasPrefix(pth, "$") { - return false +// UserHomeDir ... +func UserHomeDir() string { + if runtime.GOOS == "windows" { + home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") + if home == "" { + home = os.Getenv("USERPROFILE") + } + return home } - - return true + return os.Getenv("HOME") } // EnsureDirExist ... @@ -62,6 +68,25 @@ func EnsureDirExist(dir string) error { return nil } +// +// Path checker functions + +// PathChecker ... +type PathChecker interface { + IsPathExists(pth string) (bool, error) +} + +type defaultPathChecker struct{} + +// NewPathChecker ... +func NewPathChecker() PathChecker { + return defaultPathChecker{} +} + +func (c defaultPathChecker) IsPathExists(pth string) (bool, error) { + return IsPathExists(pth) +} + func genericIsPathExists(pth string) (os.FileInfo, bool, error) { if pth == "" { return nil, false, errors.New("No path provided") @@ -76,12 +101,6 @@ func genericIsPathExists(pth string) (os.FileInfo, bool, error) { return fileInf, false, err } -// IsPathExists ... -func IsPathExists(pth string) (bool, error) { - _, isExists, err := genericIsPathExists(pth) - return isExists, err -} - // PathCheckAndInfos ... // Returns: // 1. file info or nil @@ -106,6 +125,32 @@ func IsDirExists(pth string) (bool, error) { return fileInf.IsDir(), nil } +// IsPathExists ... +func IsPathExists(pth string) (bool, error) { + _, isExists, err := genericIsPathExists(pth) + return isExists, err +} + +// +// Path modifier functions + +// PathModifier ... +type PathModifier interface { + AbsPath(pth string) (string, error) +} + +type defaultPathModifier struct{} + +// NewPathModifier ... +func NewPathModifier() PathModifier { + return defaultPathModifier{} +} + +// AbsPath ... +func (defaultPathModifier) AbsPath(pth string) (string, error) { + return AbsPath(pth) +} + // AbsPath expands ENV vars and the ~ character // then call Go's Abs func AbsPath(pth string) (string, error) { @@ -150,34 +195,21 @@ func ExpandTilde(pth string) (string, error) { return pth, nil } -// CurrentWorkingDirectoryAbsolutePath ... -func CurrentWorkingDirectoryAbsolutePath() (string, error) { - return filepath.Abs("./") -} +// IsRelativePath ... +func IsRelativePath(pth string) bool { + if strings.HasPrefix(pth, "./") { + return true + } -// UserHomeDir ... -func UserHomeDir() string { - if runtime.GOOS == "windows" { - home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") - if home == "" { - home = os.Getenv("USERPROFILE") - } - return home + if strings.HasPrefix(pth, "/") { + return false } - return os.Getenv("HOME") -} -// NormalizedOSTempDirPath ... -// Creates a temp dir, and returns its path. -// If tmpDirNamePrefix is provided it'll be used -// as the tmp dir's name prefix. -// Normalized: it's guaranteed that the path won't end with '/'. -func NormalizedOSTempDirPath(tmpDirNamePrefix string) (retPth string, err error) { - retPth, err = ioutil.TempDir("", tmpDirNamePrefix) - if strings.HasSuffix(retPth, "/") { - retPth = retPth[:len(retPth)-1] + if strings.HasPrefix(pth, "$") { + return false } - return + + return true } // GetFileName returns the name of the file from a given path or the name of the directory if it is a directory @@ -185,54 +217,43 @@ func GetFileName(path string) string { return strings.TrimSuffix(filepath.Base(path), filepath.Ext(path)) } -// ListPathInDirSortedByComponents ... -func ListPathInDirSortedByComponents(searchDir string, relPath bool) ([]string, error) { - searchDir, err := filepath.Abs(searchDir) - if err != nil { - return []string{}, err - } - - var fileList []string - - if err := filepath.Walk(searchDir, func(path string, _ os.FileInfo, walkErr error) error { - if walkErr != nil { - return walkErr +// EscapeGlobPath escapes a partial path, determined at runtime, used as a parameter for filepath.Glob +func EscapeGlobPath(path string) string { + var escaped string + for _, ch := range path { + if ch == '[' || ch == ']' || ch == '-' || ch == '*' || ch == '?' || ch == '\\' { + escaped += "\\" } - - if relPath { - rel, err := filepath.Rel(searchDir, path) - if err != nil { - return err - } - path = rel - } - - fileList = append(fileList, path) - - return nil - }); err != nil { - return []string{}, err + escaped += string(ch) } - return SortPathsByComponents(fileList) + return escaped } -// ListEntries filters contents of a directory using the provided filters -func ListEntries(dir string, filters ...FilterFunc) ([]string, error) { - absDir, err := filepath.Abs(dir) +// +// Change dir functions + +// RevokableChangeDir ... +func RevokableChangeDir(dir string) (func() error, error) { + origDir, err := CurrentWorkingDirectoryAbsolutePath() if err != nil { - return []string{}, err + return nil, err } - entries, err := ioutil.ReadDir(absDir) - if err != nil { - return []string{}, err + revokeFn := func() error { + return os.Chdir(origDir) } - var paths []string - for _, entry := range entries { - pth := filepath.Join(absDir, entry.Name()) - paths = append(paths, pth) + return revokeFn, os.Chdir(dir) +} + +// ChangeDirForFunction ... +func ChangeDirForFunction(dir string, fn func()) error { + revokeFn, err := RevokableChangeDir(dir) + if err != nil { + return err } - return FilterPaths(paths, filters...) + fn() + + return revokeFn() } diff --git a/vendor/github.com/bitrise-io/go-utils/pathutil/sortable_path.go b/vendor/github.com/bitrise-io/go-utils/pathutil/sortable_path.go index 4bed6bf..97f63c3 100644 --- a/vendor/github.com/bitrise-io/go-utils/pathutil/sortable_path.go +++ b/vendor/github.com/bitrise-io/go-utils/pathutil/sortable_path.go @@ -7,6 +7,37 @@ import ( "strings" ) +// ListPathInDirSortedByComponents ... +func ListPathInDirSortedByComponents(searchDir string, relPath bool) ([]string, error) { + searchDir, err := filepath.Abs(searchDir) + if err != nil { + return []string{}, err + } + + var fileList []string + + if err := filepath.Walk(searchDir, func(path string, _ os.FileInfo, walkErr error) error { + if walkErr != nil { + return walkErr + } + + if relPath { + rel, err := filepath.Rel(searchDir, path) + if err != nil { + return err + } + path = rel + } + + fileList = append(fileList, path) + + return nil + }); err != nil { + return []string{}, err + } + return SortPathsByComponents(fileList) +} + // SortablePath ... type SortablePath struct { Pth string diff --git a/vendor/github.com/bitrise-io/go-utils/ziputil/ziputil.go b/vendor/github.com/bitrise-io/go-utils/ziputil/ziputil.go index 29a6252..141fbe9 100644 --- a/vendor/github.com/bitrise-io/go-utils/ziputil/ziputil.go +++ b/vendor/github.com/bitrise-io/go-utils/ziputil/ziputil.go @@ -2,6 +2,7 @@ package ziputil import ( "fmt" + "github.com/bitrise-io/go-utils/env" "path/filepath" "github.com/bitrise-io/go-utils/command" @@ -29,8 +30,9 @@ func ZipDir(sourceDirPth, destinationZipPth string, isContentOnly bool) error { // -r - Travel the directory structure recursively // -T - Test the integrity of the new zip file // -y - Store symbolic links as such in the zip archive, instead of compressing and storing the file referred to by the link - cmd := command.New("/usr/bin/zip", "-rTy", destinationZipPth, zipTarget) - cmd.SetDir(workDir) + opts := &command.Opts{Dir: workDir} + factory := command.NewFactory(env.NewRepository()) + cmd := factory.Create("/usr/bin/zip", []string{"-rTy", destinationZipPth, zipTarget}, opts) if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil { return fmt.Errorf("command: (%s) failed, output: %s, error: %s", cmd.PrintableCommandArgs(), out, err) } @@ -51,8 +53,9 @@ func ZipFile(sourceFilePth, destinationZipPth string) error { // -T - Test the integrity of the new zip file // -y - Store symbolic links as such in the zip archive, instead of compressing and storing the file referred to by the link - cmd := command.New("/usr/bin/zip", "-Ty", destinationZipPth, zipTarget) - cmd.SetDir(workDir) + opts := &command.Opts{Dir: workDir} + factory := command.NewFactory(env.NewRepository()) + cmd := factory.Create("/usr/bin/zip", []string{"-Ty", destinationZipPth, zipTarget}, opts) if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil { return fmt.Errorf("command: (%s) failed, output: %s, error: %s", cmd.PrintableCommandArgs(), out, err) } @@ -62,7 +65,8 @@ func ZipFile(sourceFilePth, destinationZipPth string) error { // UnZip ... func UnZip(zip, intoDir string) error { - cmd := command.New("/usr/bin/unzip", zip, "-d", intoDir) + factory := command.NewFactory(env.NewRepository()) + cmd := factory.Create("/usr/bin/unzip", []string{zip, "-d", intoDir}, nil) if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil { return fmt.Errorf("command: (%s) failed, output: %s, error: %s", cmd.PrintableCommandArgs(), out, err) } diff --git a/vendor/modules.txt b/vendor/modules.txt index 7d526e9..4908195 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,16 +1,17 @@ -# github.com/bitrise-io/go-android v0.0.0-20210527143215-3ad22ad02e2e +# github.com/bitrise-io/go-android v0.0.0-20211022134605-85247bb2c5c6 ## explicit github.com/bitrise-io/go-android/cache github.com/bitrise-io/go-android/gradle -# github.com/bitrise-io/go-steputils v0.0.0-20210527075147-910ce7a105a1 +# github.com/bitrise-io/go-steputils v0.0.0-20210819160244-b3962254d553 ## explicit github.com/bitrise-io/go-steputils/cache github.com/bitrise-io/go-steputils/stepconf github.com/bitrise-io/go-steputils/tools -# github.com/bitrise-io/go-utils v0.0.0-20210520073355-367fa34178f5 +# github.com/bitrise-io/go-utils v0.0.0-20211008161027-fa11986847a0 ## explicit github.com/bitrise-io/go-utils/colorstring github.com/bitrise-io/go-utils/command +github.com/bitrise-io/go-utils/env github.com/bitrise-io/go-utils/errorutil github.com/bitrise-io/go-utils/fileutil github.com/bitrise-io/go-utils/log