From 8d7dbb9167362c086d28f794c44a9b150bab4b5e Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Thu, 28 Oct 2021 12:17:08 -0500 Subject: [PATCH 01/15] wip: initial restructure Signed-off-by: Javier Romero --- benchmarks/build_test.go | 4 +- cmd/cmd.go | 47 +- cmd/docker_init.go | 8 +- cmd/pack/main.go | 4 +- .../builder/fakes/fake_inspectable_fetcher.go | 4 +- internal/builder/image_fetcher_wrapper.go | 2 +- internal/builder/inspect.go | 4 +- internal/builder/inspect_test.go | 2 +- internal/builder/lifecycle_test.go | 2 +- internal/builder/testmocks/mock_lifecycle.go | 22 +- internal/builder/writer/factory.go | 4 +- internal/builder/writer/human_readable.go | 8 +- .../builder/writer/human_readable_test.go | 13 +- internal/builder/writer/json_test.go | 13 +- internal/builder/writer/structured_format.go | 4 +- internal/builder/writer/toml_test.go | 13 +- internal/builder/writer/yaml_test.go | 13 +- internal/buildpackage/builder_test.go | 2 +- internal/buildpackage/oci_layout_package.go | 2 +- .../buildpackage/oci_layout_package_test.go | 2 +- internal/commands/build.go | 16 +- internal/commands/build_test.go | 40 +- internal/commands/builder_create.go | 10 +- internal/commands/builder_inspect.go | 10 +- internal/commands/builder_inspect_test.go | 16 +- internal/commands/builder_suggest_test.go | 6 +- internal/commands/buildpack_inspect.go | 10 +- internal/commands/buildpack_inspect_test.go | 68 ++- internal/commands/buildpack_new.go | 8 +- internal/commands/buildpack_new_test.go | 4 +- internal/commands/buildpack_package.go | 18 +- internal/commands/buildpack_package_test.go | 2 +- internal/commands/buildpack_pull.go | 8 +- internal/commands/buildpack_pull_test.go | 4 +- internal/commands/buildpack_register.go | 8 +- internal/commands/buildpack_register_test.go | 8 +- internal/commands/buildpack_yank.go | 8 +- internal/commands/buildpack_yank_test.go | 10 +- internal/commands/commands.go | 28 +- .../commands/config_default_builder_test.go | 12 +- internal/commands/config_pull_policy.go | 2 +- internal/commands/create_builder.go | 8 +- .../commands/fakes/fake_builder_inspector.go | 20 +- .../commands/fakes/fake_builder_writer.go | 8 +- .../commands/fakes/fake_buildpack_packager.go | 6 +- .../fakes/fake_inspect_image_writer.go | 8 +- internal/commands/inspect_builder.go | 7 +- internal/commands/inspect_builder_test.go | 6 +- internal/commands/inspect_buildpack.go | 23 +- internal/commands/inspect_buildpack_test.go | 72 ++- internal/commands/inspect_image_test.go | 10 +- internal/commands/package_buildpack.go | 8 +- internal/commands/package_buildpack_test.go | 2 +- internal/commands/rebase.go | 10 +- internal/commands/rebase_test.go | 8 +- internal/commands/register_buildpack.go | 8 +- internal/commands/register_buildpack_test.go | 8 +- internal/commands/set_default_builder_test.go | 10 +- internal/commands/suggest_builders_test.go | 6 +- .../mock_inspect_image_writer_factory.go | 18 +- .../commands/testmocks/mock_pack_client.go | 86 ++-- internal/commands/yank_buildpack.go | 11 +- internal/commands/yank_buildpack_test.go | 10 +- internal/dist/testmocks/mock_buildpack.go | 22 +- internal/fakes/fake_image_fetcher.go | 4 +- internal/inspectimage/bom_display.go | 4 +- internal/inspectimage/info_display.go | 10 +- internal/inspectimage/writer/bom_json_test.go | 10 +- internal/inspectimage/writer/bom_yaml_test.go | 10 +- internal/inspectimage/writer/factory.go | 4 +- .../inspectimage/writer/human_readable.go | 4 +- .../writer/human_readable_test.go | 14 +- internal/inspectimage/writer/json_test.go | 14 +- .../writer/structured_bom_format.go | 4 +- .../writer/structured_bom_format_test.go | 10 +- .../inspectimage/writer/structured_format.go | 4 +- .../writer/structured_format_test.go | 16 +- internal/inspectimage/writer/toml_test.go | 14 +- internal/inspectimage/writer/yaml_test.go | 14 +- logging/logging.go | 2 +- pack.go | 31 -- {internal => pkg}/blob/blob.go | 0 {internal => pkg}/blob/blob_test.go | 2 +- {internal => pkg}/blob/downloader.go | 0 {internal => pkg}/blob/downloader_test.go | 6 +- {internal => pkg}/blob/testdata/blob/file.txt | 0 .../blob/testdata/buildpack/buildpack.toml | 0 .../blob/testdata/lifecycle/analyzer | 0 .../blob/testdata/lifecycle/builder | 0 .../blob/testdata/lifecycle/cacher | 0 .../blob/testdata/lifecycle/detector | 0 .../blob/testdata/lifecycle/exporter | 0 .../blob/testdata/lifecycle/launcher | 0 .../blob/testdata/lifecycle/restorer | 0 .../downloader/buildpack_downloader.go | 92 +++- .../downloader/buildpack_downloader_test.go | 185 ++++--- .../downloader/testdata/buildpack/bin/build | 1 + .../downloader/testdata/buildpack/bin/detect | 0 .../testdata/buildpack/buildpack.toml | 10 + build.go => pkg/client/build.go | 39 +- build_test.go => pkg/client/build_test.go | 19 +- client.go => pkg/client/client.go | 57 +- client_test.go => pkg/client/client_test.go | 4 +- common.go => pkg/client/common.go | 2 +- common_test.go => pkg/client/common_test.go | 2 +- .../client/create_builder.go | 9 +- .../client/create_builder_test.go | 79 +-- doc.go => pkg/client/doc.go | 2 +- doc_test.go => pkg/client/doc_test.go | 10 +- errors.go => pkg/client/errors.go | 2 +- .../client/inspect_builder.go | 6 +- .../client/inspect_builder_test.go | 8 +- .../client/inspect_buildpack.go | 6 +- .../client/inspect_buildpack_test.go | 66 ++- .../client/inspect_image.go | 6 +- .../client/inspect_image_test.go | 8 +- .../client/new_buildpack.go | 2 +- .../client/new_buildpack_test.go | 12 +- pkg/client/pack.go | 6 + .../client/package_buildpack.go | 93 +--- .../client/package_buildpack_test.go | 130 ++--- .../client/pull_buildpack.go | 6 +- .../client/pull_buildpack_test.go | 34 +- rebase.go => pkg/client/rebase.go | 6 +- rebase_test.go => pkg/client/rebase_test.go | 5 +- .../client/register_buildpack.go | 6 +- .../client/register_buildpack_test.go | 9 +- pkg/client/testdata/builder.toml | 31 ++ .../testdata/buildpack-api-0.4/bin/build | 1 + .../testdata/buildpack-api-0.4/bin/detect | 0 .../testdata/buildpack-api-0.4/buildpack.toml | 10 + pkg/client/testdata/buildpack/bin/build | 1 + pkg/client/testdata/buildpack/bin/detect | 0 pkg/client/testdata/buildpack/buildpack.toml | 10 + pkg/client/testdata/buildpack2/bin/build | 0 pkg/client/testdata/buildpack2/bin/detect | 0 pkg/client/testdata/buildpack2/buildpack.toml | 9 + pkg/client/testdata/downloader/dirA/file.txt | 1 + pkg/client/testdata/empty-file | 0 pkg/client/testdata/jar-file.jar | Bin 0 -> 739 bytes pkg/client/testdata/just-a-file.txt | 0 .../lifecycle-v0.0.0-arch/analyzer | 1 + .../lifecycle-v0.0.0-arch/builder | 1 + .../lifecycle-v0.0.0-arch/creator | 1 + .../lifecycle-v0.0.0-arch/detector | 1 + .../lifecycle-v0.0.0-arch/exporter | 1 + .../lifecycle-v0.0.0-arch/launcher | 1 + .../lifecycle-v0.0.0-arch/restorer | 1 + .../lifecycle/platform-0.3/lifecycle.toml | 6 + .../lifecycle-v0.0.0-arch/analyzer | 1 + .../lifecycle-v0.0.0-arch/builder | 1 + .../lifecycle-v0.0.0-arch/creator | 1 + .../lifecycle-v0.0.0-arch/detector | 1 + .../lifecycle-v0.0.0-arch/exporter | 1 + .../lifecycle-v0.0.0-arch/launcher | 1 + .../lifecycle-v0.0.0-arch/restorer | 1 + .../lifecycle/platform-0.4/lifecycle.toml | 11 + pkg/client/testdata/non-zip-file | 1 + pkg/client/testdata/registry/3/fo/example_foo | 3 + .../testdata/registry/ja/va/example_java | 1 + pkg/client/testdata/some-app/.gitignore | 1 + pkg/client/testdata/zip-file.zip | Bin 0 -> 510 bytes .../client/yank_buildpack.go | 2 +- .../client/yank_buildpack_test.go | 2 +- {config => pkg/config}/pull_policy.go | 0 {config => pkg/config}/pull_policy_test.go | 2 +- {internal => pkg}/image/factory.go | 0 {internal => pkg}/image/fetcher.go | 2 +- {internal => pkg}/image/fetcher_test.go | 4 +- .../testmocks/mock_buildpack_downloader.go | 25 +- .../testmocks}/mock_docker_client.go | 487 +++++++++--------- .../testmocks}/mock_downloader.go | 20 +- {testmocks => pkg/testmocks}/mock_image.go | 0 .../testmocks}/mock_image_factory.go | 17 +- .../testmocks}/mock_image_fetcher.go | 20 +- pkg/testmocks/mock_registry_resolver.go | 48 ++ 176 files changed, 1374 insertions(+), 1298 deletions(-) delete mode 100644 pack.go rename {internal => pkg}/blob/blob.go (100%) rename {internal => pkg}/blob/blob_test.go (96%) rename {internal => pkg}/blob/downloader.go (100%) rename {internal => pkg}/blob/downloader_test.go (97%) rename {internal => pkg}/blob/testdata/blob/file.txt (100%) rename {internal => pkg}/blob/testdata/buildpack/buildpack.toml (100%) rename {internal => pkg}/blob/testdata/lifecycle/analyzer (100%) rename {internal => pkg}/blob/testdata/lifecycle/builder (100%) rename {internal => pkg}/blob/testdata/lifecycle/cacher (100%) rename {internal => pkg}/blob/testdata/lifecycle/detector (100%) rename {internal => pkg}/blob/testdata/lifecycle/exporter (100%) rename {internal => pkg}/blob/testdata/lifecycle/launcher (100%) rename {internal => pkg}/blob/testdata/lifecycle/restorer (100%) rename buildpack_downloader.go => pkg/buildpack/downloader/buildpack_downloader.go (50%) rename buildpack_downloader_test.go => pkg/buildpack/downloader/buildpack_downloader_test.go (70%) create mode 100644 pkg/buildpack/downloader/testdata/buildpack/bin/build create mode 100644 pkg/buildpack/downloader/testdata/buildpack/bin/detect create mode 100644 pkg/buildpack/downloader/testdata/buildpack/buildpack.toml rename build.go => pkg/client/build.go (95%) rename build_test.go => pkg/client/build_test.go (99%) rename client.go => pkg/client/client.go (75%) rename client_test.go => pkg/client/client_test.go (98%) rename common.go => pkg/client/common.go (99%) rename common_test.go => pkg/client/common_test.go (99%) rename create_builder.go => pkg/client/create_builder.go (96%) rename create_builder_test.go => pkg/client/create_builder_test.go (93%) rename doc.go => pkg/client/doc.go (97%) rename doc_test.go => pkg/client/doc_test.go (87%) rename errors.go => pkg/client/errors.go (97%) rename inspect_builder.go => pkg/client/inspect_builder.go (97%) rename inspect_builder_test.go => pkg/client/inspect_builder_test.go (98%) rename inspect_buildpack.go => pkg/client/inspect_buildpack.go (98%) rename inspect_buildpack_test.go => pkg/client/inspect_buildpack_test.go (94%) rename inspect_image.go => pkg/client/inspect_image.go (98%) rename inspect_image_test.go => pkg/client/inspect_image_test.go (99%) rename new_buildpack.go => pkg/client/new_buildpack.go (99%) rename new_buildpack_test.go => pkg/client/new_buildpack_test.go (92%) create mode 100644 pkg/client/pack.go rename package_buildpack.go => pkg/client/package_buildpack.go (57%) rename package_buildpack_test.go => pkg/client/package_buildpack_test.go (87%) rename pull_buildpack.go => pkg/client/pull_buildpack.go (95%) rename pull_buildpack_test.go => pkg/client/pull_buildpack_test.go (81%) rename rebase.go => pkg/client/rebase.go (96%) rename rebase_test.go => pkg/client/rebase_test.go (99%) rename register_buildpack.go => pkg/client/register_buildpack.go (96%) rename register_buildpack_test.go => pkg/client/register_buildpack_test.go (99%) create mode 100644 pkg/client/testdata/builder.toml create mode 100644 pkg/client/testdata/buildpack-api-0.4/bin/build create mode 100644 pkg/client/testdata/buildpack-api-0.4/bin/detect create mode 100644 pkg/client/testdata/buildpack-api-0.4/buildpack.toml create mode 100644 pkg/client/testdata/buildpack/bin/build create mode 100644 pkg/client/testdata/buildpack/bin/detect create mode 100644 pkg/client/testdata/buildpack/buildpack.toml create mode 100644 pkg/client/testdata/buildpack2/bin/build create mode 100644 pkg/client/testdata/buildpack2/bin/detect create mode 100644 pkg/client/testdata/buildpack2/buildpack.toml create mode 100644 pkg/client/testdata/downloader/dirA/file.txt create mode 100644 pkg/client/testdata/empty-file create mode 100644 pkg/client/testdata/jar-file.jar create mode 100644 pkg/client/testdata/just-a-file.txt create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/analyzer create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/builder create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/creator create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/detector create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/exporter create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/launcher create mode 100755 pkg/client/testdata/lifecycle/platform-0.3/lifecycle-v0.0.0-arch/restorer create mode 100644 pkg/client/testdata/lifecycle/platform-0.3/lifecycle.toml create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/analyzer create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/builder create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/creator create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/detector create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/exporter create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/launcher create mode 100755 pkg/client/testdata/lifecycle/platform-0.4/lifecycle-v0.0.0-arch/restorer create mode 100644 pkg/client/testdata/lifecycle/platform-0.4/lifecycle.toml create mode 100644 pkg/client/testdata/non-zip-file create mode 100644 pkg/client/testdata/registry/3/fo/example_foo create mode 100644 pkg/client/testdata/registry/ja/va/example_java create mode 100644 pkg/client/testdata/some-app/.gitignore create mode 100644 pkg/client/testdata/zip-file.zip rename yank_buildpack.go => pkg/client/yank_buildpack.go (98%) rename yank_buildpack_test.go => pkg/client/yank_buildpack_test.go (99%) rename {config => pkg/config}/pull_policy.go (100%) rename {config => pkg/config}/pull_policy_test.go (97%) rename {internal => pkg}/image/factory.go (100%) rename {internal => pkg}/image/fetcher.go (99%) rename {internal => pkg}/image/fetcher_test.go (99%) rename mock_buildpack_downloader.go => pkg/testmocks/mock_buildpack_downloader.go (76%) rename {testmocks => pkg/testmocks}/mock_docker_client.go (87%) rename {testmocks => pkg/testmocks}/mock_downloader.go (79%) rename {testmocks => pkg/testmocks}/mock_image.go (100%) rename {testmocks => pkg/testmocks}/mock_image_factory.go (82%) rename {testmocks => pkg/testmocks}/mock_image_fetcher.go (80%) create mode 100644 pkg/testmocks/mock_registry_resolver.go diff --git a/benchmarks/build_test.go b/benchmarks/build_test.go index 05fc145736..14a2675737 100644 --- a/benchmarks/build_test.go +++ b/benchmarks/build_test.go @@ -12,10 +12,10 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" cfg "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -77,7 +77,7 @@ func BenchmarkBuild(b *testing.B) { func createCmd(b *testing.B, docker *dockerCli.Client) *cobra.Command { outBuf := bytes.Buffer{} logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) - packClient, err := pack.NewClient(pack.WithLogger(logger), pack.WithDockerClient(docker), pack.WithExperimental(true)) + packClient, err := client.NewClient(client.WithLogger(logger), client.WithDockerClient(docker), client.WithExperimental(true)) if err != nil { b.Error(errors.Wrap(err, "creating packClient")) } diff --git a/cmd/cmd.go b/cmd/cmd.go index 507e4f834e..637f612a58 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -5,7 +5,6 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/buildpackage" builderwriter "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/commands" @@ -13,6 +12,7 @@ import ( imagewriter "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) // ConfigurableLogger defines behavior required by the PackCommand @@ -72,34 +72,34 @@ func NewPackCommand(logger ConfigurableLogger) (*cobra.Command, error) { commands.AddHelpFlag(rootCmd, "pack") - rootCmd.AddCommand(commands.Build(logger, cfg, &packClient)) - rootCmd.AddCommand(commands.NewBuilderCommand(logger, cfg, &packClient)) - rootCmd.AddCommand(commands.NewBuildpackCommand(logger, cfg, &packClient, buildpackage.NewConfigReader())) - rootCmd.AddCommand(commands.NewConfigCommand(logger, cfg, cfgPath, &packClient)) - rootCmd.AddCommand(commands.InspectImage(logger, imagewriter.NewFactory(), cfg, &packClient)) + rootCmd.AddCommand(commands.Build(logger, cfg, packClient)) + rootCmd.AddCommand(commands.NewBuilderCommand(logger, cfg, packClient)) + rootCmd.AddCommand(commands.NewBuildpackCommand(logger, cfg, packClient, buildpackage.NewConfigReader())) + rootCmd.AddCommand(commands.NewConfigCommand(logger, cfg, cfgPath, packClient)) + rootCmd.AddCommand(commands.InspectImage(logger, imagewriter.NewFactory(), cfg, packClient)) rootCmd.AddCommand(commands.NewStackCommand(logger)) - rootCmd.AddCommand(commands.Rebase(logger, cfg, &packClient)) + rootCmd.AddCommand(commands.Rebase(logger, cfg, packClient)) - rootCmd.AddCommand(commands.InspectBuildpack(logger, cfg, &packClient)) - rootCmd.AddCommand(commands.InspectBuilder(logger, cfg, &packClient, builderwriter.NewFactory())) + rootCmd.AddCommand(commands.InspectBuildpack(logger, cfg, packClient)) + rootCmd.AddCommand(commands.InspectBuilder(logger, cfg, packClient, builderwriter.NewFactory())) - rootCmd.AddCommand(commands.SetDefaultBuilder(logger, cfg, cfgPath, &packClient)) + rootCmd.AddCommand(commands.SetDefaultBuilder(logger, cfg, cfgPath, packClient)) rootCmd.AddCommand(commands.SetRunImagesMirrors(logger, cfg, cfgPath)) - rootCmd.AddCommand(commands.SuggestBuilders(logger, &packClient)) + rootCmd.AddCommand(commands.SuggestBuilders(logger, packClient)) rootCmd.AddCommand(commands.TrustBuilder(logger, cfg, cfgPath)) rootCmd.AddCommand(commands.UntrustBuilder(logger, cfg, cfgPath)) rootCmd.AddCommand(commands.ListTrustedBuilders(logger, cfg)) - rootCmd.AddCommand(commands.CreateBuilder(logger, cfg, &packClient)) - rootCmd.AddCommand(commands.PackageBuildpack(logger, cfg, &packClient, buildpackage.NewConfigReader())) + rootCmd.AddCommand(commands.CreateBuilder(logger, cfg, packClient)) + rootCmd.AddCommand(commands.PackageBuildpack(logger, cfg, packClient, buildpackage.NewConfigReader())) rootCmd.AddCommand(commands.SuggestStacks(logger)) if cfg.Experimental { rootCmd.AddCommand(commands.AddBuildpackRegistry(logger, cfg, cfgPath)) rootCmd.AddCommand(commands.ListBuildpackRegistries(logger, cfg)) - rootCmd.AddCommand(commands.RegisterBuildpack(logger, cfg, &packClient)) + rootCmd.AddCommand(commands.RegisterBuildpack(logger, cfg, packClient)) rootCmd.AddCommand(commands.SetDefaultRegistry(logger, cfg, cfgPath)) rootCmd.AddCommand(commands.RemoveRegistry(logger, cfg, cfgPath)) - rootCmd.AddCommand(commands.YankBuildpack(logger, cfg, &packClient)) + rootCmd.AddCommand(commands.YankBuildpack(logger, cfg, packClient)) } packHome, err := config.PackHome() @@ -108,10 +108,10 @@ func NewPackCommand(logger ConfigurableLogger) (*cobra.Command, error) { } rootCmd.AddCommand(commands.CompletionCommand(logger, packHome)) - rootCmd.AddCommand(commands.Report(logger, pack.Version, cfgPath)) - rootCmd.AddCommand(commands.Version(logger, pack.Version)) + rootCmd.AddCommand(commands.Report(logger, client.Version, cfgPath)) + rootCmd.AddCommand(commands.Version(logger, client.Version)) - rootCmd.Version = pack.Version + rootCmd.Version = client.Version rootCmd.SetVersionTemplate(`{{.Version}}{{"\n"}}`) rootCmd.SetOut(logging.GetWriterForLevel(logger, logging.InfoLevel)) rootCmd.SetErr(logging.GetWriterForLevel(logger, logging.ErrorLevel)) @@ -132,15 +132,10 @@ func initConfig() (config.Config, string, error) { return cfg, path, nil } -func initClient(logger logging.Logger, cfg config.Config) (pack.Client, error) { +func initClient(logger logging.Logger, cfg config.Config) (*client.Client, error) { dc, err := tryInitSSHDockerClient() if err != nil { - return pack.Client{}, err - } - client, err := pack.NewClient(pack.WithLogger(logger), pack.WithExperimental(cfg.Experimental), pack.WithRegistryMirrors(cfg.RegistryMirrors), pack.WithDockerClient(dc)) - if err != nil { - return pack.Client{}, err + return nil, err } - - return *client, nil + return client.NewClient(client.WithLogger(logger), client.WithExperimental(cfg.Experimental), client.WithRegistryMirrors(cfg.RegistryMirrors), client.WithDockerClient(dc)) } diff --git a/cmd/docker_init.go b/cmd/docker_init.go index 2a2f7d41a9..51b33527c5 100644 --- a/cmd/docker_init.go +++ b/cmd/docker_init.go @@ -12,12 +12,12 @@ import ( "os" "strings" - "github.com/buildpacks/pack" - "github.com/buildpacks/pack/internal/sshdialer" - dockerClient "github.com/docker/docker/client" "golang.org/x/crypto/ssh" "golang.org/x/term" + + "github.com/buildpacks/pack/internal/sshdialer" + "github.com/buildpacks/pack/pkg/client" ) func tryInitSSHDockerClient() (dockerClient.CommonAPIClient, error) { @@ -50,7 +50,7 @@ func tryInitSSHDockerClient() (dockerClient.CommonAPIClient, error) { } dockerClientOpts := []dockerClient.Opt{ - dockerClient.WithVersion(pack.DockerAPIVersion), + dockerClient.WithVersion(client.DockerAPIVersion), dockerClient.WithHTTPClient(httpClient), dockerClient.WithHost("http://dummy/"), dockerClient.WithDialContext(dialContext), diff --git a/cmd/pack/main.go b/cmd/pack/main.go index d958d37bb1..ee08a28ff1 100644 --- a/cmd/pack/main.go +++ b/cmd/pack/main.go @@ -6,8 +6,8 @@ import ( "github.com/heroku/color" "github.com/buildpacks/pack/cmd" + "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" clilogger "github.com/buildpacks/pack/internal/logging" ) @@ -24,7 +24,7 @@ func main() { ctx := commands.CreateCancellableContext() if err := rootCmd.ExecuteContext(ctx); err != nil { - if _, isSoftError := err.(pack.SoftError); isSoftError { + if _, isSoftError := err.(client.SoftError); isSoftError { os.Exit(2) } os.Exit(1) diff --git a/internal/builder/fakes/fake_inspectable_fetcher.go b/internal/builder/fakes/fake_inspectable_fetcher.go index 968930e985..2f7125735b 100644 --- a/internal/builder/fakes/fake_inspectable_fetcher.go +++ b/internal/builder/fakes/fake_inspectable_fetcher.go @@ -3,9 +3,9 @@ package fakes import ( "context" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) type FakeInspectableFetcher struct { diff --git a/internal/builder/image_fetcher_wrapper.go b/internal/builder/image_fetcher_wrapper.go index d7657e129a..dfb0de4a83 100644 --- a/internal/builder/image_fetcher_wrapper.go +++ b/internal/builder/image_fetcher_wrapper.go @@ -5,7 +5,7 @@ import ( "github.com/buildpacks/imgutil" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/image" ) type ImageFetcher interface { diff --git a/internal/builder/inspect.go b/internal/builder/inspect.go index 3cc3a8c63c..331a3a4fc7 100644 --- a/internal/builder/inspect.go +++ b/internal/builder/inspect.go @@ -7,9 +7,9 @@ import ( "strings" pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) type Info struct { diff --git a/internal/builder/inspect_test.go b/internal/builder/inspect_test.go index 5fefc2a1c5..df183ee1a1 100644 --- a/internal/builder/inspect_test.go +++ b/internal/builder/inspect_test.go @@ -7,10 +7,10 @@ import ( "github.com/buildpacks/lifecycle/api" pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/fakes" "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/config" h "github.com/buildpacks/pack/testhelpers" "github.com/heroku/color" diff --git a/internal/builder/lifecycle_test.go b/internal/builder/lifecycle_test.go index 8f5d2f8a87..d7d8b90dda 100644 --- a/internal/builder/lifecycle_test.go +++ b/internal/builder/lifecycle_test.go @@ -12,8 +12,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/builder" + "github.com/buildpacks/pack/pkg/blob" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/builder/testmocks/mock_lifecycle.go b/internal/builder/testmocks/mock_lifecycle.go index 88aacd786f..258909b72e 100644 --- a/internal/builder/testmocks/mock_lifecycle.go +++ b/internal/builder/testmocks/mock_lifecycle.go @@ -5,38 +5,36 @@ package testmocks import ( + builder "github.com/buildpacks/pack/internal/builder" + gomock "github.com/golang/mock/gomock" io "io" reflect "reflect" - - gomock "github.com/golang/mock/gomock" - - builder "github.com/buildpacks/pack/internal/builder" ) -// MockLifecycle is a mock of Lifecycle interface. +// MockLifecycle is a mock of Lifecycle interface type MockLifecycle struct { ctrl *gomock.Controller recorder *MockLifecycleMockRecorder } -// MockLifecycleMockRecorder is the mock recorder for MockLifecycle. +// MockLifecycleMockRecorder is the mock recorder for MockLifecycle type MockLifecycleMockRecorder struct { mock *MockLifecycle } -// NewMockLifecycle creates a new mock instance. +// NewMockLifecycle creates a new mock instance func NewMockLifecycle(ctrl *gomock.Controller) *MockLifecycle { mock := &MockLifecycle{ctrl: ctrl} mock.recorder = &MockLifecycleMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockLifecycle) EXPECT() *MockLifecycleMockRecorder { return m.recorder } -// Descriptor mocks base method. +// Descriptor mocks base method func (m *MockLifecycle) Descriptor() builder.LifecycleDescriptor { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Descriptor") @@ -44,13 +42,13 @@ func (m *MockLifecycle) Descriptor() builder.LifecycleDescriptor { return ret0 } -// Descriptor indicates an expected call of Descriptor. +// Descriptor indicates an expected call of Descriptor func (mr *MockLifecycleMockRecorder) Descriptor() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Descriptor", reflect.TypeOf((*MockLifecycle)(nil).Descriptor)) } -// Open mocks base method. +// Open mocks base method func (m *MockLifecycle) Open() (io.ReadCloser, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Open") @@ -59,7 +57,7 @@ func (m *MockLifecycle) Open() (io.ReadCloser, error) { return ret0, ret1 } -// Open indicates an expected call of Open. +// Open indicates an expected call of Open func (mr *MockLifecycleMockRecorder) Open() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open", reflect.TypeOf((*MockLifecycle)(nil).Open)) diff --git a/internal/builder/writer/factory.go b/internal/builder/writer/factory.go index 35ece81738..5dc21858f3 100644 --- a/internal/builder/writer/factory.go +++ b/internal/builder/writer/factory.go @@ -3,9 +3,9 @@ package writer import ( "fmt" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/style" ) @@ -16,7 +16,7 @@ type BuilderWriter interface { Print( logger logging.Logger, localRunImages []config.RunImage, - local, remote *pack.BuilderInfo, + local, remote *client.BuilderInfo, localErr, remoteErr error, builderInfo SharedBuilderInfo, ) error diff --git a/internal/builder/writer/human_readable.go b/internal/builder/writer/human_readable.go index 8edf515c20..e416680e77 100644 --- a/internal/builder/writer/human_readable.go +++ b/internal/builder/writer/human_readable.go @@ -9,6 +9,7 @@ import ( "text/template" strs "github.com/buildpacks/pack/internal/strings" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/style" @@ -18,7 +19,6 @@ import ( "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/logging" ) @@ -71,7 +71,7 @@ func NewHumanReadable() *HumanReadable { func (h *HumanReadable) Print( logger logging.Logger, localRunImages []config.RunImage, - local, remote *pack.BuilderInfo, + local, remote *client.BuilderInfo, localErr, remoteErr error, builderInfo SharedBuilderInfo, ) error { @@ -102,7 +102,7 @@ func (h *HumanReadable) Print( func writeBuilderInfo( logger logging.Logger, localRunImages []config.RunImage, - info *pack.BuilderInfo, + info *client.BuilderInfo, err error, sharedInfo SharedBuilderInfo, ) error { @@ -141,7 +141,7 @@ func writeBuilderInfo( err = outputTemplate.Execute( logger.Writer(), &struct { - Info pack.BuilderInfo + Info client.BuilderInfo Verbose bool Buildpacks string RunImages string diff --git a/internal/builder/writer/human_readable_test.go b/internal/builder/writer/human_readable_test.go index 89930b332b..0b977cf684 100644 --- a/internal/builder/writer/human_readable_test.go +++ b/internal/builder/writer/human_readable_test.go @@ -6,19 +6,18 @@ import ( "testing" "github.com/Masterminds/semver" + "github.com/buildpacks/lifecycle/api" "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -33,8 +32,8 @@ func testHumanReadable(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.BuilderInfo - localInfo *pack.BuilderInfo + remoteInfo *client.BuilderInfo + localInfo *client.BuilderInfo expectedRemoteOutput = ` REMOTE: @@ -178,7 +177,7 @@ REMOTE: when("Print", func() { it.Before(func() { - remoteInfo = &pack.BuilderInfo{ + remoteInfo = &client.BuilderInfo{ Description: "Some remote description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, @@ -210,7 +209,7 @@ REMOTE: }, } - localInfo = &pack.BuilderInfo{ + localInfo = &client.BuilderInfo{ Description: "Some local description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, diff --git a/internal/builder/writer/json_test.go b/internal/builder/writer/json_test.go index 49850285cd..f8d40534fc 100644 --- a/internal/builder/writer/json_test.go +++ b/internal/builder/writer/json_test.go @@ -8,19 +8,18 @@ import ( "testing" "github.com/Masterminds/semver" + "github.com/buildpacks/lifecycle/api" "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -160,8 +159,8 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.BuilderInfo - localInfo *pack.BuilderInfo + remoteInfo *client.BuilderInfo + localInfo *client.BuilderInfo expectedRemoteInfo = fmt.Sprintf(`"remote_info": { "description": "Some remote description", @@ -241,7 +240,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { when("Print", func() { it.Before(func() { - remoteInfo = &pack.BuilderInfo{ + remoteInfo = &client.BuilderInfo{ Description: "Some remote description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, @@ -273,7 +272,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { }, } - localInfo = &pack.BuilderInfo{ + localInfo = &client.BuilderInfo{ Description: "Some local description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, diff --git a/internal/builder/writer/structured_format.go b/internal/builder/writer/structured_format.go index c33ec35510..44ee56481a 100644 --- a/internal/builder/writer/structured_format.go +++ b/internal/builder/writer/structured_format.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/config" @@ -52,7 +52,7 @@ type StructuredFormat struct { func (w *StructuredFormat) Print( logger logging.Logger, localRunImages []config.RunImage, - local, remote *pack.BuilderInfo, + local, remote *client.BuilderInfo, localErr, remoteErr error, builderInfo SharedBuilderInfo, ) error { diff --git a/internal/builder/writer/toml_test.go b/internal/builder/writer/toml_test.go index 97f9c26192..8e48b69487 100644 --- a/internal/builder/writer/toml_test.go +++ b/internal/builder/writer/toml_test.go @@ -9,19 +9,18 @@ import ( "github.com/pelletier/go-toml" "github.com/Masterminds/semver" + "github.com/buildpacks/lifecycle/api" "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -200,8 +199,8 @@ func testTOML(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.BuilderInfo - localInfo *pack.BuilderInfo + remoteInfo *client.BuilderInfo + localInfo *client.BuilderInfo expectedRemoteInfo = fmt.Sprintf(`[remote_info] description = "Some remote description" @@ -268,7 +267,7 @@ default = false when("Print", func() { it.Before(func() { - remoteInfo = &pack.BuilderInfo{ + remoteInfo = &client.BuilderInfo{ Description: "Some remote description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, @@ -300,7 +299,7 @@ default = false }, } - localInfo = &pack.BuilderInfo{ + localInfo = &client.BuilderInfo{ Description: "Some local description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, diff --git a/internal/builder/writer/yaml_test.go b/internal/builder/writer/yaml_test.go index a39cf97158..0b04aa23c8 100644 --- a/internal/builder/writer/yaml_test.go +++ b/internal/builder/writer/yaml_test.go @@ -9,19 +9,18 @@ import ( "github.com/ghodss/yaml" "github.com/Masterminds/semver" + "github.com/buildpacks/lifecycle/api" "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -105,8 +104,8 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.BuilderInfo - localInfo *pack.BuilderInfo + remoteInfo *client.BuilderInfo + localInfo *client.BuilderInfo expectedRemoteInfo = fmt.Sprintf(`remote_info: description: Some remote description @@ -165,7 +164,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { when("Print", func() { it.Before(func() { - remoteInfo = &pack.BuilderInfo{ + remoteInfo = &client.BuilderInfo{ Description: "Some remote description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, @@ -197,7 +196,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { }, } - localInfo = &pack.BuilderInfo{ + localInfo = &client.BuilderInfo{ Description: "Some local description", Stack: "test.stack.id", Mixins: []string{"mixin1", "mixin2", "build:mixin3", "build:mixin4"}, diff --git a/internal/buildpackage/builder_test.go b/internal/buildpackage/builder_test.go index cfa3cd3b5d..bd930fc4a4 100644 --- a/internal/buildpackage/builder_test.go +++ b/internal/buildpackage/builder_test.go @@ -25,8 +25,8 @@ import ( "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestPackageBuilder(t *testing.T) { diff --git a/internal/buildpackage/oci_layout_package.go b/internal/buildpackage/oci_layout_package.go index d22a379469..2919f0ac05 100644 --- a/internal/buildpackage/oci_layout_package.go +++ b/internal/buildpackage/oci_layout_package.go @@ -12,10 +12,10 @@ import ( v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - blob2 "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" + blob2 "github.com/buildpacks/pack/pkg/blob" ) // IsOCILayoutBlob checks whether a blob is in OCI layout format. diff --git a/internal/buildpackage/oci_layout_package_test.go b/internal/buildpackage/oci_layout_package_test.go index 2318fc5873..9aadd49b70 100644 --- a/internal/buildpackage/oci_layout_package_test.go +++ b/internal/buildpackage/oci_layout_package_test.go @@ -11,11 +11,11 @@ import ( "github.com/buildpacks/lifecycle/api" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/fakes" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/blob" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/build.go b/internal/commands/build.go index adafeb801e..9c78418339 100644 --- a/internal/commands/build.go +++ b/internal/commands/build.go @@ -7,16 +7,14 @@ import ( "strings" "github.com/google/go-containerregistry/pkg/name" - - pubcfg "github.com/buildpacks/pack/config" - "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/project" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) @@ -86,7 +84,7 @@ func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cob if builder == "" { suggestSettingBuilder(logger, packClient) - return pack.NewSoftError() + return client.NewSoftError() } buildpacks := flags.Buildpacks @@ -129,7 +127,7 @@ func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cob if cmd.Flags().Changed("gid") { gid = flags.GID } - if err := packClient.Build(cmd.Context(), pack.BuildOptions{ + if err := packClient.Build(cmd.Context(), client.BuildOptions{ AppPath: flags.AppPath, Builder: builder, Registry: flags.Registry, @@ -146,7 +144,7 @@ func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cob return trustBuilder }, Buildpacks: buildpacks, - ContainerConfig: pack.ContainerConfig{ + ContainerConfig: client.ContainerConfig{ Network: flags.Network, Volumes: flags.Volumes, }, @@ -207,7 +205,7 @@ This option may set DOCKER_HOST environment variable for the build container if func validateBuildFlags(flags *BuildFlags, cfg config.Config, packClient PackClient, logger logging.Logger) error { if flags.Registry != "" && !cfg.Experimental { - return pack.NewExperimentError("Support for buildpack registries is currently experimental.") + return client.NewExperimentError("Support for buildpack registries is currently experimental.") } if flags.CacheImage != "" && !flags.Publish { @@ -219,7 +217,7 @@ func validateBuildFlags(flags *BuildFlags, cfg config.Config, packClient PackCli } if flags.Interactive && !cfg.Experimental { - return pack.NewExperimentError("Interactive mode is currently experimental.") + return client.NewExperimentError("Interactive mode is currently experimental.") } return nil diff --git a/internal/commands/build_test.go b/internal/commands/build_test.go index 019919cb69..fdf485aa1f 100644 --- a/internal/commands/build_test.go +++ b/internal/commands/build_test.go @@ -17,12 +17,12 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -58,12 +58,12 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { it("returns a soft error", func() { mockClient.EXPECT(). InspectBuilder(gomock.Any(), false). - Return(&pack.BuilderInfo{Description: ""}, nil). + Return(&client.BuilderInfo{Description: ""}, nil). AnyTimes() command.SetArgs([]string{"image"}) err := command.Execute() - h.AssertError(t, err, pack.NewSoftError().Error()) + h.AssertError(t, err, client.NewSoftError().Error()) }) }) @@ -778,7 +778,7 @@ builder = "my-builder" func EqBuildOptionsWithImage(builder, image string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Builder=%s and Image=%s", builder, image), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.Builder == builder && o.Image == image }, } @@ -787,7 +787,7 @@ func EqBuildOptionsWithImage(builder, image string) gomock.Matcher { func EqBuildOptionsDefaultProcess(defaultProc string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Default Process Type=%s", defaultProc), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.DefaultProcessType == defaultProc }, } @@ -796,7 +796,7 @@ func EqBuildOptionsDefaultProcess(defaultProc string) gomock.Matcher { func EqBuildOptionsWithPullPolicy(policy pubcfg.PullPolicy) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("PullPolicy=%s", policy), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.PullPolicy == policy }, } @@ -805,7 +805,7 @@ func EqBuildOptionsWithPullPolicy(policy pubcfg.PullPolicy) gomock.Matcher { func EqBuildOptionsWithCacheImage(cacheImage string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("CacheImage=%s", cacheImage), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.CacheImage == cacheImage }, } @@ -814,7 +814,7 @@ func EqBuildOptionsWithCacheImage(cacheImage string) gomock.Matcher { func EqBuildOptionsWithLifecycleImage(lifecycleImage string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("LifecycleImage=%s", lifecycleImage), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.LifecycleImage == lifecycleImage }, } @@ -823,7 +823,7 @@ func EqBuildOptionsWithLifecycleImage(lifecycleImage string) gomock.Matcher { func EqBuildOptionsWithNetwork(network string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Network=%s", network), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.ContainerConfig.Network == network }, } @@ -832,7 +832,7 @@ func EqBuildOptionsWithNetwork(network string) gomock.Matcher { func EqBuildOptionsWithBuilder(builder string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Builder=%s", builder), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.Builder == builder }, } @@ -841,7 +841,7 @@ func EqBuildOptionsWithBuilder(builder string) gomock.Matcher { func EqBuildOptionsWithTrustedBuilder(trustBuilder bool) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Trust Builder=%t", trustBuilder), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.TrustBuilder(o.Builder) }, } @@ -850,7 +850,7 @@ func EqBuildOptionsWithTrustedBuilder(trustBuilder bool) gomock.Matcher { func EqBuildOptionsWithVolumes(volumes []string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Volumes=%s", volumes), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return reflect.DeepEqual(o.ContainerConfig.Volumes, volumes) }, } @@ -859,7 +859,7 @@ func EqBuildOptionsWithVolumes(volumes []string) gomock.Matcher { func EqBuildOptionsWithAdditionalTags(additionalTags []string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("AdditionalTags=%s", additionalTags), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return reflect.DeepEqual(o.AdditionalTags, additionalTags) }, } @@ -868,7 +868,7 @@ func EqBuildOptionsWithAdditionalTags(additionalTags []string) gomock.Matcher { func EqBuildOptionsWithProjectDescriptor(descriptor projectTypes.Descriptor) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Descriptor=%s", descriptor), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return reflect.DeepEqual(o.ProjectDescriptor, descriptor) }, } @@ -877,7 +877,7 @@ func EqBuildOptionsWithProjectDescriptor(descriptor projectTypes.Descriptor) gom func EqBuildOptionsWithEnv(env map[string]string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Env=%+v", env), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { for k, v := range o.Env { if env[k] != v { return false @@ -896,7 +896,7 @@ func EqBuildOptionsWithEnv(env map[string]string) gomock.Matcher { func EqBuildOptionsWithOverrideGroupID(gid int) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("GID=%d", gid), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.GroupID == gid }, } @@ -905,19 +905,19 @@ func EqBuildOptionsWithOverrideGroupID(gid int) gomock.Matcher { func EqBuildOptionsWithPreviousImage(prevImage string) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("Previous image=%s", prevImage), - equals: func(o pack.BuildOptions) bool { + equals: func(o client.BuildOptions) bool { return o.PreviousImage == prevImage }, } } type buildOptionsMatcher struct { - equals func(pack.BuildOptions) bool + equals func(client.BuildOptions) bool description string } func (m buildOptionsMatcher) Matches(x interface{}) bool { - if b, ok := x.(pack.BuildOptions); ok { + if b, ok := x.(client.BuildOptions); ok { return m.equals(b) } return false diff --git a/internal/commands/builder_create.go b/internal/commands/builder_create.go index f83b0fd015..488868b6db 100644 --- a/internal/commands/builder_create.go +++ b/internal/commands/builder_create.go @@ -7,12 +7,12 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/builder" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" ) // BuilderCreateFlags define flags provided to the CreateBuilder command @@ -24,7 +24,7 @@ type BuilderCreateFlags struct { } // CreateBuilder creates a builder image, based on a builder config -func BuilderCreate(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { +func BuilderCreate(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { var flags BuilderCreateFlags cmd := &cobra.Command{ @@ -66,7 +66,7 @@ Creating a custom builder allows you to control what buildpacks are used and wha } imageName := args[0] - if err := client.CreateBuilder(cmd.Context(), pack.CreateBuilderOptions{ + if err := pack.CreateBuilder(cmd.Context(), client.CreateBuilderOptions{ RelativeBaseDir: relativeBaseDir, BuilderName: imageName, Config: builderConfig, @@ -100,7 +100,7 @@ func validateCreateFlags(flags *BuilderCreateFlags, cfg config.Config) error { } if flags.Registry != "" && !cfg.Experimental { - return pack.NewExperimentError("Support for buildpack registries is currently experimental.") + return client.NewExperimentError("Support for buildpack registries is currently experimental.") } if flags.BuilderTomlPath == "" { diff --git a/internal/commands/builder_inspect.go b/internal/commands/builder_inspect.go index b0564cef43..743a6d616d 100644 --- a/internal/commands/builder_inspect.go +++ b/internal/commands/builder_inspect.go @@ -3,15 +3,15 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type BuilderInspector interface { - InspectBuilder(name string, daemon bool, modifiers ...pack.BuilderInspectionModifier) (*pack.BuilderInfo, error) + InspectBuilder(name string, daemon bool, modifiers ...client.BuilderInspectionModifier) (*client.BuilderInfo, error) } type BuilderInspectFlags struct { @@ -40,7 +40,7 @@ func BuilderInspect(logger logging.Logger, if imageName == "" { suggestSettingBuilder(logger, inspector) - return pack.NewSoftError() + return client.NewSoftError() } return inspectBuilder(logger, imageName, flags, cfg, inspector, writerFactory) @@ -67,8 +67,8 @@ func inspectBuilder( Trusted: isTrustedBuilder(cfg, imageName), } - localInfo, localErr := inspector.InspectBuilder(imageName, true, pack.WithDetectionOrderDepth(flags.Depth)) - remoteInfo, remoteErr := inspector.InspectBuilder(imageName, false, pack.WithDetectionOrderDepth(flags.Depth)) + localInfo, localErr := inspector.InspectBuilder(imageName, true, client.WithDetectionOrderDepth(flags.Depth)) + remoteInfo, remoteErr := inspector.InspectBuilder(imageName, false, client.WithDetectionOrderDepth(flags.Depth)) writer, err := writerFactory.Writer(flags.OutputFormat) if err != nil { diff --git a/internal/commands/builder_inspect_test.go b/internal/commands/builder_inspect_test.go index 11a4c04183..d95c9f31c0 100644 --- a/internal/commands/builder_inspect_test.go +++ b/internal/commands/builder_inspect_test.go @@ -7,20 +7,18 @@ import ( "testing" "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/builder/writer" - "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" + "github.com/buildpacks/pack/internal/builder" + "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,13 +34,13 @@ var ( expectedLocalRunImages = []config.RunImage{ {Image: "some/run-image", Mirrors: []string{"first/local", "second/local"}}, } - expectedLocalInfo = &pack.BuilderInfo{ + expectedLocalInfo = &client.BuilderInfo{ Description: "test-local-builder", Stack: "local-stack", RunImage: "local/image", Lifecycle: minimalLifecycleDescriptor, } - expectedRemoteInfo = &pack.BuilderInfo{ + expectedRemoteInfo = &client.BuilderInfo{ Description: "test-remote-builder", Stack: "remote-stack", RunImage: "remote/image", @@ -245,8 +243,8 @@ func testBuilderInspectCommand(t *testing.T, when spec.G, it spec.S) { err := command.Execute() assert.Error(err) - if !errors.Is(err, pack.SoftError{}) { - t.Fatalf("expect a pack.SoftError, got: %s", err) + if !errors.Is(err, client.SoftError{}) { + t.Fatalf("expect a client.SoftError, got: %s", err) } assert.Contains(outBuf.String(), `Please select a default builder with: diff --git a/internal/commands/builder_suggest_test.go b/internal/commands/builder_suggest_test.go index 1105cae7ad..81fdd99b49 100644 --- a/internal/commands/builder_suggest_test.go +++ b/internal/commands/builder_suggest_test.go @@ -10,12 +10,12 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -42,7 +42,7 @@ func testSuggestCommand(t *testing.T, when spec.G, it spec.S) { when("#WriteSuggestedBuilder", func() { when("description metadata exists", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder("gcr.io/some/builder:latest", false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder("gcr.io/some/builder:latest", false).Return(&client.BuilderInfo{ Description: "Remote description", }, nil) }) @@ -60,7 +60,7 @@ func testSuggestCommand(t *testing.T, when spec.G, it spec.S) { when("description metadata does not exist", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&client.BuilderInfo{ Description: "", }, nil).AnyTimes() }) diff --git a/internal/commands/buildpack_inspect.go b/internal/commands/buildpack_inspect.go index a15c422ece..c381028508 100644 --- a/internal/commands/buildpack_inspect.go +++ b/internal/commands/buildpack_inspect.go @@ -5,10 +5,10 @@ import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type BuildpackInspectFlags struct { @@ -42,18 +42,18 @@ func BuildpackInspect(logger logging.Logger, cfg config.Config, client PackClien return cmd } -func buildpackInspect(logger logging.Logger, buildpackName, registryName string, flags BuildpackInspectFlags, cfg config.Config, client PackClient) error { +func buildpackInspect(logger logging.Logger, buildpackName, registryName string, flags BuildpackInspectFlags, cfg config.Config, pack PackClient) error { logger.Infof("Inspecting buildpack: %s\n", style.Symbol(buildpackName)) inspectedBuildpacksOutput, err := inspectAllBuildpacks( - client, + pack, flags, - pack.InspectBuildpackOptions{ + client.InspectBuildpackOptions{ BuildpackName: buildpackName, Daemon: true, Registry: registryName, }, - pack.InspectBuildpackOptions{ + client.InspectBuildpackOptions{ BuildpackName: buildpackName, Daemon: false, Registry: registryName, diff --git a/internal/commands/buildpack_inspect_test.go b/internal/commands/buildpack_inspect_test.go index b8cb6b5f78..843b389fa9 100644 --- a/internal/commands/buildpack_inspect_test.go +++ b/internal/commands/buildpack_inspect_test.go @@ -5,18 +5,14 @@ import ( "fmt" "testing" - "github.com/pkg/errors" - - "github.com/buildpacks/pack/internal/image" - "github.com/buildpacks/lifecycle/api" "github.com/golang/mock/gomock" "github.com/heroku/color" + "github.com/pkg/errors" "github.com/sclevine/spec" "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/commands" @@ -25,6 +21,8 @@ import ( "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -127,8 +125,8 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { mockController *gomock.Controller mockClient *testmocks.MockPackClient cfg config.Config - complexInfo *pack.BuildpackInfo - simpleInfo *pack.BuildpackInfo + complexInfo *client.BuildpackInfo + simpleInfo *client.BuildpackInfo assert = h.NewAssertionManager(t) ) @@ -141,7 +139,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { DefaultRegistryName: "default-registry", } - complexInfo = &pack.BuildpackInfo{ + complexInfo = &client.BuildpackInfo{ BuildpackMetadata: buildpackage.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", @@ -299,7 +297,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { }, } - simpleInfo = &pack.BuildpackInfo{ + simpleInfo = &client.BuildpackInfo{ BuildpackMetadata: buildpackage.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/single-buildpack", @@ -364,13 +362,13 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "test/buildpack", Daemon: true, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "test/buildpack", Daemon: false, Registry: "default-registry", @@ -400,13 +398,13 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-local-test/buildpack", Daemon: true, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-local-test/buildpack", Daemon: false, Registry: "default-registry", @@ -431,13 +429,13 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: false, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: true, Registry: "default-registry", @@ -465,7 +463,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("uri is a local path", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -491,7 +489,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { }) when("uri is a local path", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "https://path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -520,7 +518,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("using the default registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:test/buildpack", Daemon: true, Registry: "default-registry", @@ -541,7 +539,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("using a user provided registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:test/buildpack", Daemon: true, Registry: "some-registry", @@ -566,7 +564,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { complexInfo.Location = buildpack.URILocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/other/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -585,7 +583,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("verbose flag is passed", func() { it.Before(func() { simpleInfo.Location = buildpack.URILocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/another/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -603,17 +601,17 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("failure cases", func() { when("unable to inspect buildpack image", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect local failure-case/buildpack")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect local failure-case/buildpack")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "failure-case/buildpack", Daemon: false, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect remote failure-case/buildpack")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect remote failure-case/buildpack")) }) it("errors", func() { @@ -624,11 +622,11 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { }) when("unable to inspect buildpack archive", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "http://path/to/failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting local archive")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting local archive")) it("errors", func() { command.SetArgs([]string{"http://path/to/failure-case/buildpack"}) @@ -641,17 +639,17 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { }) when("unable to inspect both remote and local images", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "image-failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting local archive")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting local archive")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "image-failure-case/buildpack", Daemon: false, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting remote archive")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting remote archive")) }) it("errors", func() { @@ -665,17 +663,17 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { when("unable to inspect buildpack on registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:registry-failure/buildpack", Daemon: true, Registry: "some-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting registry image")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting registry image")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:registry-failure/buildpack", Daemon: false, Registry: "some-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting registry image")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting registry image")) }) it("errors", func() { diff --git a/internal/commands/buildpack_new.go b/internal/commands/buildpack_new.go index 4e4ea75946..d6a382b4e2 100644 --- a/internal/commands/buildpack_new.go +++ b/internal/commands/buildpack_new.go @@ -9,11 +9,11 @@ import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) // BuildpackNewFlags define flags provided to the BuildpackNew command @@ -26,11 +26,11 @@ type BuildpackNewFlags struct { // BuildpackCreator creates buildpacks type BuildpackCreator interface { - NewBuildpack(ctx context.Context, options pack.NewBuildpackOptions) error + NewBuildpack(ctx context.Context, options client.NewBuildpackOptions) error } // BuildpackNew generates the scaffolding of a buildpack -func BuildpackNew(logger logging.Logger, client BuildpackCreator) *cobra.Command { +func BuildpackNew(logger logging.Logger, creator BuildpackCreator) *cobra.Command { var flags BuildpackNewFlags cmd := &cobra.Command{ Use: "new ", @@ -67,7 +67,7 @@ func BuildpackNew(logger logging.Logger, client BuildpackCreator) *cobra.Command }) } - if err := client.NewBuildpack(cmd.Context(), pack.NewBuildpackOptions{ + if err := creator.NewBuildpack(cmd.Context(), client.NewBuildpackOptions{ API: flags.API, ID: id, Path: path, diff --git a/internal/commands/buildpack_new_test.go b/internal/commands/buildpack_new_test.go index f6bc668bc9..f0a0414c4e 100644 --- a/internal/commands/buildpack_new_test.go +++ b/internal/commands/buildpack_new_test.go @@ -7,8 +7,8 @@ import ( "path/filepath" "testing" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/client" "github.com/golang/mock/gomock" "github.com/heroku/color" @@ -56,7 +56,7 @@ func testBuildpackNewCommand(t *testing.T, when spec.G, it spec.S) { when("BuildpackNew#Execute", func() { it("uses the args to generate artifacts", func() { - mockClient.EXPECT().NewBuildpack(gomock.Any(), pack.NewBuildpackOptions{ + mockClient.EXPECT().NewBuildpack(gomock.Any(), client.NewBuildpackOptions{ API: "0.6", ID: "example/some-cnb", Path: filepath.Join(tmpDir, "some-cnb"), diff --git a/internal/commands/buildpack_package.go b/internal/commands/buildpack_package.go index 4801281ffc..cb162de91d 100644 --- a/internal/commands/buildpack_package.go +++ b/internal/commands/buildpack_package.go @@ -7,12 +7,12 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" pubbldpkg "github.com/buildpacks/pack/buildpackage" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" ) // BuildpackPackageFlags define flags provided to the BuildpackPackage command @@ -27,7 +27,7 @@ type BuildpackPackageFlags struct { // BuildpackPackager packages buildpacks type BuildpackPackager interface { - PackageBuildpack(ctx context.Context, options pack.PackageBuildpackOptions) error + PackageBuildpack(ctx context.Context, options client.PackageBuildpackOptions) error } // PackageConfigReader reads BuildpackPackage configs @@ -36,7 +36,7 @@ type PackageConfigReader interface { } // BuildpackPackage packages (a) buildpack(s) into OCI format, based on a package config -func BuildpackPackage(logger logging.Logger, cfg config.Config, client BuildpackPackager, packageConfigReader PackageConfigReader) *cobra.Command { +func BuildpackPackage(logger logging.Logger, cfg config.Config, packager BuildpackPackager, packageConfigReader PackageConfigReader) *cobra.Command { var flags BuildpackPackageFlags cmd := &cobra.Command{ Use: "package --config ", @@ -83,16 +83,16 @@ func BuildpackPackage(logger logging.Logger, cfg config.Config, client Buildpack } } name := args[0] - if flags.Format == pack.FormatFile { + if flags.Format == client.FormatFile { switch ext := filepath.Ext(name); ext { - case pack.CNBExtension: + case client.CNBExtension: case "": - name += pack.CNBExtension + name += client.CNBExtension default: - logger.Warnf("%s is not a valid extension for a packaged buildpack. Packaged buildpacks must have a %s extension", style.Symbol(ext), style.Symbol(pack.CNBExtension)) + logger.Warnf("%s is not a valid extension for a packaged buildpack. Packaged buildpacks must have a %s extension", style.Symbol(ext), style.Symbol(client.CNBExtension)) } } - if err := client.PackageBuildpack(cmd.Context(), pack.PackageBuildpackOptions{ + if err := packager.PackageBuildpack(cmd.Context(), client.PackageBuildpackOptions{ RelativeBaseDir: relativeBaseDir, Name: name, Format: flags.Format, diff --git a/internal/commands/buildpack_package_test.go b/internal/commands/buildpack_package_test.go index 4887ab5bbe..393c450cde 100644 --- a/internal/commands/buildpack_package_test.go +++ b/internal/commands/buildpack_package_test.go @@ -13,12 +13,12 @@ import ( "github.com/spf13/cobra" pubbldpkg "github.com/buildpacks/pack/buildpackage" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + pubcfg "github.com/buildpacks/pack/pkg/config" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/buildpack_pull.go b/internal/commands/buildpack_pull.go index 38b1e94730..0b19ff09f7 100644 --- a/internal/commands/buildpack_pull.go +++ b/internal/commands/buildpack_pull.go @@ -3,10 +3,10 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) // BuildpackPullFlags consist of flags applicable to the `buildpack pull` command @@ -16,7 +16,7 @@ type BuildpackPullFlags struct { } // BuildpackPull pulls a buildpack and stores it locally -func BuildpackPull(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { +func BuildpackPull(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { var flags BuildpackPullFlags cmd := &cobra.Command{ @@ -30,12 +30,12 @@ func BuildpackPull(logger logging.Logger, cfg config.Config, client PackClient) return err } - opts := pack.PullBuildpackOptions{ + opts := client.PullBuildpackOptions{ URI: args[0], RegistryName: registry.Name, } - if err := client.PullBuildpack(cmd.Context(), opts); err != nil { + if err := pack.PullBuildpack(cmd.Context(), opts); err != nil { return err } logger.Infof("Successfully pulled %s", style.Symbol(opts.URI)) diff --git a/internal/commands/buildpack_pull_test.go b/internal/commands/buildpack_pull_test.go index 8a492201bd..8114e71c81 100644 --- a/internal/commands/buildpack_pull_test.go +++ b/internal/commands/buildpack_pull_test.go @@ -9,12 +9,12 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -52,7 +52,7 @@ func testPullBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("buildpack uri is provided", func() { it("should work for required args", func() { buildpackImage := "buildpack/image" - opts := pack.PullBuildpackOptions{ + opts := client.PullBuildpackOptions{ URI: buildpackImage, RegistryName: "official", } diff --git a/internal/commands/buildpack_register.go b/internal/commands/buildpack_register.go index 2fd533c15c..7b3f6d26fc 100644 --- a/internal/commands/buildpack_register.go +++ b/internal/commands/buildpack_register.go @@ -3,18 +3,18 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type BuildpackRegisterFlags struct { BuildpackRegistry string } -func BuildpackRegister(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { - var opts pack.RegisterBuildpackOptions +func BuildpackRegister(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { + var opts client.RegisterBuildpackOptions var flags BuildpackRegisterFlags cmd := &cobra.Command{ @@ -32,7 +32,7 @@ func BuildpackRegister(logger logging.Logger, cfg config.Config, client PackClie opts.URL = registry.URL opts.Name = registry.Name - if err := client.RegisterBuildpack(cmd.Context(), opts); err != nil { + if err := pack.RegisterBuildpack(cmd.Context(), opts); err != nil { return err } logger.Infof("Successfully registered %s", style.Symbol(opts.ImageName)) diff --git a/internal/commands/buildpack_register_test.go b/internal/commands/buildpack_register_test.go index 15cda8ff8e..9b1d85e9bf 100644 --- a/internal/commands/buildpack_register_test.go +++ b/internal/commands/buildpack_register_test.go @@ -4,8 +4,8 @@ import ( "bytes" "testing" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" + "github.com/buildpacks/pack/pkg/client" "github.com/golang/mock/gomock" "github.com/sclevine/spec" @@ -56,7 +56,7 @@ func testRegisterCommand(t *testing.T, when spec.G, it spec.S) { var buildpackImage = "buildpack/image" it("should work for required args", func() { - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/buildpacks/registry-index", @@ -84,7 +84,7 @@ func testRegisterCommand(t *testing.T, when spec.G, it spec.S) { }, } cmd = commands.BuildpackRegister(logger, cfg, mockClient) - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/berneuse/buildpack-registry", @@ -128,7 +128,7 @@ func testRegisterCommand(t *testing.T, when spec.G, it spec.S) { }, }, } - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/override/buildpack-registry", diff --git a/internal/commands/buildpack_yank.go b/internal/commands/buildpack_yank.go index 5c3c252076..52609859fd 100644 --- a/internal/commands/buildpack_yank.go +++ b/internal/commands/buildpack_yank.go @@ -6,10 +6,10 @@ import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type BuildpackYankFlags struct { @@ -17,7 +17,7 @@ type BuildpackYankFlags struct { Undo bool } -func BuildpackYank(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { +func BuildpackYank(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { var flags BuildpackYankFlags cmd := &cobra.Command{ @@ -37,7 +37,7 @@ func BuildpackYank(logger logging.Logger, cfg config.Config, client PackClient) return err } - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: id, Version: version, Type: "github", @@ -45,7 +45,7 @@ func BuildpackYank(logger logging.Logger, cfg config.Config, client PackClient) Yank: !flags.Undo, } - if err := client.YankBuildpack(opts); err != nil { + if err := pack.YankBuildpack(opts); err != nil { return err } logger.Infof("Successfully yanked %s", style.Symbol(buildpackIDVersion)) diff --git a/internal/commands/buildpack_yank_test.go b/internal/commands/buildpack_yank_test.go index d048e63b74..911f38d3bb 100644 --- a/internal/commands/buildpack_yank_test.go +++ b/internal/commands/buildpack_yank_test.go @@ -10,12 +10,12 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -62,7 +62,7 @@ func testYankCommand(t *testing.T, when spec.G, it spec.S) { }) it("should work for required args", func() { - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -97,7 +97,7 @@ func testYankCommand(t *testing.T, when spec.G, it spec.S) { }, } - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -114,7 +114,7 @@ func testYankCommand(t *testing.T, when spec.G, it spec.S) { }) it("should undo", func() { - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -147,7 +147,7 @@ func testYankCommand(t *testing.T, when spec.G, it spec.S) { }, }, } - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", diff --git a/internal/commands/commands.go b/internal/commands/commands.go index a3a03b7072..bf692b6639 100644 --- a/internal/commands/commands.go +++ b/internal/commands/commands.go @@ -10,25 +10,25 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) //go:generate mockgen -package testmocks -destination testmocks/mock_pack_client.go github.com/buildpacks/pack/internal/commands PackClient type PackClient interface { - InspectBuilder(string, bool, ...pack.BuilderInspectionModifier) (*pack.BuilderInfo, error) - InspectImage(string, bool) (*pack.ImageInfo, error) - Rebase(context.Context, pack.RebaseOptions) error - CreateBuilder(context.Context, pack.CreateBuilderOptions) error - NewBuildpack(context.Context, pack.NewBuildpackOptions) error - PackageBuildpack(ctx context.Context, opts pack.PackageBuildpackOptions) error - Build(context.Context, pack.BuildOptions) error - RegisterBuildpack(context.Context, pack.RegisterBuildpackOptions) error - YankBuildpack(pack.YankBuildpackOptions) error - InspectBuildpack(pack.InspectBuildpackOptions) (*pack.BuildpackInfo, error) - PullBuildpack(context.Context, pack.PullBuildpackOptions) error + InspectBuilder(string, bool, ...client.BuilderInspectionModifier) (*client.BuilderInfo, error) + InspectImage(string, bool) (*client.ImageInfo, error) + Rebase(context.Context, client.RebaseOptions) error + CreateBuilder(context.Context, client.CreateBuilderOptions) error + NewBuildpack(context.Context, client.NewBuildpackOptions) error + PackageBuildpack(ctx context.Context, opts client.PackageBuildpackOptions) error + Build(context.Context, client.BuildOptions) error + RegisterBuildpack(context.Context, client.RegisterBuildpackOptions) error + YankBuildpack(client.YankBuildpackOptions) error + InspectBuildpack(client.InspectBuildpackOptions) (*client.BuildpackInfo, error) + PullBuildpack(context.Context, client.PullBuildpackOptions) error } func AddHelpFlag(cmd *cobra.Command, commandName string) { @@ -54,11 +54,11 @@ func logError(logger logging.Logger, f func(cmd *cobra.Command, args []string) e cmd.SilenceUsage = true err := f(cmd, args) if err != nil { - if _, isSoftError := errors.Cause(err).(pack.SoftError); !isSoftError { + if _, isSoftError := errors.Cause(err).(client.SoftError); !isSoftError { logger.Error(err.Error()) } - if _, isExpError := errors.Cause(err).(pack.ExperimentError); isExpError { + if _, isExpError := errors.Cause(err).(client.ExperimentError); isExpError { configPath, err := config.DefaultConfigPath() if err != nil { return err diff --git a/internal/commands/config_default_builder_test.go b/internal/commands/config_default_builder_test.go index d7d5e44807..dbb345d8d4 100644 --- a/internal/commands/config_default_builder_test.go +++ b/internal/commands/config_default_builder_test.go @@ -14,13 +14,13 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -110,7 +110,7 @@ func testConfigDefaultBuilder(t *testing.T, when spec.G, it spec.S) { var imageName = "some/image" it("sets default builder", func() { - mockClient.EXPECT().InspectBuilder(imageName, true).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, true).Return(&client.BuilderInfo{ Stack: "test.stack.id", }, nil) @@ -125,7 +125,7 @@ func testConfigDefaultBuilder(t *testing.T, when spec.G, it spec.S) { it("gives clear error if unable to write to config", func() { h.AssertNil(t, ioutil.WriteFile(configPath, []byte("some-data"), 0001)) - mockClient.EXPECT().InspectBuilder(imageName, true).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, true).Return(&client.BuilderInfo{ Stack: "test.stack.id", }, nil) cmd = commands.ConfigDefaultBuilder(logger, config.Config{}, configPath, mockClient) @@ -141,7 +141,7 @@ func testConfigDefaultBuilder(t *testing.T, when spec.G, it spec.S) { localCall := mockClient.EXPECT().InspectBuilder(imageName, true).Return(nil, nil) - mockClient.EXPECT().InspectBuilder(imageName, false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, false).Return(&client.BuilderInfo{ Stack: "test.stack.id", }, nil).After(localCall) @@ -155,9 +155,9 @@ func testConfigDefaultBuilder(t *testing.T, when spec.G, it spec.S) { localCall := mockClient.EXPECT().InspectBuilder(imageName, true).Return(nil, nil) - mockClient.EXPECT().InspectBuilder(imageName, false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, false).Return(&client.BuilderInfo{ Stack: "test.stack.id", - }, pack.SoftError{}).After(localCall) + }, client.SoftError{}).After(localCall) cmd.SetArgs([]string{imageName}) err := cmd.Execute() diff --git a/internal/commands/config_pull_policy.go b/internal/commands/config_pull_policy.go index a45a7bd37e..17db5af955 100644 --- a/internal/commands/config_pull_policy.go +++ b/internal/commands/config_pull_policy.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - pubcfg "github.com/buildpacks/pack/config" + pubcfg "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" diff --git a/internal/commands/create_builder.go b/internal/commands/create_builder.go index 304ccd56f0..6887502b69 100644 --- a/internal/commands/create_builder.go +++ b/internal/commands/create_builder.go @@ -7,17 +7,17 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/builder" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" ) // Deprecated: Use 'builder create' instead. // CreateBuilder creates a builder image, based on a builder config -func CreateBuilder(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { +func CreateBuilder(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { var flags BuilderCreateFlags cmd := &cobra.Command{ @@ -62,7 +62,7 @@ Creating a custom builder allows you to control what buildpacks are used and wha } imageName := args[0] - if err := client.CreateBuilder(cmd.Context(), pack.CreateBuilderOptions{ + if err := pack.CreateBuilder(cmd.Context(), client.CreateBuilderOptions{ RelativeBaseDir: relativeBaseDir, BuilderName: imageName, Config: builderConfig, diff --git a/internal/commands/fakes/fake_builder_inspector.go b/internal/commands/fakes/fake_builder_inspector.go index d8f7fff203..5605c79db6 100644 --- a/internal/commands/fakes/fake_builder_inspector.go +++ b/internal/commands/fakes/fake_builder_inspector.go @@ -1,26 +1,28 @@ package fakes -import "github.com/buildpacks/pack" +import ( + "github.com/buildpacks/pack/pkg/client" +) type FakeBuilderInspector struct { - InfoForLocal *pack.BuilderInfo - InfoForRemote *pack.BuilderInfo + InfoForLocal *client.BuilderInfo + InfoForRemote *client.BuilderInfo ErrorForLocal error ErrorForRemote error ReceivedForLocalName string ReceivedForRemoteName string - CalculatedConfigForLocal pack.BuilderInspectionConfig - CalculatedConfigForRemote pack.BuilderInspectionConfig + CalculatedConfigForLocal client.BuilderInspectionConfig + CalculatedConfigForRemote client.BuilderInspectionConfig } func (i *FakeBuilderInspector) InspectBuilder( name string, daemon bool, - modifiers ...pack.BuilderInspectionModifier, -) (*pack.BuilderInfo, error) { + modifiers ...client.BuilderInspectionModifier, +) (*client.BuilderInfo, error) { if daemon { - i.CalculatedConfigForLocal = pack.BuilderInspectionConfig{} + i.CalculatedConfigForLocal = client.BuilderInspectionConfig{} for _, mod := range modifiers { mod(&i.CalculatedConfigForLocal) } @@ -28,7 +30,7 @@ func (i *FakeBuilderInspector) InspectBuilder( return i.InfoForLocal, i.ErrorForLocal } - i.CalculatedConfigForRemote = pack.BuilderInspectionConfig{} + i.CalculatedConfigForRemote = client.BuilderInspectionConfig{} for _, mod := range modifiers { mod(&i.CalculatedConfigForRemote) } diff --git a/internal/commands/fakes/fake_builder_writer.go b/internal/commands/fakes/fake_builder_writer.go index 58e9cb3333..f7e2b7a2d0 100644 --- a/internal/commands/fakes/fake_builder_writer.go +++ b/internal/commands/fakes/fake_builder_writer.go @@ -1,10 +1,10 @@ package fakes import ( - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type FakeBuilderWriter struct { @@ -12,8 +12,8 @@ type FakeBuilderWriter struct { PrintForRemote string ErrorForPrint error - ReceivedInfoForLocal *pack.BuilderInfo - ReceivedInfoForRemote *pack.BuilderInfo + ReceivedInfoForLocal *client.BuilderInfo + ReceivedInfoForRemote *client.BuilderInfo ReceivedErrorForLocal error ReceivedErrorForRemote error ReceivedBuilderInfo writer.SharedBuilderInfo @@ -23,7 +23,7 @@ type FakeBuilderWriter struct { func (w *FakeBuilderWriter) Print( logger logging.Logger, localRunImages []config.RunImage, - local, remote *pack.BuilderInfo, + local, remote *client.BuilderInfo, localErr, remoteErr error, builderInfo writer.SharedBuilderInfo, ) error { diff --git a/internal/commands/fakes/fake_buildpack_packager.go b/internal/commands/fakes/fake_buildpack_packager.go index 22ca8244ee..d58ab831c9 100644 --- a/internal/commands/fakes/fake_buildpack_packager.go +++ b/internal/commands/fakes/fake_buildpack_packager.go @@ -3,14 +3,14 @@ package fakes import ( "context" - "github.com/buildpacks/pack" + "github.com/buildpacks/pack/pkg/client" ) type FakeBuildpackPackager struct { - CreateCalledWithOptions pack.PackageBuildpackOptions + CreateCalledWithOptions client.PackageBuildpackOptions } -func (c *FakeBuildpackPackager) PackageBuildpack(ctx context.Context, opts pack.PackageBuildpackOptions) error { +func (c *FakeBuildpackPackager) PackageBuildpack(ctx context.Context, opts client.PackageBuildpackOptions) error { c.CreateCalledWithOptions = opts return nil diff --git a/internal/commands/fakes/fake_inspect_image_writer.go b/internal/commands/fakes/fake_inspect_image_writer.go index 04e4bb9a01..7978ed5b0b 100644 --- a/internal/commands/fakes/fake_inspect_image_writer.go +++ b/internal/commands/fakes/fake_inspect_image_writer.go @@ -1,9 +1,9 @@ package fakes import ( - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) type FakeInspectImageWriter struct { @@ -11,8 +11,8 @@ type FakeInspectImageWriter struct { PrintForRemote string ErrorForPrint error - ReceivedInfoForLocal *pack.ImageInfo - ReceivedInfoForRemote *pack.ImageInfo + ReceivedInfoForLocal *client.ImageInfo + ReceivedInfoForRemote *client.ImageInfo RecievedGeneralInfo inspectimage.GeneralInfo ReceivedErrorForLocal error ReceivedErrorForRemote error @@ -21,7 +21,7 @@ type FakeInspectImageWriter struct { func (w *FakeInspectImageWriter) Print( logger logging.Logger, sharedInfo inspectimage.GeneralInfo, - local, remote *pack.ImageInfo, + local, remote *client.ImageInfo, localErr, remoteErr error, ) error { w.ReceivedInfoForLocal = local diff --git a/internal/commands/inspect_builder.go b/internal/commands/inspect_builder.go index 721400c3d4..8afa0e3fd6 100644 --- a/internal/commands/inspect_builder.go +++ b/internal/commands/inspect_builder.go @@ -3,12 +3,11 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/internal/builder/writer" - - "github.com/buildpacks/pack" "github.com/buildpacks/pack/builder" + "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) // Deprecated: Use builder inspect instead. @@ -33,7 +32,7 @@ func InspectBuilder( if imageName == "" { suggestSettingBuilder(logger, inspector) - return pack.NewSoftError() + return client.NewSoftError() } return inspectBuilder(logger, imageName, flags, cfg, inspector, writerFactory) diff --git a/internal/commands/inspect_builder_test.go b/internal/commands/inspect_builder_test.go index 59bdf84b15..9ab7d9e191 100644 --- a/internal/commands/inspect_builder_test.go +++ b/internal/commands/inspect_builder_test.go @@ -10,11 +10,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -206,8 +206,8 @@ func testInspectBuilderCommand(t *testing.T, when spec.G, it spec.S) { err := command.Execute() assert.Error(err) - if !errors.Is(err, pack.SoftError{}) { - t.Fatalf("expect a pack.SoftError, got: %s", err) + if !errors.Is(err, client.SoftError{}) { + t.Fatalf("expect a client.SoftError, got: %s", err) } assert.Contains(outBuf.String(), `Please select a default builder with: diff --git a/internal/commands/inspect_buildpack.go b/internal/commands/inspect_buildpack.go index f46a309652..69d4d28c3c 100644 --- a/internal/commands/inspect_buildpack.go +++ b/internal/commands/inspect_buildpack.go @@ -8,21 +8,16 @@ import ( "text/tabwriter" "text/template" - strs "github.com/buildpacks/pack/internal/strings" - - "github.com/buildpacks/pack/internal/dist" - "github.com/pkg/errors" - - "github.com/buildpacks/pack/internal/buildpack" - "github.com/spf13/cobra" - "github.com/buildpacks/pack" + "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/config" + "github.com/buildpacks/pack/internal/dist" + strs "github.com/buildpacks/pack/internal/strings" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) const inspectBuildpackTemplate = ` @@ -92,7 +87,7 @@ func InspectBuildpack(logger logging.Logger, cfg config.Config, client PackClien return cmd } -func inspectAllBuildpacks(client PackClient, flags BuildpackInspectFlags, options ...pack.InspectBuildpackOptions) (string, error) { +func inspectAllBuildpacks(client PackClient, flags BuildpackInspectFlags, options ...client.InspectBuildpackOptions) (string, error) { buf := bytes.NewBuffer(nil) errArray := []error{} for _, option := range options { @@ -123,7 +118,7 @@ func inspectAllBuildpacks(client PackClient, flags BuildpackInspectFlags, option return buf.String(), nil } -func inspectBuildpackOutput(info *pack.BuildpackInfo, prefix string, flags BuildpackInspectFlags) (output []byte, err error) { +func inspectBuildpackOutput(info *client.BuildpackInfo, prefix string, flags BuildpackInspectFlags) (output []byte, err error) { tpl := template.Must(template.New("inspect-buildpack").Parse(inspectBuildpackTemplate)) bpOutput, err := buildpacksOutput(info.Buildpacks) if err != nil { @@ -198,7 +193,7 @@ func buildpacksOutput(bps []dist.BuildpackInfo) (string, error) { func detectionOrderOutput(order dist.Order, layers dist.BuildpackLayers, maxDepth int) (string, error) { buf := strings.Builder{} tabWriter := new(tabwriter.Writer).Init(&buf, writerMinWidth, writerTabWidth, defaultTabWidth, writerPadChar, writerFlags) - buildpackSet := map[pack.BuildpackInfoKey]bool{} + buildpackSet := map[client.BuildpackInfoKey]bool{} if err := orderOutputRecurrence(tabWriter, "", order, layers, buildpackSet, 0, maxDepth); err != nil { return "", err @@ -210,7 +205,7 @@ func detectionOrderOutput(order dist.Order, layers dist.BuildpackLayers, maxDept } // Recursively generate output for every buildpack in an order. -func orderOutputRecurrence(w io.Writer, prefix string, order dist.Order, layers dist.BuildpackLayers, buildpackSet map[pack.BuildpackInfoKey]bool, curDepth, maxDepth int) error { +func orderOutputRecurrence(w io.Writer, prefix string, order dist.Order, layers dist.BuildpackLayers, buildpackSet map[client.BuildpackInfoKey]bool, curDepth, maxDepth int) error { // exit if maxDepth is exceeded if validMaxDepth(maxDepth) && maxDepth <= curDepth { return nil @@ -225,7 +220,7 @@ func orderOutputRecurrence(w io.Writer, prefix string, order dist.Order, layers for bpIndex, buildpackEntry := range group.Group { lastBuildpack := bpIndex == len(group.Group)-1 - key := pack.BuildpackInfoKey{ + key := client.BuildpackInfoKey{ ID: buildpackEntry.ID, Version: buildpackEntry.Version, } diff --git a/internal/commands/inspect_buildpack_test.go b/internal/commands/inspect_buildpack_test.go index 34d5722807..cdf74c8607 100644 --- a/internal/commands/inspect_buildpack_test.go +++ b/internal/commands/inspect_buildpack_test.go @@ -5,18 +5,14 @@ import ( "fmt" "testing" - "github.com/pkg/errors" - - "github.com/buildpacks/pack/internal/image" - "github.com/buildpacks/lifecycle/api" "github.com/golang/mock/gomock" "github.com/heroku/color" + "github.com/pkg/errors" "github.com/sclevine/spec" "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/commands" @@ -25,6 +21,8 @@ import ( "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -47,8 +45,8 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { mockController *gomock.Controller mockClient *testmocks.MockPackClient cfg config.Config - complexInfo *pack.BuildpackInfo - simpleInfo *pack.BuildpackInfo + complexInfo *client.BuildpackInfo + simpleInfo *client.BuildpackInfo assert = h.NewAssertionManager(t) ) @@ -61,7 +59,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { DefaultRegistry: "default-registry", } - complexInfo = &pack.BuildpackInfo{ + complexInfo = &client.BuildpackInfo{ BuildpackMetadata: buildpackage.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", @@ -216,7 +214,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }, } - simpleInfo = &pack.BuildpackInfo{ + simpleInfo = &client.BuildpackInfo{ BuildpackMetadata: buildpackage.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/single-buildpack", @@ -279,13 +277,13 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "test/buildpack", Daemon: true, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "test/buildpack", Daemon: false, Registry: "default-registry", @@ -314,13 +312,13 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-local-test/buildpack", Daemon: true, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-local-test/buildpack", Daemon: false, Registry: "default-registry", @@ -344,13 +342,13 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: false, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: true, Registry: "default-registry", @@ -374,13 +372,13 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { complexInfo.Location = buildpack.PackageLocator simpleInfo.Location = buildpack.PackageLocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: false, Registry: "default-registry", }).Return(complexInfo, nil) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "only-remote-test/buildpack", Daemon: true, Registry: "default-registry", @@ -407,7 +405,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("uri is a local path", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -431,7 +429,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("uri is a local path", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "https://path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -459,7 +457,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("using the default registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:test/buildpack", Daemon: true, Registry: "default-registry", @@ -479,7 +477,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("using a user provided registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:test/buildpack", Daemon: true, Registry: "some-registry", @@ -504,7 +502,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { complexInfo.Location = buildpack.URILocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/other/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -522,7 +520,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("verbose flag is passed", func() { it.Before(func() { simpleInfo.Location = buildpack.URILocator - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "/another/path/to/test/buildpack", Daemon: true, Registry: "default-registry", @@ -539,17 +537,17 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("failure cases", func() { when("unable to inspect buildpack image", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect local failure-case/buildpack")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect local failure-case/buildpack")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "failure-case/buildpack", Daemon: false, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect remote failure-case/buildpack")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "unable to inspect remote failure-case/buildpack")) }) it("errors", func() { command.SetArgs([]string{"failure-case/buildpack"}) @@ -559,11 +557,11 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("unable to inspect buildpack archive", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "http://path/to/failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting local archive")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting local archive")) it("errors", func() { command.SetArgs([]string{"http://path/to/failure-case/buildpack"}) @@ -576,17 +574,17 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("unable to inspect both remote and local images", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "image-failure-case/buildpack", Daemon: true, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting local archive")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting local archive")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "image-failure-case/buildpack", Daemon: false, Registry: "default-registry", - }).Return(&pack.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting remote archive")) + }).Return(&client.BuildpackInfo{}, errors.Wrap(image.ErrNotFound, "error inspecting remote archive")) }) it("errors", func() { command.SetArgs([]string{"image-failure-case/buildpack"}) @@ -599,17 +597,17 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("unable to inspect buildpack on registry", func() { it.Before(func() { - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:registry-failure/buildpack", Daemon: true, Registry: "some-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting registry image")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting registry image")) - mockClient.EXPECT().InspectBuildpack(pack.InspectBuildpackOptions{ + mockClient.EXPECT().InspectBuildpack(client.InspectBuildpackOptions{ BuildpackName: "urn:cnb:registry:registry-failure/buildpack", Daemon: false, Registry: "some-registry", - }).Return(&pack.BuildpackInfo{}, errors.New("error inspecting registry image")) + }).Return(&client.BuildpackInfo{}, errors.New("error inspecting registry image")) }) it("errors", func() { diff --git a/internal/commands/inspect_image_test.go b/internal/commands/inspect_image_test.go index 64c8e615d2..26276b887b 100644 --- a/internal/commands/inspect_image_test.go +++ b/internal/commands/inspect_image_test.go @@ -11,7 +11,6 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/commands/testmocks" @@ -19,6 +18,7 @@ import ( "github.com/buildpacks/pack/internal/inspectimage" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -30,22 +30,22 @@ var ( Name: "some/image", } - expectedLocalImageInfo = &pack.ImageInfo{ + expectedLocalImageInfo = &client.ImageInfo{ StackID: "local.image.stack", Buildpacks: nil, Base: platform.RunImageMetadata{}, BOM: nil, Stack: platform.StackMetadata{}, - Processes: pack.ProcessDetails{}, + Processes: client.ProcessDetails{}, } - expectedRemoteImageInfo = &pack.ImageInfo{ + expectedRemoteImageInfo = &client.ImageInfo{ StackID: "remote.image.stack", Buildpacks: nil, Base: platform.RunImageMetadata{}, BOM: nil, Stack: platform.StackMetadata{}, - Processes: pack.ProcessDetails{}, + Processes: client.ProcessDetails{}, } ) diff --git a/internal/commands/package_buildpack.go b/internal/commands/package_buildpack.go index a50067b87d..ea179f2088 100644 --- a/internal/commands/package_buildpack.go +++ b/internal/commands/package_buildpack.go @@ -6,17 +6,17 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack" pubbldpkg "github.com/buildpacks/pack/buildpackage" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" ) // Deprecated: use BuildpackPackage instead // PackageBuildpack packages (a) buildpack(s) into OCI format, based on a package config -func PackageBuildpack(logger logging.Logger, cfg config.Config, client BuildpackPackager, packageConfigReader PackageConfigReader) *cobra.Command { +func PackageBuildpack(logger logging.Logger, cfg config.Config, packager BuildpackPackager, packageConfigReader PackageConfigReader) *cobra.Command { var flags BuildpackPackageFlags cmd := &cobra.Command{ @@ -61,7 +61,7 @@ func PackageBuildpack(logger logging.Logger, cfg config.Config, client Buildpack } name := args[0] - if err := client.PackageBuildpack(cmd.Context(), pack.PackageBuildpackOptions{ + if err := packager.PackageBuildpack(cmd.Context(), client.PackageBuildpackOptions{ RelativeBaseDir: relativeBaseDir, Name: name, Format: flags.Format, diff --git a/internal/commands/package_buildpack_test.go b/internal/commands/package_buildpack_test.go index 91df8e400f..9a0877f6ad 100644 --- a/internal/commands/package_buildpack_test.go +++ b/internal/commands/package_buildpack_test.go @@ -12,12 +12,12 @@ import ( "github.com/spf13/cobra" pubbldpkg "github.com/buildpacks/pack/buildpackage" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" + pubcfg "github.com/buildpacks/pack/pkg/config" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/rebase.go b/internal/commands/rebase.go index f4f2fe98ea..b1fd3d613e 100644 --- a/internal/commands/rebase.go +++ b/internal/commands/rebase.go @@ -5,16 +5,16 @@ import ( "github.com/spf13/cobra" - pubcfg "github.com/buildpacks/pack/config" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" ) -func Rebase(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { - var opts pack.RebaseOptions +func Rebase(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { + var opts client.RebaseOptions var policy string cmd := &cobra.Command{ @@ -38,7 +38,7 @@ func Rebase(logger logging.Logger, cfg config.Config, client PackClient) *cobra. return errors.Wrapf(err, "parsing pull policy %s", stringPolicy) } - if err := client.Rebase(cmd.Context(), opts); err != nil { + if err := pack.Rebase(cmd.Context(), opts); err != nil { return err } logger.Infof("Successfully rebased image %s", style.Symbol(opts.RepoName)) diff --git a/internal/commands/rebase_test.go b/internal/commands/rebase_test.go index 3e84c9ec4c..bdc7451040 100644 --- a/internal/commands/rebase_test.go +++ b/internal/commands/rebase_test.go @@ -6,14 +6,14 @@ import ( "github.com/heroku/color" - pubcfg "github.com/buildpacks/pack/config" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" "github.com/golang/mock/gomock" "github.com/sclevine/spec" "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" @@ -59,7 +59,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { when("image name is provided", func() { var ( repoName string - opts pack.RebaseOptions + opts client.RebaseOptions ) it.Before(func() { runImage := "test/image" @@ -73,7 +73,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { command = commands.Rebase(logger, cfg, mockClient) repoName = "test/repo-image" - opts = pack.RebaseOptions{ + opts = client.RebaseOptions{ RepoName: repoName, Publish: false, PullPolicy: pubcfg.PullAlways, diff --git a/internal/commands/register_buildpack.go b/internal/commands/register_buildpack.go index dc63116c79..fecb2e4ac9 100644 --- a/internal/commands/register_buildpack.go +++ b/internal/commands/register_buildpack.go @@ -3,16 +3,16 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/logging" ) // Deprecated: Use BuildpackRegister instead -func RegisterBuildpack(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { - var opts pack.RegisterBuildpackOptions +func RegisterBuildpack(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { + var opts client.RegisterBuildpackOptions var flags BuildpackRegisterFlags cmd := &cobra.Command{ @@ -32,7 +32,7 @@ func RegisterBuildpack(logger logging.Logger, cfg config.Config, client PackClie opts.URL = registry.URL opts.Name = registry.Name - if err := client.RegisterBuildpack(cmd.Context(), opts); err != nil { + if err := pack.RegisterBuildpack(cmd.Context(), opts); err != nil { return err } logger.Infof("Successfully registered %s", style.Symbol(opts.ImageName)) diff --git a/internal/commands/register_buildpack_test.go b/internal/commands/register_buildpack_test.go index 79991cbb71..ef8e8b3656 100644 --- a/internal/commands/register_buildpack_test.go +++ b/internal/commands/register_buildpack_test.go @@ -4,8 +4,8 @@ import ( "bytes" "testing" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" + "github.com/buildpacks/pack/pkg/client" "github.com/golang/mock/gomock" "github.com/sclevine/spec" @@ -62,7 +62,7 @@ func testRegisterBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) it("should work for required args", func() { - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/buildpacks/registry-index", @@ -90,7 +90,7 @@ func testRegisterBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }, } command = commands.RegisterBuildpack(logger, cfg, mockClient) - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/berneuse/buildpack-registry", @@ -134,7 +134,7 @@ func testRegisterBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }, }, } - opts := pack.RegisterBuildpackOptions{ + opts := client.RegisterBuildpackOptions{ ImageName: buildpackImage, Type: "github", URL: "https://github.com/override/buildpack-registry", diff --git a/internal/commands/set_default_builder_test.go b/internal/commands/set_default_builder_test.go index 9470c6b305..6a5bcda872 100644 --- a/internal/commands/set_default_builder_test.go +++ b/internal/commands/set_default_builder_test.go @@ -14,12 +14,12 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -58,7 +58,7 @@ func testSetDefaultBuilderCommand(t *testing.T, when spec.G, it spec.S) { when("#SetDefaultBuilder", func() { when("no builder provided", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&pack.BuilderInfo{}, nil).AnyTimes() + mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&client.BuilderInfo{}, nil).AnyTimes() }) it("display suggested builders", func() { @@ -70,7 +70,7 @@ func testSetDefaultBuilderCommand(t *testing.T, when spec.G, it spec.S) { when("empty builder name is provided", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&pack.BuilderInfo{}, nil).AnyTimes() + mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&client.BuilderInfo{}, nil).AnyTimes() }) it("display suggested builders", func() { @@ -84,7 +84,7 @@ func testSetDefaultBuilderCommand(t *testing.T, when spec.G, it spec.S) { when("in local", func() { it("sets default builder", func() { imageName := "some/image" - mockClient.EXPECT().InspectBuilder(imageName, true).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, true).Return(&client.BuilderInfo{ Stack: "test.stack.id", }, nil) @@ -100,7 +100,7 @@ func testSetDefaultBuilderCommand(t *testing.T, when spec.G, it spec.S) { localCall := mockClient.EXPECT().InspectBuilder(imageName, true).Return(nil, nil) - mockClient.EXPECT().InspectBuilder(imageName, false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(imageName, false).Return(&client.BuilderInfo{ Stack: "test.stack.id", }, nil).After(localCall) diff --git a/internal/commands/suggest_builders_test.go b/internal/commands/suggest_builders_test.go index 9d7d9efdec..b54ed13e25 100644 --- a/internal/commands/suggest_builders_test.go +++ b/internal/commands/suggest_builders_test.go @@ -10,12 +10,12 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -42,7 +42,7 @@ func testSuggestBuildersCommand(t *testing.T, when spec.G, it spec.S) { when("#WriteSuggestedBuilder", func() { when("description metadata exists", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder("gcr.io/some/builder:latest", false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder("gcr.io/some/builder:latest", false).Return(&client.BuilderInfo{ Description: "Remote description", }, nil) }) @@ -60,7 +60,7 @@ func testSuggestBuildersCommand(t *testing.T, when spec.G, it spec.S) { when("description metadata does not exist", func() { it.Before(func() { - mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&pack.BuilderInfo{ + mockClient.EXPECT().InspectBuilder(gomock.Any(), false).Return(&client.BuilderInfo{ Description: "", }, nil).AnyTimes() }) diff --git a/internal/commands/testmocks/mock_inspect_image_writer_factory.go b/internal/commands/testmocks/mock_inspect_image_writer_factory.go index 9f5a65c546..6f887e2e87 100644 --- a/internal/commands/testmocks/mock_inspect_image_writer_factory.go +++ b/internal/commands/testmocks/mock_inspect_image_writer_factory.go @@ -5,37 +5,35 @@ package testmocks import ( - reflect "reflect" - - gomock "github.com/golang/mock/gomock" - writer "github.com/buildpacks/pack/internal/inspectimage/writer" + gomock "github.com/golang/mock/gomock" + reflect "reflect" ) -// MockInspectImageWriterFactory is a mock of InspectImageWriterFactory interface. +// MockInspectImageWriterFactory is a mock of InspectImageWriterFactory interface type MockInspectImageWriterFactory struct { ctrl *gomock.Controller recorder *MockInspectImageWriterFactoryMockRecorder } -// MockInspectImageWriterFactoryMockRecorder is the mock recorder for MockInspectImageWriterFactory. +// MockInspectImageWriterFactoryMockRecorder is the mock recorder for MockInspectImageWriterFactory type MockInspectImageWriterFactoryMockRecorder struct { mock *MockInspectImageWriterFactory } -// NewMockInspectImageWriterFactory creates a new mock instance. +// NewMockInspectImageWriterFactory creates a new mock instance func NewMockInspectImageWriterFactory(ctrl *gomock.Controller) *MockInspectImageWriterFactory { mock := &MockInspectImageWriterFactory{ctrl: ctrl} mock.recorder = &MockInspectImageWriterFactoryMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockInspectImageWriterFactory) EXPECT() *MockInspectImageWriterFactoryMockRecorder { return m.recorder } -// Writer mocks base method. +// Writer mocks base method func (m *MockInspectImageWriterFactory) Writer(arg0 string, arg1 bool) (writer.InspectImageWriter, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Writer", arg0, arg1) @@ -44,7 +42,7 @@ func (m *MockInspectImageWriterFactory) Writer(arg0 string, arg1 bool) (writer.I return ret0, ret1 } -// Writer indicates an expected call of Writer. +// Writer indicates an expected call of Writer func (mr *MockInspectImageWriterFactoryMockRecorder) Writer(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Writer", reflect.TypeOf((*MockInspectImageWriterFactory)(nil).Writer), arg0, arg1) diff --git a/internal/commands/testmocks/mock_pack_client.go b/internal/commands/testmocks/mock_pack_client.go index f8483e62fb..49bd187940 100644 --- a/internal/commands/testmocks/mock_pack_client.go +++ b/internal/commands/testmocks/mock_pack_client.go @@ -6,193 +6,191 @@ package testmocks import ( context "context" - reflect "reflect" - + client "github.com/buildpacks/pack/pkg/client" gomock "github.com/golang/mock/gomock" - - pack "github.com/buildpacks/pack" + reflect "reflect" ) -// MockPackClient is a mock of PackClient interface. +// MockPackClient is a mock of PackClient interface type MockPackClient struct { ctrl *gomock.Controller recorder *MockPackClientMockRecorder } -// MockPackClientMockRecorder is the mock recorder for MockPackClient. +// MockPackClientMockRecorder is the mock recorder for MockPackClient type MockPackClientMockRecorder struct { mock *MockPackClient } -// NewMockPackClient creates a new mock instance. +// NewMockPackClient creates a new mock instance func NewMockPackClient(ctrl *gomock.Controller) *MockPackClient { mock := &MockPackClient{ctrl: ctrl} mock.recorder = &MockPackClientMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockPackClient) EXPECT() *MockPackClientMockRecorder { return m.recorder } -// Build mocks base method. -func (m *MockPackClient) Build(arg0 context.Context, arg1 pack.BuildOptions) error { +// Build mocks base method +func (m *MockPackClient) Build(arg0 context.Context, arg1 client.BuildOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Build", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// Build indicates an expected call of Build. +// Build indicates an expected call of Build func (mr *MockPackClientMockRecorder) Build(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Build", reflect.TypeOf((*MockPackClient)(nil).Build), arg0, arg1) } -// CreateBuilder mocks base method. -func (m *MockPackClient) CreateBuilder(arg0 context.Context, arg1 pack.CreateBuilderOptions) error { +// CreateBuilder mocks base method +func (m *MockPackClient) CreateBuilder(arg0 context.Context, arg1 client.CreateBuilderOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateBuilder", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// CreateBuilder indicates an expected call of CreateBuilder. +// CreateBuilder indicates an expected call of CreateBuilder func (mr *MockPackClientMockRecorder) CreateBuilder(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBuilder", reflect.TypeOf((*MockPackClient)(nil).CreateBuilder), arg0, arg1) } -// InspectBuilder mocks base method. -func (m *MockPackClient) InspectBuilder(arg0 string, arg1 bool, arg2 ...pack.BuilderInspectionModifier) (*pack.BuilderInfo, error) { +// InspectBuilder mocks base method +func (m *MockPackClient) InspectBuilder(arg0 string, arg1 bool, arg2 ...client.BuilderInspectionModifier) (*client.BuilderInfo, error) { m.ctrl.T.Helper() varargs := []interface{}{arg0, arg1} for _, a := range arg2 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "InspectBuilder", varargs...) - ret0, _ := ret[0].(*pack.BuilderInfo) + ret0, _ := ret[0].(*client.BuilderInfo) ret1, _ := ret[1].(error) return ret0, ret1 } -// InspectBuilder indicates an expected call of InspectBuilder. +// InspectBuilder indicates an expected call of InspectBuilder func (mr *MockPackClientMockRecorder) InspectBuilder(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0, arg1}, arg2...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InspectBuilder", reflect.TypeOf((*MockPackClient)(nil).InspectBuilder), varargs...) } -// InspectBuildpack mocks base method. -func (m *MockPackClient) InspectBuildpack(arg0 pack.InspectBuildpackOptions) (*pack.BuildpackInfo, error) { +// InspectBuildpack mocks base method +func (m *MockPackClient) InspectBuildpack(arg0 client.InspectBuildpackOptions) (*client.BuildpackInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InspectBuildpack", arg0) - ret0, _ := ret[0].(*pack.BuildpackInfo) + ret0, _ := ret[0].(*client.BuildpackInfo) ret1, _ := ret[1].(error) return ret0, ret1 } -// InspectBuildpack indicates an expected call of InspectBuildpack. +// InspectBuildpack indicates an expected call of InspectBuildpack func (mr *MockPackClientMockRecorder) InspectBuildpack(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InspectBuildpack", reflect.TypeOf((*MockPackClient)(nil).InspectBuildpack), arg0) } -// InspectImage mocks base method. -func (m *MockPackClient) InspectImage(arg0 string, arg1 bool) (*pack.ImageInfo, error) { +// InspectImage mocks base method +func (m *MockPackClient) InspectImage(arg0 string, arg1 bool) (*client.ImageInfo, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InspectImage", arg0, arg1) - ret0, _ := ret[0].(*pack.ImageInfo) + ret0, _ := ret[0].(*client.ImageInfo) ret1, _ := ret[1].(error) return ret0, ret1 } -// InspectImage indicates an expected call of InspectImage. +// InspectImage indicates an expected call of InspectImage func (mr *MockPackClientMockRecorder) InspectImage(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InspectImage", reflect.TypeOf((*MockPackClient)(nil).InspectImage), arg0, arg1) } -// NewBuildpack mocks base method. -func (m *MockPackClient) NewBuildpack(arg0 context.Context, arg1 pack.NewBuildpackOptions) error { +// NewBuildpack mocks base method +func (m *MockPackClient) NewBuildpack(arg0 context.Context, arg1 client.NewBuildpackOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewBuildpack", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// NewBuildpack indicates an expected call of NewBuildpack. +// NewBuildpack indicates an expected call of NewBuildpack func (mr *MockPackClientMockRecorder) NewBuildpack(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBuildpack", reflect.TypeOf((*MockPackClient)(nil).NewBuildpack), arg0, arg1) } -// PackageBuildpack mocks base method. -func (m *MockPackClient) PackageBuildpack(arg0 context.Context, arg1 pack.PackageBuildpackOptions) error { +// PackageBuildpack mocks base method +func (m *MockPackClient) PackageBuildpack(arg0 context.Context, arg1 client.PackageBuildpackOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PackageBuildpack", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// PackageBuildpack indicates an expected call of PackageBuildpack. +// PackageBuildpack indicates an expected call of PackageBuildpack func (mr *MockPackClientMockRecorder) PackageBuildpack(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PackageBuildpack", reflect.TypeOf((*MockPackClient)(nil).PackageBuildpack), arg0, arg1) } -// PullBuildpack mocks base method. -func (m *MockPackClient) PullBuildpack(arg0 context.Context, arg1 pack.PullBuildpackOptions) error { +// PullBuildpack mocks base method +func (m *MockPackClient) PullBuildpack(arg0 context.Context, arg1 client.PullBuildpackOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PullBuildpack", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// PullBuildpack indicates an expected call of PullBuildpack. +// PullBuildpack indicates an expected call of PullBuildpack func (mr *MockPackClientMockRecorder) PullBuildpack(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PullBuildpack", reflect.TypeOf((*MockPackClient)(nil).PullBuildpack), arg0, arg1) } -// Rebase mocks base method. -func (m *MockPackClient) Rebase(arg0 context.Context, arg1 pack.RebaseOptions) error { +// Rebase mocks base method +func (m *MockPackClient) Rebase(arg0 context.Context, arg1 client.RebaseOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Rebase", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// Rebase indicates an expected call of Rebase. +// Rebase indicates an expected call of Rebase func (mr *MockPackClientMockRecorder) Rebase(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Rebase", reflect.TypeOf((*MockPackClient)(nil).Rebase), arg0, arg1) } -// RegisterBuildpack mocks base method. -func (m *MockPackClient) RegisterBuildpack(arg0 context.Context, arg1 pack.RegisterBuildpackOptions) error { +// RegisterBuildpack mocks base method +func (m *MockPackClient) RegisterBuildpack(arg0 context.Context, arg1 client.RegisterBuildpackOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterBuildpack", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } -// RegisterBuildpack indicates an expected call of RegisterBuildpack. +// RegisterBuildpack indicates an expected call of RegisterBuildpack func (mr *MockPackClientMockRecorder) RegisterBuildpack(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterBuildpack", reflect.TypeOf((*MockPackClient)(nil).RegisterBuildpack), arg0, arg1) } -// YankBuildpack mocks base method. -func (m *MockPackClient) YankBuildpack(arg0 pack.YankBuildpackOptions) error { +// YankBuildpack mocks base method +func (m *MockPackClient) YankBuildpack(arg0 client.YankBuildpackOptions) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "YankBuildpack", arg0) ret0, _ := ret[0].(error) return ret0 } -// YankBuildpack indicates an expected call of YankBuildpack. +// YankBuildpack indicates an expected call of YankBuildpack func (mr *MockPackClientMockRecorder) YankBuildpack(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "YankBuildpack", reflect.TypeOf((*MockPackClient)(nil).YankBuildpack), arg0) diff --git a/internal/commands/yank_buildpack.go b/internal/commands/yank_buildpack.go index e2b68d65c4..c6f79f3584 100644 --- a/internal/commands/yank_buildpack.go +++ b/internal/commands/yank_buildpack.go @@ -3,15 +3,14 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack" - "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/internal/config" + "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/client" ) // Deprecated: Use yank instead -func YankBuildpack(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { +func YankBuildpack(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { var flags BuildpackYankFlags cmd := &cobra.Command{ @@ -33,7 +32,7 @@ func YankBuildpack(logger logging.Logger, cfg config.Config, client PackClient) return err } - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: id, Version: version, Type: "github", @@ -41,7 +40,7 @@ func YankBuildpack(logger logging.Logger, cfg config.Config, client PackClient) Yank: !flags.Undo, } - if err := client.YankBuildpack(opts); err != nil { + if err := pack.YankBuildpack(opts); err != nil { return err } logger.Infof("Successfully yanked %s", style.Symbol(buildpackIDVersion)) diff --git a/internal/commands/yank_buildpack_test.go b/internal/commands/yank_buildpack_test.go index 0792cd14b4..703968705e 100644 --- a/internal/commands/yank_buildpack_test.go +++ b/internal/commands/yank_buildpack_test.go @@ -11,8 +11,8 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/commands" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" @@ -64,7 +64,7 @@ func testYankBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) it("should work for required args", func() { - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -99,7 +99,7 @@ func testYankBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }, } command = commands.YankBuildpack(logger, cfg, mockClient) - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -116,7 +116,7 @@ func testYankBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) it("should undo", func() { - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", @@ -150,7 +150,7 @@ func testYankBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }, }, } - opts := pack.YankBuildpackOptions{ + opts := client.YankBuildpackOptions{ ID: "heroku/rust", Version: "0.0.1", Type: "github", diff --git a/internal/dist/testmocks/mock_buildpack.go b/internal/dist/testmocks/mock_buildpack.go index 0be13655e0..efa16e5841 100644 --- a/internal/dist/testmocks/mock_buildpack.go +++ b/internal/dist/testmocks/mock_buildpack.go @@ -5,38 +5,36 @@ package testmocks import ( + dist "github.com/buildpacks/pack/internal/dist" + gomock "github.com/golang/mock/gomock" io "io" reflect "reflect" - - gomock "github.com/golang/mock/gomock" - - dist "github.com/buildpacks/pack/internal/dist" ) -// MockBuildpack is a mock of Buildpack interface. +// MockBuildpack is a mock of Buildpack interface type MockBuildpack struct { ctrl *gomock.Controller recorder *MockBuildpackMockRecorder } -// MockBuildpackMockRecorder is the mock recorder for MockBuildpack. +// MockBuildpackMockRecorder is the mock recorder for MockBuildpack type MockBuildpackMockRecorder struct { mock *MockBuildpack } -// NewMockBuildpack creates a new mock instance. +// NewMockBuildpack creates a new mock instance func NewMockBuildpack(ctrl *gomock.Controller) *MockBuildpack { mock := &MockBuildpack{ctrl: ctrl} mock.recorder = &MockBuildpackMockRecorder{mock} return mock } -// EXPECT returns an object that allows the caller to indicate expected use. +// EXPECT returns an object that allows the caller to indicate expected use func (m *MockBuildpack) EXPECT() *MockBuildpackMockRecorder { return m.recorder } -// Descriptor mocks base method. +// Descriptor mocks base method func (m *MockBuildpack) Descriptor() dist.BuildpackDescriptor { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Descriptor") @@ -44,13 +42,13 @@ func (m *MockBuildpack) Descriptor() dist.BuildpackDescriptor { return ret0 } -// Descriptor indicates an expected call of Descriptor. +// Descriptor indicates an expected call of Descriptor func (mr *MockBuildpackMockRecorder) Descriptor() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Descriptor", reflect.TypeOf((*MockBuildpack)(nil).Descriptor)) } -// Open mocks base method. +// Open mocks base method func (m *MockBuildpack) Open() (io.ReadCloser, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Open") @@ -59,7 +57,7 @@ func (m *MockBuildpack) Open() (io.ReadCloser, error) { return ret0, ret1 } -// Open indicates an expected call of Open. +// Open indicates an expected call of Open func (mr *MockBuildpackMockRecorder) Open() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Open", reflect.TypeOf((*MockBuildpack)(nil).Open)) diff --git a/internal/fakes/fake_image_fetcher.go b/internal/fakes/fake_image_fetcher.go index 142d82aa29..26476e5d15 100644 --- a/internal/fakes/fake_image_fetcher.go +++ b/internal/fakes/fake_image_fetcher.go @@ -3,12 +3,12 @@ package fakes import ( "context" - "github.com/buildpacks/pack/config" + "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/imgutil" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/image" ) type FetchArgs struct { diff --git a/internal/inspectimage/bom_display.go b/internal/inspectimage/bom_display.go index 85dbe1bd8f..b0c1efdc4d 100644 --- a/internal/inspectimage/bom_display.go +++ b/internal/inspectimage/bom_display.go @@ -3,8 +3,8 @@ package inspectimage import ( "github.com/buildpacks/lifecycle/buildpack" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/client" ) type BOMDisplay struct { @@ -21,7 +21,7 @@ type BOMEntryDisplay struct { Buildpack dist.BuildpackRef `json:"buildpacks" yaml:"buildpacks" toml:"buildpacks"` } -func NewBOMDisplay(info *pack.ImageInfo) []BOMEntryDisplay { +func NewBOMDisplay(info *client.ImageInfo) []BOMEntryDisplay { if info == nil { return nil } diff --git a/internal/inspectimage/info_display.go b/internal/inspectimage/info_display.go index 0b70d2b372..06a0e557d6 100644 --- a/internal/inspectimage/info_display.go +++ b/internal/inspectimage/info_display.go @@ -5,9 +5,9 @@ import ( "github.com/buildpacks/lifecycle/launch" "github.com/buildpacks/lifecycle/platform" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/client" ) type GeneralInfo struct { @@ -52,7 +52,7 @@ type InspectOutput struct { Local *InfoDisplay `json:"local_info" yaml:"local_info" toml:"local_info"` } -func NewInfoDisplay(info *pack.ImageInfo, generalInfo GeneralInfo) *InfoDisplay { +func NewInfoDisplay(info *client.ImageInfo, generalInfo GeneralInfo) *InfoDisplay { if info == nil { return nil } @@ -69,7 +69,7 @@ func NewInfoDisplay(info *pack.ImageInfo, generalInfo GeneralInfo) *InfoDisplay // private functions // -func getConfigMirrors(info *pack.ImageInfo, imageMirrors []config.RunImage) []string { +func getConfigMirrors(info *client.ImageInfo, imageMirrors []config.RunImage) []string { var runImage string if info != nil { runImage = info.Stack.RunImage.Image @@ -90,7 +90,7 @@ func displayBase(base platform.RunImageMetadata) BaseDisplay { } } -func displayMirrors(info *pack.ImageInfo, generalInfo GeneralInfo) []RunImageMirrorDisplay { +func displayMirrors(info *client.ImageInfo, generalInfo GeneralInfo) []RunImageMirrorDisplay { // add all user configured run images, then add run images provided by info var result []RunImageMirrorDisplay if info == nil { @@ -139,7 +139,7 @@ func displayBuildpacks(buildpacks []buildpack.GroupBuildpack) []dist.BuildpackIn return result } -func displayProcesses(details pack.ProcessDetails) []ProcessDisplay { +func displayProcesses(details client.ProcessDetails) []ProcessDisplay { var result []ProcessDisplay detailsArray := details.OtherProcesses if details.DefaultProcess != nil { diff --git a/internal/inspectimage/writer/bom_json_test.go b/internal/inspectimage/writer/bom_json_test.go index e6f23af3d6..3ec2d4291c 100644 --- a/internal/inspectimage/writer/bom_json_test.go +++ b/internal/inspectimage/writer/bom_json_test.go @@ -9,10 +9,10 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -27,8 +27,8 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedLocalOutput = `{ "local": [ @@ -87,7 +87,7 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{{ Require: buildpack.Require{ Name: "name-1", @@ -108,7 +108,7 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage"}, }}} - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{{ Require: buildpack.Require{ Name: "name-1", diff --git a/internal/inspectimage/writer/bom_yaml_test.go b/internal/inspectimage/writer/bom_yaml_test.go index 3dabe3d462..5c7478f02e 100644 --- a/internal/inspectimage/writer/bom_yaml_test.go +++ b/internal/inspectimage/writer/bom_yaml_test.go @@ -9,10 +9,10 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -27,8 +27,8 @@ func testYAMLBOM(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedLocalOutput = `--- local: @@ -73,7 +73,7 @@ remote: } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{{ Require: buildpack.Require{ Name: "name-1", @@ -94,7 +94,7 @@ remote: Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage"}, }}} - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{{ Require: buildpack.Require{ Name: "name-1", diff --git a/internal/inspectimage/writer/factory.go b/internal/inspectimage/writer/factory.go index 9bd85ea034..79bc3219f4 100644 --- a/internal/inspectimage/writer/factory.go +++ b/internal/inspectimage/writer/factory.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/buildpacks/pack/internal/inspectimage" + "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/internal/style" @@ -17,7 +17,7 @@ type InspectImageWriter interface { Print( logger logging.Logger, sharedInfo inspectimage.GeneralInfo, - local, remote *pack.ImageInfo, + local, remote *client.ImageInfo, localErr, remoteErr error, ) error } diff --git a/internal/inspectimage/writer/human_readable.go b/internal/inspectimage/writer/human_readable.go index a0958be5d5..e1f3024ee1 100644 --- a/internal/inspectimage/writer/human_readable.go +++ b/internal/inspectimage/writer/human_readable.go @@ -8,8 +8,8 @@ import ( "text/template" "github.com/buildpacks/pack/internal/inspectimage" + "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack" strs "github.com/buildpacks/pack/internal/strings" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" @@ -24,7 +24,7 @@ func NewHumanReadable() *HumanReadable { func (h *HumanReadable) Print( logger logging.Logger, generalInfo inspectimage.GeneralInfo, - local, remote *pack.ImageInfo, + local, remote *client.ImageInfo, localErr, remoteErr error, ) error { if local == nil && remote == nil { diff --git a/internal/inspectimage/writer/human_readable_test.go b/internal/inspectimage/writer/human_readable_test.go index b59feb47b2..98b77153f2 100644 --- a/internal/inspectimage/writer/human_readable_test.go +++ b/internal/inspectimage/writer/human_readable_test.go @@ -13,11 +13,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -32,8 +32,8 @@ func testHumanReadable(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedRemoteOutput = `REMOTE: @@ -97,7 +97,7 @@ Processes: } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ StackID: "test.stack.id.remote", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -133,7 +133,7 @@ Processes: }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-remote-type", Command: "/some/remote command", @@ -151,7 +151,7 @@ Processes: }, } - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ StackID: "test.stack.id.local", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.local", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -181,7 +181,7 @@ Processes: }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-local-type", Command: "/some/local command", diff --git a/internal/inspectimage/writer/json_test.go b/internal/inspectimage/writer/json_test.go index d8f2158d65..73107791b8 100644 --- a/internal/inspectimage/writer/json_test.go +++ b/internal/inspectimage/writer/json_test.go @@ -11,11 +11,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -30,8 +30,8 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedLocalOutput = `{ "local_info": { @@ -166,7 +166,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ StackID: "test.stack.id.remote", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -201,7 +201,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-remote-type", Command: "/some/remote command", @@ -219,7 +219,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { }, } - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ StackID: "test.stack.id.local", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.local", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -248,7 +248,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-local-type", Command: "/some/local command", diff --git a/internal/inspectimage/writer/structured_bom_format.go b/internal/inspectimage/writer/structured_bom_format.go index e91780373a..e2d246ad26 100644 --- a/internal/inspectimage/writer/structured_bom_format.go +++ b/internal/inspectimage/writer/structured_bom_format.go @@ -4,10 +4,10 @@ import ( "fmt" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/inspectimage" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/logging" ) @@ -18,7 +18,7 @@ type StructuredBOMFormat struct { func (w *StructuredBOMFormat) Print( logger logging.Logger, generalInfo inspectimage.GeneralInfo, - local, remote *pack.ImageInfo, + local, remote *client.ImageInfo, localErr, remoteErr error, ) error { if local == nil && remote == nil { diff --git a/internal/inspectimage/writer/structured_bom_format_test.go b/internal/inspectimage/writer/structured_bom_format_test.go index 78272fcdd0..a5732c0ed8 100644 --- a/internal/inspectimage/writer/structured_bom_format_test.go +++ b/internal/inspectimage/writer/structured_bom_format_test.go @@ -11,12 +11,12 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -31,8 +31,8 @@ func testStructuredBOMFormat(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf *bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo generalInfo inspectimage.GeneralInfo logger *ilogging.LogWithWriters ) @@ -41,7 +41,7 @@ func testStructuredBOMFormat(t *testing.T, when spec.G, it spec.S) { it.Before(func() { outBuf = bytes.NewBuffer(nil) logger = ilogging.NewLogWithWriters(outBuf, outBuf) - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{ { Require: buildpack.Require{ @@ -58,7 +58,7 @@ func testStructuredBOMFormat(t *testing.T, when spec.G, it spec.S) { }, }, } - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{ { Require: buildpack.Require{ diff --git a/internal/inspectimage/writer/structured_format.go b/internal/inspectimage/writer/structured_format.go index fc42731950..40526ea7d0 100644 --- a/internal/inspectimage/writer/structured_format.go +++ b/internal/inspectimage/writer/structured_format.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/buildpacks/pack/internal/inspectimage" + "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" ) @@ -17,7 +17,7 @@ type StructuredFormat struct { func (w *StructuredFormat) Print( logger logging.Logger, generalInfo inspectimage.GeneralInfo, - local, remote *pack.ImageInfo, + local, remote *client.ImageInfo, localErr, remoteErr error, ) error { // synthesize all objects here using methods diff --git a/internal/inspectimage/writer/structured_format_test.go b/internal/inspectimage/writer/structured_format_test.go index eedf46cbd7..dfc68a1f1d 100644 --- a/internal/inspectimage/writer/structured_format_test.go +++ b/internal/inspectimage/writer/structured_format_test.go @@ -6,17 +6,15 @@ import ( "fmt" "testing" - "github.com/buildpacks/pack/internal/inspectimage" - - "github.com/buildpacks/pack/internal/inspectimage/writer" - "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" + "github.com/buildpacks/pack/internal/inspectimage" + "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -31,14 +29,14 @@ func testStructuredFormat(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo ) when("Print", func() { it.Before(func() { - remoteInfo = &pack.ImageInfo{} - localInfo = &pack.ImageInfo{} + remoteInfo = &client.ImageInfo{} + localInfo = &client.ImageInfo{} outBuf = bytes.Buffer{} }) diff --git a/internal/inspectimage/writer/toml_test.go b/internal/inspectimage/writer/toml_test.go index c6f57185c7..341436a56a 100644 --- a/internal/inspectimage/writer/toml_test.go +++ b/internal/inspectimage/writer/toml_test.go @@ -11,11 +11,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -30,8 +30,8 @@ func testTOML(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedLocalOutput = `[local_info] stack = 'test.stack.id.local' @@ -152,7 +152,7 @@ args = [ } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ StackID: "test.stack.id.remote", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -187,7 +187,7 @@ args = [ }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-remote-type", Command: "/some/remote command", @@ -205,7 +205,7 @@ args = [ }, } - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ StackID: "test.stack.id.local", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.local", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -234,7 +234,7 @@ args = [ }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-local-type", Command: "/some/local command", diff --git a/internal/inspectimage/writer/yaml_test.go b/internal/inspectimage/writer/yaml_test.go index da980765c7..814a1b674b 100644 --- a/internal/inspectimage/writer/yaml_test.go +++ b/internal/inspectimage/writer/yaml_test.go @@ -11,11 +11,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -30,8 +30,8 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { assert = h.NewAssertionManager(t) outBuf bytes.Buffer - remoteInfo *pack.ImageInfo - localInfo *pack.ImageInfo + remoteInfo *client.ImageInfo + localInfo *client.ImageInfo expectedLocalOutput = `--- local_info: @@ -120,7 +120,7 @@ remote_info: } } - remoteInfo = &pack.ImageInfo{ + remoteInfo = &client.ImageInfo{ StackID: "test.stack.id.remote", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -155,7 +155,7 @@ remote_info: }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-remote-type", Command: "/some/remote command", @@ -173,7 +173,7 @@ remote_info: }, } - localInfo = &pack.ImageInfo{ + localInfo = &client.ImageInfo{ StackID: "test.stack.id.local", Buildpacks: []buildpack.GroupBuildpack{ {ID: "test.bp.one.local", Version: "1.0.0", Homepage: "https://some-homepage-one"}, @@ -202,7 +202,7 @@ remote_info: }, Buildpack: buildpack.GroupBuildpack{ID: "test.bp.one.remote", Version: "1.0.0", Homepage: "https://some-homepage-one"}, }}, - Processes: pack.ProcessDetails{ + Processes: client.ProcessDetails{ DefaultProcess: &launch.Process{ Type: "some-local-type", Command: "/some/local command", diff --git a/logging/logging.go b/logging/logging.go index 597c981596..bcf63be8c7 100644 --- a/logging/logging.go +++ b/logging/logging.go @@ -1,4 +1,4 @@ -// Package logging defines the minimal interface that loggers must support to be used by pack. +// Package logging defines the minimal interface that loggers must support to be used by client. package logging import ( diff --git a/pack.go b/pack.go deleted file mode 100644 index 5d50f4b8d9..0000000000 --- a/pack.go +++ /dev/null @@ -1,31 +0,0 @@ -package pack - -import ( - "context" - - "github.com/pkg/errors" - - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" - "github.com/buildpacks/pack/internal/style" -) - -var ( - // Version is the version of `pack`. It is injected at compile time. - Version = "0.0.0" -) - -func extractPackagedBuildpacks(ctx context.Context, pkgImageRef string, fetcher ImageFetcher, fetchOptions image.FetchOptions) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { - pkgImage, err := fetcher.Fetch(ctx, pkgImageRef, fetchOptions) - if err != nil { - return nil, nil, errors.Wrapf(err, "fetching image") - } - - mainBP, depBPs, err = buildpackage.ExtractBuildpacks(pkgImage) - if err != nil { - return nil, nil, errors.Wrapf(err, "extracting buildpacks from %s", style.Symbol(pkgImageRef)) - } - - return mainBP, depBPs, nil -} diff --git a/internal/blob/blob.go b/pkg/blob/blob.go similarity index 100% rename from internal/blob/blob.go rename to pkg/blob/blob.go diff --git a/internal/blob/blob_test.go b/pkg/blob/blob_test.go similarity index 96% rename from internal/blob/blob_test.go rename to pkg/blob/blob_test.go index 7ec67eef69..298589403f 100644 --- a/internal/blob/blob_test.go +++ b/pkg/blob/blob_test.go @@ -8,7 +8,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/blob" + "github.com/buildpacks/pack/pkg/blob" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/blob/downloader.go b/pkg/blob/downloader.go similarity index 100% rename from internal/blob/downloader.go rename to pkg/blob/downloader.go diff --git a/internal/blob/downloader_test.go b/pkg/blob/downloader_test.go similarity index 97% rename from internal/blob/downloader_test.go rename to pkg/blob/downloader_test.go index 855144b29e..657b6f5e2a 100644 --- a/internal/blob/downloader_test.go +++ b/pkg/blob/downloader_test.go @@ -13,11 +13,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -32,7 +32,7 @@ func testDownloader(t *testing.T, when spec.G, it spec.S) { var ( cacheDir string err error - subject pack.Downloader + subject client.Downloader ) it.Before(func() { diff --git a/internal/blob/testdata/blob/file.txt b/pkg/blob/testdata/blob/file.txt similarity index 100% rename from internal/blob/testdata/blob/file.txt rename to pkg/blob/testdata/blob/file.txt diff --git a/internal/blob/testdata/buildpack/buildpack.toml b/pkg/blob/testdata/buildpack/buildpack.toml similarity index 100% rename from internal/blob/testdata/buildpack/buildpack.toml rename to pkg/blob/testdata/buildpack/buildpack.toml diff --git a/internal/blob/testdata/lifecycle/analyzer b/pkg/blob/testdata/lifecycle/analyzer similarity index 100% rename from internal/blob/testdata/lifecycle/analyzer rename to pkg/blob/testdata/lifecycle/analyzer diff --git a/internal/blob/testdata/lifecycle/builder b/pkg/blob/testdata/lifecycle/builder similarity index 100% rename from internal/blob/testdata/lifecycle/builder rename to pkg/blob/testdata/lifecycle/builder diff --git a/internal/blob/testdata/lifecycle/cacher b/pkg/blob/testdata/lifecycle/cacher similarity index 100% rename from internal/blob/testdata/lifecycle/cacher rename to pkg/blob/testdata/lifecycle/cacher diff --git a/internal/blob/testdata/lifecycle/detector b/pkg/blob/testdata/lifecycle/detector similarity index 100% rename from internal/blob/testdata/lifecycle/detector rename to pkg/blob/testdata/lifecycle/detector diff --git a/internal/blob/testdata/lifecycle/exporter b/pkg/blob/testdata/lifecycle/exporter similarity index 100% rename from internal/blob/testdata/lifecycle/exporter rename to pkg/blob/testdata/lifecycle/exporter diff --git a/internal/blob/testdata/lifecycle/launcher b/pkg/blob/testdata/lifecycle/launcher similarity index 100% rename from internal/blob/testdata/lifecycle/launcher rename to pkg/blob/testdata/lifecycle/launcher diff --git a/internal/blob/testdata/lifecycle/restorer b/pkg/blob/testdata/lifecycle/restorer similarity index 100% rename from internal/blob/testdata/lifecycle/restorer rename to pkg/blob/testdata/lifecycle/restorer diff --git a/buildpack_downloader.go b/pkg/buildpack/downloader/buildpack_downloader.go similarity index 50% rename from buildpack_downloader.go rename to pkg/buildpack/downloader/buildpack_downloader.go index 4816c2c32b..938bff1c67 100644 --- a/buildpack_downloader.go +++ b/pkg/buildpack/downloader/buildpack_downloader.go @@ -1,4 +1,4 @@ -package pack +package downloader import ( "context" @@ -6,26 +6,46 @@ import ( "github.com/pkg/errors" - "github.com/buildpacks/pack/config" + "github.com/buildpacks/imgutil" "github.com/buildpacks/pack/internal/buildpack" + "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) +type ImageFetcher interface { + Fetch(ctx context.Context, name string, options image.FetchOptions) (imgutil.Image, error) +} + +type Downloader interface { + Download(ctx context.Context, pathOrURI string) (blob.Blob, error) +} + +//go:generate mockgen -package testmocks -destination ../../testmocks/mock_registry_resolver.go github.com/buildpacks/pack/pkg/buildpack/downloader RegistryResolver + +type RegistryResolver interface { + Resolve(registryName, bpURI string) (string, error) +} + type buildpackDownloader struct { - logger logging.Logger - imageFetcher ImageFetcher - downloader Downloader + logger logging.Logger + imageFetcher ImageFetcher + downloader Downloader + registryResolver RegistryResolver } -func NewBuildpackDownloader(logger logging.Logger, imageFetcher ImageFetcher, downloader Downloader) *buildpackDownloader { //nolint:golint,gosimple +func NewBuildpackDownloader(logger logging.Logger, imageFetcher ImageFetcher, downloader Downloader, registryResolver RegistryResolver) *buildpackDownloader { //nolint:golint,gosimple return &buildpackDownloader{ - logger: logger, - imageFetcher: imageFetcher, - downloader: downloader, + logger: logger, + imageFetcher: imageFetcher, + downloader: downloader, + registryResolver: registryResolver, } } @@ -73,17 +93,12 @@ func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, } case buildpack.RegistryLocator: c.logger.Debugf("Downloading buildpack from registry: %s", style.Symbol(buildpackURI)) - registryCache, err := getRegistry(c.logger, opts.RegistryName) - if err != nil { - return nil, nil, errors.Wrapf(err, "invalid registry '%s'", opts.RegistryName) - } - - registryBp, err := registryCache.LocateBuildpack(buildpackURI) + address, err := c.registryResolver.Resolve(opts.RegistryName, buildpackURI) if err != nil { - return nil, nil, errors.Wrapf(err, "locating in registry %s", style.Symbol(buildpackURI)) + return nil, nil, errors.Wrapf(err, "locating in registry: %s", style.Symbol(buildpackURI)) } - mainBP, depBPs, err = extractPackagedBuildpacks(ctx, registryBp.Address, c.imageFetcher, image.FetchOptions{Daemon: opts.Daemon, PullPolicy: opts.PullPolicy}) + mainBP, depBPs, err = extractPackagedBuildpacks(ctx, address, c.imageFetcher, image.FetchOptions{Daemon: opts.Daemon, PullPolicy: opts.PullPolicy}) if err != nil { return nil, nil, errors.Wrapf(err, "extracting from registry %s", style.Symbol(buildpackURI)) } @@ -109,3 +124,44 @@ func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, } return mainBP, depBPs, nil } + +// decomposeBuildpack decomposes a buildpack blob into the main builder (order buildpack) and it's dependencies buildpacks. +func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { + isOCILayout, err := buildpackage.IsOCILayoutBlob(blob) + if err != nil { + return mainBP, depBPs, errors.Wrap(err, "inspecting buildpack blob") + } + + if isOCILayout { + mainBP, depBPs, err = buildpackage.BuildpacksFromOCILayoutBlob(blob) + if err != nil { + return mainBP, depBPs, errors.Wrap(err, "extracting buildpacks") + } + } else { + layerWriterFactory, err := layer.NewWriterFactory(imageOS) + if err != nil { + return mainBP, depBPs, errors.Wrapf(err, "get tar writer factory for OS %s", style.Symbol(imageOS)) + } + + mainBP, err = dist.BuildpackFromRootBlob(blob, layerWriterFactory) + if err != nil { + return mainBP, depBPs, errors.Wrap(err, "reading buildpack") + } + } + + return mainBP, depBPs, nil +} + +func extractPackagedBuildpacks(ctx context.Context, pkgImageRef string, fetcher ImageFetcher, fetchOptions image.FetchOptions) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { + pkgImage, err := fetcher.Fetch(ctx, pkgImageRef, fetchOptions) + if err != nil { + return nil, nil, errors.Wrapf(err, "fetching image") + } + + mainBP, depBPs, err = buildpackage.ExtractBuildpacks(pkgImage) + if err != nil { + return nil, nil, errors.Wrapf(err, "extracting buildpacks from %s", style.Symbol(pkgImageRef)) + } + + return mainBP, depBPs, nil +} diff --git a/buildpack_downloader_test.go b/pkg/buildpack/downloader/buildpack_downloader_test.go similarity index 70% rename from buildpack_downloader_test.go rename to pkg/buildpack/downloader/buildpack_downloader_test.go index 4d9b31044e..9117659819 100644 --- a/buildpack_downloader_test.go +++ b/pkg/buildpack/downloader/buildpack_downloader_test.go @@ -1,4 +1,4 @@ -package pack_test +package downloader_test import ( "bytes" @@ -18,19 +18,19 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" - cfg "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - image "github.com/buildpacks/pack/internal/image" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/config" + image "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestBuildpackDownloader(t *testing.T) { @@ -38,19 +38,21 @@ func TestBuildpackDownloader(t *testing.T) { defer color.Disable(false) spec.Run(t, "BuildpackDownloader", testBuildpackDownloader, spec.Report(report.Terminal{})) } + func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { var ( - mockController *gomock.Controller - mockDownloader *testmocks.MockDownloader - mockImageFactory *testmocks.MockImageFactory - mockImageFetcher *testmocks.MockImageFetcher - mockDockerClient *testmocks.MockCommonAPIClient - subject *pack.Client - buildpackDownloader pack.BuildpackDownloader - logger logging.Logger - out bytes.Buffer - tmpDir string + mockController *gomock.Controller + mockDownloader *testmocks.MockDownloader + mockImageFactory *testmocks.MockImageFactory + mockImageFetcher *testmocks.MockImageFetcher + mockRegistryResolver *testmocks.MockRegistryResolver + mockDockerClient *testmocks.MockCommonAPIClient + buildpackDownloader client.BuildpackDownloader + logger logging.Logger + out bytes.Buffer + tmpDir string ) + var createBuildpack = func(descriptor dist.BuildpackDescriptor) string { bp, err := ifakes.NewFakeBuildpackBlob(descriptor, 0644) h.AssertNil(t, err) @@ -63,7 +65,16 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { packageImage := fakes.NewImage(imageName, "", nil) mockImageFactory.EXPECT().NewImage(packageImage.Name(), false, "linux").Return(packageImage, nil) - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + pack, err := client.NewClient( + client.WithLogger(logger), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithDockerClient(mockDockerClient), + ) + h.AssertNil(t, err) + + h.AssertNil(t, pack.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packageImage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -78,75 +89,76 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { return packageImage } + it.Before(func() { logger = ilogging.NewLogWithWriters(&out, &out, ilogging.WithVerbose()) mockController = gomock.NewController(t) mockDownloader = testmocks.NewMockDownloader(mockController) + mockRegistryResolver = testmocks.NewMockRegistryResolver(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) mockDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz").Return(blob.NewBlob(filepath.Join("testdata", "buildpack")), nil).AnyTimes() mockDownloader.EXPECT().Download(gomock.Any(), "some/buildpack/dir").Return(blob.NewBlob(filepath.Join("testdata", "buildpack")), nil).AnyTimes() - var err error - subject, err = pack.NewClient( - pack.WithLogger(logger), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithDockerClient(mockDockerClient), - ) - h.AssertNil(t, err) - buildpackDownloader = pack.NewBuildpackDownloader(logger, mockImageFetcher, mockDownloader) + buildpackDownloader = downloader.NewBuildpackDownloader(logger, mockImageFetcher, mockDownloader, mockRegistryResolver) mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() - tmpDir, err = ioutil.TempDir("", "buildpack-downloader-test") - h.AssertNil(t, err) + mockRegistryResolver.EXPECT(). + Resolve("some-registry", "urn:cnb:registry:example/foo@1.1.0"). + Return("example.com/some/package@sha256:74eb48882e835d8767f62940d453eb96ed2737de3a16573881dcea7dea769df7", nil). + AnyTimes() + mockRegistryResolver.EXPECT(). + Resolve("some-registry", "example/foo@1.1.0"). + Return("example.com/some/package@sha256:74eb48882e835d8767f62940d453eb96ed2737de3a16573881dcea7dea769df7", nil). + AnyTimes() - packHome := filepath.Join(tmpDir, ".pack") - err = os.MkdirAll(packHome, 0755) + var err error + tmpDir, err = ioutil.TempDir("", "buildpack-downloader-test") h.AssertNil(t, err) - os.Setenv("PACK_HOME", packHome) - t.Logf("%v pack home here %v", t.Name(), packHome) - registryFixture := h.CreateRegistryFixture(t, tmpDir, filepath.Join("testdata", "registry")) - configPath := filepath.Join(packHome, "config.toml") - h.AssertNil(t, cfg.Write(cfg.Config{ - Registries: []cfg.Registry{ - { - Name: "some-registry", - Type: "github", - URL: registryFixture, - }, - }, - }, configPath)) - h.AssertNil(t, err) + // registryFixture := h.CreateRegistryFixture(t, tmpDir, filepath.Join("testdata", "registry")) + + // packHome := filepath.Join(tmpDir, ".pack") + // configPath := filepath.Join(packHome, "config.toml") + + // h.AssertNil(t, cfg.Write(cfg.Config{ + // Registries: []cfg.Registry{ + // { + // Name: "some-registry", + // Type: "github", + // URL: registryFixture, + // }, + // }, + // }, configPath)) + // h.AssertNil(t, err) }) it.After(func() { mockController.Finish() h.AssertNil(t, os.RemoveAll(tmpDir)) - os.Unsetenv("PACK_HOME") + // os.Unsetenv("PACK_HOME") }) when("#DownloadBuildpack", func() { var ( - packageImage *fakes.Image + packageImage *fakes.Image + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ImageOS: "linux"} ) shouldFetchPackageImageWith := func(demon bool, pull config.PullPolicy) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: demon, PullPolicy: pull}).Return(packageImage, nil) } - var buildpackDownloadOptions pack.BuildpackDownloadOptions = pack.BuildpackDownloadOptions{ImageOS: "linux"} when("package image lives in cnb registry", func() { it.Before(func() { packageImage = createPackage("example.com/some/package@sha256:74eb48882e835d8767f62940d453eb96ed2737de3a16573881dcea7dea769df7") }) + when("daemon=true and pull-policy=always", func() { it("should pull and use local package image", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ RegistryName: "some-registry", ImageOS: "linux", Daemon: true, @@ -159,9 +171,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") }) }) + when("ambigious URI provided", func() { it("should find package in registry", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ RegistryName: "some-registry", ImageOS: "linux", Daemon: true, @@ -178,24 +191,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("package image lives in docker registry", func() { it.Before(func() { - packageImage = fakes.NewImage("docker.io/some/package-"+h.RandString(12), "", nil) - mockImageFactory.EXPECT().NewImage(packageImage.Name(), false, "linux").Return(packageImage, nil) - - bpd := dist.BuildpackDescriptor{ - API: api.MustParse("0.3"), - Info: dist.BuildpackInfo{ID: "some.pkg.bp", Version: "2.3.4", Homepage: "http://meta.buildpack"}, - Stacks: []dist.Stack{{ID: "some.stack.id"}}, - } - - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ - Name: packageImage.Name(), - Config: pubbldpkg.Config{ - Platform: dist.Platform{OS: "linux"}, - Buildpack: dist.BuildpackURI{URI: createBuildpack(bpd)}, - }, - Publish: true, - PullPolicy: config.PullAlways, - })) + packageImage = createPackage("docker.io/some/package-" + h.RandString(12)) }) prepareFetcherWithMissingPackageImage := func() { @@ -205,7 +201,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("image key is provided", func() { it("should succeed", func() { packageImage = createPackage("some/package:tag") - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ Daemon: true, PullPolicy: config.PullAlways, ImageOS: "linux", @@ -221,7 +217,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=true and pull-policy=always", func() { it("should pull and use local package image", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, @@ -231,13 +227,13 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { shouldFetchPackageImageWith(true, config.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) - h.AssertEq(t, mainBP.Descriptor().Info.ID, "some.pkg.bp") + h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") }) }) when("daemon=false and pull-policy=always", func() { it("should use remote package image", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, @@ -247,13 +243,13 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { shouldFetchPackageImageWith(false, config.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) - h.AssertEq(t, mainBP.Descriptor().Info.ID, "some.pkg.bp") + h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") }) }) when("daemon=false and pull-policy=always", func() { it("should use remote package URI", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", Daemon: false, PullPolicy: config.PullAlways, @@ -261,13 +257,13 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { shouldFetchPackageImageWith(false, config.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), packageImage.Name(), buildpackDownloadOptions) h.AssertNil(t, err) - h.AssertEq(t, mainBP.Descriptor().Info.ID, "some.pkg.bp") + h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") }) }) when("publish=true and pull-policy=never", func() { it("should push to registry and not pull package image", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, @@ -277,13 +273,13 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { shouldFetchPackageImageWith(false, config.PullNever) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) - h.AssertEq(t, mainBP.Descriptor().Info.ID, "some.pkg.bp") + h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") }) }) when("daemon=true pull-policy=never and there is no local package image", func() { it("should fail without trying to retrieve package image from registry", func() { - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, @@ -308,7 +304,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { buildpackPath := filepath.Join("testdata", "buildpack") buildpackURI, _ := paths.FilePathToURI(buildpackPath, "") mockDownloader.EXPECT().Download(gomock.Any(), buildpackURI).Return(blob.NewBlob(buildpackPath), nil).AnyTimes() - buildpackDownloadOptions = pack.BuildpackDownloadOptions{ + buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ ImageOS: "linux", RelativeBaseDir: "testdata", } @@ -332,34 +328,29 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("invalid buildpack URI", func() { when("buildpack URI is from=builder:fake", func() { it("errors", func() { - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "from=builder:fake", buildpackDownloadOptions) + _, _, err := buildpackDownloader.Download(context.TODO(), "from=builder:fake", buildpackDownloadOptions) h.AssertError(t, err, "'from=builder:fake' is not a valid identifier") }) }) when("buildpack URI is from=builder", func() { it("errors", func() { - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "from=builder", buildpackDownloadOptions) + _, _, err := buildpackDownloader.Download(context.TODO(), "from=builder", buildpackDownloadOptions) h.AssertError(t, err, "invalid locator: FromBuilderLocator") }) }) - when("buildpack URI is invalid registry", func() { + when("can't resolve buildpack in registry", func() { it("errors", func() { - buildpackDownloadOptions.RegistryName = "://bad-url" - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "urn:cnb:registry:fake", buildpackDownloadOptions) - h.AssertError(t, err, - "invalid registry") - }) - }) + mockRegistryResolver.EXPECT(). + Resolve("://bad-url", "urn:cnb:registry:fake"). + Return("", errors.New("bad mhkay")). + AnyTimes() - when("buildpack is missing from registry", func() { - it("errors", func() { - buildpackDownloadOptions.RegistryName = "some-registry" - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "urn:cnb:registry:fake", buildpackDownloadOptions) - h.AssertError(t, err, - "locating in registry") + buildpackDownloadOptions.RegistryName = "://bad-url" + _, _, err := buildpackDownloader.Download(context.TODO(), "urn:cnb:registry:fake", buildpackDownloadOptions) + h.AssertError(t, err, "locating in registry") }) }) @@ -369,14 +360,14 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}).Return(nil, errors.New("failed to pull")) buildpackDownloadOptions.RegistryName = "some-registry" - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "urn:cnb:registry:example/foo@1.1.0", buildpackDownloadOptions) + _, _, err := buildpackDownloader.Download(context.TODO(), "urn:cnb:registry:example/foo@1.1.0", buildpackDownloadOptions) h.AssertError(t, err, "extracting from registry") }) }) when("buildpack URI is an invalid locator", func() { it("errors", func() { - _, _, err := subject.BuildpackDownloader.Download(context.TODO(), "nonsense string here", buildpackDownloadOptions) + _, _, err := buildpackDownloader.Download(context.TODO(), "nonsense string here", buildpackDownloadOptions) h.AssertError(t, err, "invalid locator: InvalidLocator") }) diff --git a/pkg/buildpack/downloader/testdata/buildpack/bin/build b/pkg/buildpack/downloader/testdata/buildpack/bin/build new file mode 100644 index 0000000000..c76df1a291 --- /dev/null +++ b/pkg/buildpack/downloader/testdata/buildpack/bin/build @@ -0,0 +1 @@ +build-contents \ No newline at end of file diff --git a/pkg/buildpack/downloader/testdata/buildpack/bin/detect b/pkg/buildpack/downloader/testdata/buildpack/bin/detect new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/buildpack/downloader/testdata/buildpack/buildpack.toml b/pkg/buildpack/downloader/testdata/buildpack/buildpack.toml new file mode 100644 index 0000000000..131cb045f6 --- /dev/null +++ b/pkg/buildpack/downloader/testdata/buildpack/buildpack.toml @@ -0,0 +1,10 @@ +api = "0.3" + +[buildpack] +id = "bp.one" +version = "1.2.3" +homepage = "http://one.buildpack" + +[[stacks]] +id = "some.stack.id" +mixins = ["mixinX", "build:mixinY", "run:mixinZ"] diff --git a/build.go b/pkg/client/build.go similarity index 95% rename from build.go rename to pkg/client/build.go index 2e09d82c3d..84af2fdbd3 100644 --- a/build.go +++ b/pkg/client/build.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -21,16 +21,11 @@ import ( "github.com/pkg/errors" ignore "github.com/sabhiram/go-gitignore" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" internalConfig "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" - "github.com/buildpacks/pack/internal/layer" pname "github.com/buildpacks/pack/internal/name" "github.com/buildpacks/pack/internal/stack" "github.com/buildpacks/pack/internal/stringset" @@ -38,6 +33,9 @@ import ( "github.com/buildpacks/pack/internal/termui" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) @@ -749,7 +747,7 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima if err != nil { return fetchedBPs, order, errors.Wrapf(err, "getting OS from %s", style.Symbol(builderImage.Name())) } - mainBP, depBPs, err := c.BuildpackDownloader.Download(ctx, bp, BuildpackDownloadOptions{ + mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, bp, downloader.BuildpackDownloadOptions{ RegistryName: registry, ImageOS: imageOS, RelativeBaseDir: relativeBaseDir, @@ -780,33 +778,6 @@ func appendBuildpackToOrder(order dist.Order, bpInfo dist.BuildpackInfo) (newOrd return newOrder } -// decomposeBuildpack decomposes a buildpack blob into the main builder (order buildpack) and it's dependencies buildpacks. -func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { - isOCILayout, err := buildpackage.IsOCILayoutBlob(blob) - if err != nil { - return mainBP, depBPs, errors.Wrap(err, "inspecting buildpack blob") - } - - if isOCILayout { - mainBP, depBPs, err = buildpackage.BuildpacksFromOCILayoutBlob(blob) - if err != nil { - return mainBP, depBPs, errors.Wrap(err, "extracting buildpacks") - } - } else { - layerWriterFactory, err := layer.NewWriterFactory(imageOS) - if err != nil { - return mainBP, depBPs, errors.Wrapf(err, "get tar writer factory for OS %s", style.Symbol(imageOS)) - } - - mainBP, err = dist.BuildpackFromRootBlob(blob, layerWriterFactory) - if err != nil { - return mainBP, depBPs, errors.Wrap(err, "reading buildpack") - } - } - - return mainBP, depBPs, nil -} - func (c *Client) createEphemeralBuilder(rawBuilderImage imgutil.Image, env map[string]string, order dist.Order, buildpacks []dist.Buildpack) (*builder.Builder, error) { origBuilderName := rawBuilderImage.Name() bldr, err := builder.New(rawBuilderImage, fmt.Sprintf("pack.local/builder/%x:latest", randString(10))) diff --git a/build_test.go b/pkg/client/build_test.go similarity index 99% rename from build_test.go rename to pkg/client/build_test.go index cf241140a7..fa6f1be806 100644 --- a/build_test.go +++ b/pkg/client/build_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" @@ -24,7 +24,7 @@ import ( "github.com/buildpacks/imgutil/remote" "github.com/buildpacks/lifecycle/api" "github.com/buildpacks/lifecycle/platform" - "github.com/docker/docker/client" + dockerclient "github.com/docker/docker/client" "github.com/google/go-containerregistry/pkg/name" "github.com/heroku/color" "github.com/onsi/gomega/ghttp" @@ -32,8 +32,6 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/buildpackage" @@ -43,6 +41,9 @@ import ( ilogging "github.com/buildpacks/pack/internal/logging" rg "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/config" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -116,7 +117,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { fakeLifecycleImage = newLinuxImage(fmt.Sprintf("%s:%s", cfg.DefaultLifecycleImageRepo, builder.DefaultLifecycleVersion), "", nil) fakeImageFetcher.LocalImages[fakeLifecycleImage.Name()] = fakeLifecycleImage - docker, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.38")) + docker, err := dockerclient.NewClientWithOpts(dockerclient.FromEnv, dockerclient.WithVersion("1.38")) h.AssertNil(t, err) logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) @@ -124,15 +125,15 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { dlCacheDir, err := ioutil.TempDir(tmpDir, "dl-cache") h.AssertNil(t, err) - downloader := blob.NewDownloader(logger, dlCacheDir) - buildpackDownloader := NewBuildpackDownloader(logger, fakeImageFetcher, downloader) + blobDownloader := blob.NewDownloader(logger, dlCacheDir) + buildpackDownloader := downloader.NewBuildpackDownloader(logger, fakeImageFetcher, blobDownloader, ®istryResolver{logger: logger}) subject = &Client{ logger: logger, imageFetcher: fakeImageFetcher, - downloader: downloader, + downloader: blobDownloader, lifecycleExecutor: fakeLifecycle, docker: docker, - BuildpackDownloader: buildpackDownloader, + buildpackDownloader: buildpackDownloader, } }) diff --git a/client.go b/pkg/client/client.go similarity index 75% rename from client.go rename to pkg/client/client.go index ee3447ede1..3e09a9815e 100644 --- a/client.go +++ b/pkg/client/client.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -10,17 +10,19 @@ import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/build" - "github.com/buildpacks/pack/internal/config" + iconfig "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/image" ) -//go:generate mockgen -package testmocks -destination testmocks/mock_docker_client.go github.com/docker/docker/client CommonAPIClient +//go:generate mockgen -package testmocks -destination ../testmocks/mock_docker_client.go github.com/docker/docker/client CommonAPIClient -//go:generate mockgen -package testmocks -destination testmocks/mock_image_fetcher.go github.com/buildpacks/pack ImageFetcher +//go:generate mockgen -package testmocks -destination ../testmocks/mock_image_fetcher.go github.com/buildpacks/pack/pkg/client ImageFetcher // ImageFetcher is an interface representing the ability to fetch local and images. type ImageFetcher interface { @@ -36,7 +38,7 @@ type ImageFetcher interface { Fetch(ctx context.Context, name string, options image.FetchOptions) (imgutil.Image, error) } -//go:generate mockgen -package testmocks -destination testmocks/mock_downloader.go github.com/buildpacks/pack Downloader +//go:generate mockgen -package testmocks -destination ../testmocks/mock_downloader.go github.com/buildpacks/pack/pkg/client Downloader // Downloader is an interface for collecting both remote and local assets. type Downloader interface { @@ -45,7 +47,7 @@ type Downloader interface { Download(ctx context.Context, pathOrURI string) (blob.Blob, error) } -//go:generate mockgen -package testmocks -destination testmocks/mock_image_factory.go github.com/buildpacks/pack ImageFactory +//go:generate mockgen -package testmocks -destination ../testmocks/mock_image_factory.go github.com/buildpacks/pack/pkg/client ImageFactory // ImageFactory is an interface representing the ability to create a new OCI image. type ImageFactory interface { @@ -54,12 +56,12 @@ type ImageFactory interface { NewImage(repoName string, local bool, imageOS string) (imgutil.Image, error) } -//go:generate mockgen -package pack -destination mock_buildpack_downloader.go github.com/buildpacks/pack BuildpackDownloader +//go:generate mockgen -package testmocks -destination ../testmocks/mock_buildpack_downloader.go github.com/buildpacks/pack/pkg/client BuildpackDownloader // BuildpackDownloader is an interface for downloading and extracting buildpacks from various sources type BuildpackDownloader interface { // Download parses a buildpack URI and downloads the buildpack and any dependencies buildpacks from the appropriate source - Download(ctx context.Context, buildpackURI string, opts BuildpackDownloadOptions) (dist.Buildpack, []dist.Buildpack, error) + Download(ctx context.Context, buildpackURI string, opts downloader.BuildpackDownloadOptions) (dist.Buildpack, []dist.Buildpack, error) } // Client is an orchestration object, it contains all parameters needed to @@ -72,7 +74,7 @@ type Client struct { lifecycleExecutor LifecycleExecutor docker dockerClient.CommonAPIClient imageFactory ImageFactory - BuildpackDownloader BuildpackDownloader + buildpackDownloader BuildpackDownloader experimental bool registryMirrors map[string]string } @@ -115,7 +117,7 @@ func WithDownloader(d Downloader) ClientOption { // A BuildpackDownloader is used to gather buildpacks from both remote urls, or local sources. func WithBuildpackDownloader(d BuildpackDownloader) ClientOption { return func(c *Client) { - c.BuildpackDownloader = d + c.buildpackDownloader = d } } @@ -175,7 +177,7 @@ func NewClient(opts ...ClientOption) (*Client, error) { } if client.downloader == nil { - packHome, err := config.PackHome() + packHome, err := iconfig.PackHome() if err != nil { return nil, errors.Wrap(err, "getting pack home") } @@ -190,11 +192,36 @@ func NewClient(opts ...ClientOption) (*Client, error) { client.imageFactory = image.NewFactory(client.docker, authn.DefaultKeychain) } - if client.BuildpackDownloader == nil { - client.BuildpackDownloader = NewBuildpackDownloader(client.logger, client.imageFetcher, client.downloader) + if client.buildpackDownloader == nil { + client.buildpackDownloader = downloader.NewBuildpackDownloader( + client.logger, + client.imageFetcher, + client.downloader, + ®istryResolver{ + logger: client.logger, + }, + ) } client.lifecycleExecutor = build.NewLifecycleExecutor(client.logger, client.docker) return &client, nil } + +type registryResolver struct { + logger logging.Logger +} + +func (r *registryResolver) Resolve(registryName, bpName string) (string, error) { + cache, err := getRegistry(r.logger, registryName) + if err != nil { + return "", errors.Wrapf(err, "lookup registry %s", style.Symbol(registryName)) + } + + regBuildpack, err := cache.LocateBuildpack(bpName) + if err != nil { + return "", errors.Wrapf(err, "lookup buildpack %s", style.Symbol(bpName)) + } + + return regBuildpack.Address, nil +} diff --git a/client_test.go b/pkg/client/client_test.go similarity index 98% rename from client_test.go rename to pkg/client/client_test.go index db25c419f2..00ce946a81 100644 --- a/client_test.go +++ b/pkg/client/client_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" @@ -11,8 +11,8 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestClient(t *testing.T) { diff --git a/common.go b/pkg/client/common.go similarity index 99% rename from common.go rename to pkg/client/common.go index 54f3b4b8cb..bf02ea329b 100644 --- a/common.go +++ b/pkg/client/common.go @@ -1,4 +1,4 @@ -package pack +package client import ( "errors" diff --git a/common_test.go b/pkg/client/common_test.go similarity index 99% rename from common_test.go rename to pkg/client/common_test.go index 90273c78a0..2d9507b4e6 100644 --- a/common_test.go +++ b/pkg/client/common_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" diff --git a/create_builder.go b/pkg/client/create_builder.go similarity index 96% rename from create_builder.go rename to pkg/client/create_builder.go index d1413a0627..5bda3a3ffc 100644 --- a/create_builder.go +++ b/pkg/client/create_builder.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -9,12 +9,13 @@ import ( "github.com/pkg/errors" pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // CreateBuilderOptions is a configuration object used to change the behavior of @@ -209,7 +210,7 @@ func (c *Client) addBuildpacksToBuilder(ctx context.Context, opts CreateBuilderO return errors.Wrapf(err, "getting OS from %s", style.Symbol(bldr.Image().Name())) } - mainBP, depBPs, err := c.BuildpackDownloader.Download(ctx, b.URI, BuildpackDownloadOptions{ + mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, b.URI, downloader.BuildpackDownloadOptions{ RegistryName: opts.Registry, ImageOS: imageOS, RelativeBaseDir: opts.RelativeBaseDir, diff --git a/create_builder_test.go b/pkg/client/create_builder_test.go similarity index 93% rename from create_builder_test.go rename to pkg/client/create_builder_test.go index cc5689c1af..cfa753fe10 100644 --- a/create_builder_test.go +++ b/pkg/client/create_builder_test.go @@ -1,4 +1,4 @@ -package pack_test +package client_test import ( "bytes" @@ -18,23 +18,24 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" pubbldr "github.com/buildpacks/pack/builder" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/image" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestCreateBuilder(t *testing.T) { @@ -48,15 +49,15 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { var ( mockController *gomock.Controller mockDownloader *testmocks.MockDownloader - mockBuildpackDownloader *pack.MockBuildpackDownloader + mockBuildpackDownloader *testmocks.MockBuildpackDownloader mockImageFactory *testmocks.MockImageFactory mockImageFetcher *testmocks.MockImageFetcher mockDockerClient *testmocks.MockCommonAPIClient fakeBuildImage *fakes.Image fakeRunImage *fakes.Image fakeRunImageMirror *fakes.Image - opts pack.CreateBuilderOptions - subject *pack.Client + opts client.CreateBuilderOptions + subject *client.Client logger logging.Logger out bytes.Buffer tmpDir string @@ -75,7 +76,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) return buildpack } - var shouldCallBuildpackDownloaderWith = func(uri string, buildpackDownloadOptions pack.BuildpackDownloadOptions) { + var shouldCallBuildpackDownloaderWith = func(uri string, buildpackDownloadOptions downloader.BuildpackDownloadOptions) { buildpack := createBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.3"), Info: dist.BuildpackInfo{ID: "example/foo", Version: "1.1.0"}, @@ -91,7 +92,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) - mockBuildpackDownloader = pack.NewMockBuildpackDownloader(mockController) + mockBuildpackDownloader = testmocks.NewMockBuildpackDownloader(mockController) fakeBuildImage = fakes.NewImage("some/build-image", "", nil) h.AssertNil(t, fakeBuildImage.SetLabel("io.buildpacks.stack.id", "some.stack.id")) @@ -117,19 +118,19 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz", gomock.Any()).Return(buildpack, nil, nil).AnyTimes() - subject, err = pack.NewClient( - pack.WithLogger(logger), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithDockerClient(mockDockerClient), - pack.WithBuildpackDownloader(mockBuildpackDownloader), + subject, err = client.NewClient( + client.WithLogger(logger), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithDockerClient(mockDockerClient), + client.WithBuildpackDownloader(mockBuildpackDownloader), ) h.AssertNil(t, err) mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() - opts = pack.CreateBuilderOptions{ + opts = client.CreateBuilderOptions{ RelativeBaseDir: "/", BuilderName: "some/builder", Config: pubbldr.Config{ @@ -364,12 +365,12 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { when("windows containers", func() { when("experimental enabled", func() { it("succeeds", func() { - packClientWithExperimental, err := pack.NewClient( - pack.WithLogger(logger), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithExperimental(true), + packClientWithExperimental, err := client.NewClient( + client.WithLogger(logger), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithExperimental(true), ) h.AssertNil(t, err) @@ -449,12 +450,12 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { when("windows", func() { it("should download from predetermined uri", func() { - packClientWithExperimental, err := pack.NewClient( - pack.WithLogger(logger), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithExperimental(true), + packClientWithExperimental, err := client.NewClient( + client.WithLogger(logger), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithExperimental(true), ) h.AssertNil(t, err) @@ -501,12 +502,12 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { when("windows", func() { it("should download default lifecycle", func() { - packClientWithExperimental, err := pack.NewClient( - pack.WithLogger(logger), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithExperimental(true), + packClientWithExperimental, err := client.NewClient( + client.WithLogger(logger), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithExperimental(true), ) h.AssertNil(t, err) @@ -665,7 +666,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { buildpackPath, buildpackPathURI := fileURI(filepath.Join("testdata", "buildpack")) mockDownloader.EXPECT().Download(gomock.Any(), buildpackPathURI).Return(blob.NewBlob(buildpackPath), nil) - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: cnbFile, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -724,7 +725,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }, ) - shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", pack.BuildpackDownloadOptions{Daemon: true, PullPolicy: config.PullAlways, RegistryName: "some-"}) + shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", downloader.BuildpackDownloadOptions{Daemon: true, PullPolicy: config.PullAlways, RegistryName: "some-"}) h.AssertNil(t, subject.CreateBuilder(context.TODO(), opts)) }) }) diff --git a/doc.go b/pkg/client/doc.go similarity index 97% rename from doc.go rename to pkg/client/doc.go index 935373f02f..d840a14905 100644 --- a/doc.go +++ b/pkg/client/doc.go @@ -14,4 +14,4 @@ An introduction to these artifacts and their usage can be found at https://build The formal specification of the pack platform provides can be found at: https://github.com/buildpacks/spec. */ -package pack +package client diff --git a/doc_test.go b/pkg/client/doc_test.go similarity index 87% rename from doc_test.go rename to pkg/client/doc_test.go index 19e055be17..a613135d62 100644 --- a/doc_test.go +++ b/pkg/client/doc_test.go @@ -1,11 +1,11 @@ -package pack_test +package client_test import ( "context" "fmt" "math/rand" - "github.com/buildpacks/pack" + "github.com/buildpacks/pack/pkg/client" ) // This example shows the basic usage of the package: Create a client, @@ -15,7 +15,7 @@ func Example_build() { context := context.Background() // initialize a pack client - client, err := pack.NewClient() + pack, err := client.NewClient() if err != nil { panic(err) } @@ -36,7 +36,7 @@ func Example_build() { randomBuilder := builderList[randomIndex] // initialize our options - buildOpts := pack.BuildOptions{ + buildOpts := client.BuildOptions{ Image: "pack-lib-test-image:0.0.1", Builder: randomBuilder, AppPath: appPath, @@ -46,7 +46,7 @@ func Example_build() { fmt.Println("building application image") // build an image - err = client.Build(context, buildOpts) + err = pack.Build(context, buildOpts) if err != nil { panic(err) } diff --git a/errors.go b/pkg/client/errors.go similarity index 97% rename from errors.go rename to pkg/client/errors.go index 7efb9bc487..ef4092154c 100644 --- a/errors.go +++ b/pkg/client/errors.go @@ -1,4 +1,4 @@ -package pack +package client // ExperimentError denotes that an experimental feature was trying to be used without experimental features enabled. type ExperimentError struct { diff --git a/inspect_builder.go b/pkg/client/inspect_builder.go similarity index 97% rename from inspect_builder.go rename to pkg/client/inspect_builder.go index c445a498f7..9305c1792b 100644 --- a/inspect_builder.go +++ b/pkg/client/inspect_builder.go @@ -1,4 +1,4 @@ -package pack +package client import ( "errors" @@ -7,10 +7,10 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/image" ) -// BuilderInfo is a collection of metadata describing a builder created using pack. +// BuilderInfo is a collection of metadata describing a builder created using client. type BuilderInfo struct { // Human readable, description of a builder. Description string diff --git a/inspect_builder_test.go b/pkg/client/inspect_builder_test.go similarity index 98% rename from inspect_builder_test.go rename to pkg/client/inspect_builder_test.go index f22edb0db1..4e175846dc 100644 --- a/inspect_builder_test.go +++ b/pkg/client/inspect_builder_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" @@ -7,7 +7,7 @@ import ( pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/config" + "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/imgutil/fakes" "github.com/buildpacks/lifecycle/api" @@ -20,10 +20,10 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestInspectBuilder(t *testing.T) { diff --git a/inspect_buildpack.go b/pkg/client/inspect_buildpack.go similarity index 98% rename from inspect_buildpack.go rename to pkg/client/inspect_buildpack.go index 028f4b5850..9b59b0a978 100644 --- a/inspect_buildpack.go +++ b/pkg/client/inspect_buildpack.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -7,12 +7,12 @@ import ( v1 "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) type BuildpackInfo struct { diff --git a/inspect_buildpack_test.go b/pkg/client/inspect_buildpack_test.go similarity index 94% rename from inspect_buildpack_test.go rename to pkg/client/inspect_buildpack_test.go index 6908cbbe1f..af403b6227 100644 --- a/inspect_buildpack_test.go +++ b/pkg/client/inspect_buildpack_test.go @@ -1,4 +1,4 @@ -package pack_test +package client_test import ( "archive/tar" @@ -9,33 +9,29 @@ import ( "path/filepath" "testing" - "github.com/pkg/errors" - - cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/image" - - "github.com/google/go-containerregistry/pkg/v1/empty" - "github.com/google/go-containerregistry/pkg/v1/layout" - "github.com/google/go-containerregistry/pkg/v1/mutate" - - "github.com/buildpacks/pack/internal/blob" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/pkg/archive" - "github.com/buildpacks/imgutil/fakes" "github.com/buildpacks/lifecycle/api" "github.com/golang/mock/gomock" + "github.com/google/go-containerregistry/pkg/v1/empty" + "github.com/google/go-containerregistry/pkg/v1/layout" + "github.com/google/go-containerregistry/pkg/v1/mutate" "github.com/heroku/color" + "github.com/pkg/errors" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" - "github.com/buildpacks/pack/config" + "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" + cfg "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) const buildpackageMetadataTag = `{ @@ -159,13 +155,13 @@ func TestInspectBuildpack(t *testing.T) { func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { var ( - subject *pack.Client + subject *client.Client mockImageFetcher *testmocks.MockImageFetcher mockController *gomock.Controller out bytes.Buffer buildpackImage *fakes.Image apiVersion *api.Version - expectedInfo *pack.BuildpackInfo + expectedInfo *client.BuildpackInfo mockDownloader *testmocks.MockDownloader tmpDir string @@ -177,10 +173,10 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockDownloader = testmocks.NewMockDownloader(mockController) - subject = &pack.Client{} - pack.WithLogger(logging.NewLogWithWriters(&out, &out))(subject) - pack.WithFetcher(mockImageFetcher)(subject) - pack.WithDownloader(mockDownloader)(subject) + subject = &client.Client{} + client.WithLogger(logging.NewLogWithWriters(&out, &out))(subject) + client.WithFetcher(mockImageFetcher)(subject) + client.WithDownloader(mockDownloader)(subject) buildpackImage = fakes.NewImage("some/buildpack", "", nil) h.AssertNil(t, buildpackImage.SetLabel(buildpackage.MetadataLabel, buildpackageMetadataTag)) @@ -195,7 +191,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { buildpackPath = filepath.Join(tmpDir, "buildpackTarFile.tar") - expectedInfo = &pack.BuildpackInfo{ + expectedInfo = &client.BuildpackInfo{ BuildpackMetadata: buildpackage.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", @@ -391,7 +387,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { it("succeeds", func() { registryBuildpack := "urn:cnb:registry:example/java" - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: registryBuildpack, Registry: "some-registry", } @@ -411,7 +407,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { it("succeeds", func() { mockDownloader.EXPECT().Download(gomock.Any(), buildpackPath).Return(blob.NewBlob(buildpackPath), nil) - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: buildpackPath, Daemon: false, } @@ -436,7 +432,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("succeeds", func() { - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: "docker://some/buildpack", Daemon: useDaemon, } @@ -453,7 +449,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { when("invalid buildpack name", func() { it("returns an error", func() { invalidBuildpackName := "" - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: invalidBuildpackName, } _, err := subject.InspectBuildpack(inspectOptions) @@ -468,7 +464,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing/buildpack", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(nil, errors.Wrapf(image.ErrNotFound, "big bad error")) }) it("returns an ErrNotFound error", func() { - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: "docker://missing/buildpack", Daemon: true, } @@ -484,7 +480,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing-metadata/buildpack", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(fakeImage, nil) }) it("returns an error", func() { - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: "docker://missing-metadata/buildpack", Daemon: true, } @@ -504,7 +500,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), "https://invalid/buildpack").Return(blob.NewBlob(invalidBuildpackPath), nil) }) it("returns an error", func() { - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: "https://invalid/buildpack", Daemon: true, } @@ -520,7 +516,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), "https://missing/buildpack").Return(nil, errors.New("unable to download archive")) }) it("returns a untyped error", func() { - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: "https://missing/buildpack", Daemon: true, } @@ -537,7 +533,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { when("unable to get registry", func() { it("returns an error", func() { registryBuildpack := "urn:cnb:registry:example/foo" - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: registryBuildpack, Daemon: true, Registry: ":::", @@ -570,7 +566,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("returns an error", func() { registryBuildpack := "urn:cnb:registry:example/not-present" - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: registryBuildpack, Daemon: true, Registry: "some-registry", @@ -607,7 +603,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("returns an untyped error", func() { registryBuildpack := "urn:cnb:registry:example/foo" - inspectOptions := pack.InspectBuildpackOptions{ + inspectOptions := client.InspectBuildpackOptions{ BuildpackName: registryBuildpack, Daemon: true, Registry: "some-registry", diff --git a/inspect_image.go b/pkg/client/inspect_image.go similarity index 98% rename from inspect_image.go rename to pkg/client/inspect_image.go index eb0fe7f302..4287dbe61f 100644 --- a/inspect_image.go +++ b/pkg/client/inspect_image.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -10,9 +10,9 @@ import ( "github.com/buildpacks/lifecycle/platform" "github.com/pkg/errors" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // ImageInfo is a collection of metadata describing diff --git a/inspect_image_test.go b/pkg/client/inspect_image_test.go similarity index 99% rename from inspect_image_test.go rename to pkg/client/inspect_image_test.go index 51a03f38d2..296c3d6e5e 100644 --- a/inspect_image_test.go +++ b/pkg/client/inspect_image_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" @@ -15,11 +15,11 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestInspectImage(t *testing.T) { diff --git a/new_buildpack.go b/pkg/client/new_buildpack.go similarity index 99% rename from new_buildpack.go rename to pkg/client/new_buildpack.go index 244eb1e558..95e130b2e6 100644 --- a/new_buildpack.go +++ b/pkg/client/new_buildpack.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" diff --git a/new_buildpack_test.go b/pkg/client/new_buildpack_test.go similarity index 92% rename from new_buildpack_test.go rename to pkg/client/new_buildpack_test.go index 2ae478428e..a8352119e7 100644 --- a/new_buildpack_test.go +++ b/pkg/client/new_buildpack_test.go @@ -1,4 +1,4 @@ -package pack_test +package client_test import ( "context" @@ -14,8 +14,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -27,7 +27,7 @@ func TestNewBuildpack(t *testing.T) { func testNewBuildpack(t *testing.T, when spec.G, it spec.S) { var ( - subject *pack.Client + subject *client.Client tmpDir string ) @@ -37,7 +37,7 @@ func testNewBuildpack(t *testing.T, when spec.G, it spec.S) { tmpDir, err = ioutil.TempDir("", "new-buildpack-test") h.AssertNil(t, err) - subject, err = pack.NewClient() + subject, err = client.NewClient() h.AssertNil(t, err) }) @@ -47,7 +47,7 @@ func testNewBuildpack(t *testing.T, when spec.G, it spec.S) { when("#NewBuildpack", func() { it("should create bash scripts", func() { - err := subject.NewBuildpack(context.TODO(), pack.NewBuildpackOptions{ + err := subject.NewBuildpack(context.TODO(), client.NewBuildpackOptions{ API: "0.4", Path: tmpDir, ID: "example/my-cnb", @@ -91,7 +91,7 @@ func testNewBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("should not clobber files that exist", func() { - err := subject.NewBuildpack(context.TODO(), pack.NewBuildpackOptions{ + err := subject.NewBuildpack(context.TODO(), client.NewBuildpackOptions{ API: "0.4", Path: tmpDir, ID: "example/my-cnb", diff --git a/pkg/client/pack.go b/pkg/client/pack.go new file mode 100644 index 0000000000..f4175841ac --- /dev/null +++ b/pkg/client/pack.go @@ -0,0 +1,6 @@ +package client + +var ( + // Version is the version of `pack`. It is injected at compile time. + Version = "0.0.0" +) diff --git a/package_buildpack.go b/pkg/client/package_buildpack.go similarity index 57% rename from package_buildpack.go rename to pkg/client/package_buildpack.go index e76b100685..c475422f45 100644 --- a/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -6,15 +6,14 @@ import ( "github.com/pkg/errors" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" - "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/config" ) const ( @@ -96,80 +95,20 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti for _, dep := range opts.Config.Dependencies { var depBPs []dist.Buildpack - - if dep.ImageName != "" { - c.logger.Warn("The 'image' key is deprecated. Use 'uri=\"docker://...\"' instead.") - mainBP, deps, err := extractPackagedBuildpacks(ctx, dep.ImageName, c.imageFetcher, image.FetchOptions{Daemon: !opts.Publish, PullPolicy: opts.PullPolicy}) - if err != nil { - return err - } - - depBPs = append([]dist.Buildpack{mainBP}, deps...) - } else if dep.URI != "" { - locatorType, err := buildpack.GetLocatorType(dep.URI, opts.RelativeBaseDir, nil) - if err != nil { - return err - } - - switch locatorType { - case buildpack.URILocator: - depBlob, err := c.downloadBuildpackFromURI(ctx, dep.URI, opts.RelativeBaseDir) - if err != nil { - return err - } - - isOCILayout, err := buildpackage.IsOCILayoutBlob(depBlob) - if err != nil { - return errors.Wrap(err, "inspecting buildpack blob") - } - - if isOCILayout { - mainBP, deps, err := buildpackage.BuildpacksFromOCILayoutBlob(depBlob) - if err != nil { - return errors.Wrapf(err, "extracting buildpacks from %s", style.Symbol(dep.URI)) - } - - depBPs = append([]dist.Buildpack{mainBP}, deps...) - } else { - depBP, err := dist.BuildpackFromRootBlob(depBlob, writerFactory) - if err != nil { - return errors.Wrapf(err, "creating buildpack from %s", style.Symbol(dep.URI)) - } - depBPs = []dist.Buildpack{depBP} - } - case buildpack.PackageLocator: - imageName := buildpack.ParsePackageLocator(dep.URI) - c.logger.Debugf("Downloading buildpack from image: %s", style.Symbol(imageName)) - mainBP, deps, err := extractPackagedBuildpacks(ctx, imageName, c.imageFetcher, image.FetchOptions{Daemon: !opts.Publish, PullPolicy: opts.PullPolicy}) - if err != nil { - return err - } - - depBPs = append([]dist.Buildpack{mainBP}, deps...) - case buildpack.RegistryLocator: - registryCache, err := getRegistry(c.logger, opts.Registry) - if err != nil { - return errors.Wrapf(err, "invalid registry '%s'", opts.Registry) - } - - registryBp, err := registryCache.LocateBuildpack(dep.URI) - if err != nil { - return errors.Wrapf(err, "locating in registry %s", style.Symbol(dep.URI)) - } - - mainBP, deps, err := extractPackagedBuildpacks(ctx, registryBp.Address, c.imageFetcher, image.FetchOptions{Daemon: !opts.Publish, PullPolicy: opts.PullPolicy}) - if err != nil { - return errors.Wrapf(err, "extracting from registry %s", style.Symbol(dep.URI)) - } - - depBPs = append([]dist.Buildpack{mainBP}, deps...) - case buildpack.InvalidLocator: - return errors.Errorf("invalid locator %s", style.Symbol(dep.URI)) - default: - return errors.Errorf("unsupported locator type %s", style.Symbol(locatorType.String())) - } + mainBP, deps, err := c.buildpackDownloader.Download(ctx, dep.URI, downloader.BuildpackDownloadOptions{ + RegistryName: opts.Registry, + RelativeBaseDir: opts.RelativeBaseDir, + ImageOS: "linux", + ImageName: dep.ImageName, + Daemon: !opts.Publish, + PullPolicy: opts.PullPolicy, + }) + + if err != nil { + return errors.Wrapf(err, "packaging dependencies (uri=%s,image=%s)", style.Symbol(dep.URI), style.Symbol(dep.ImageName)) } + depBPs = append([]dist.Buildpack{mainBP}, deps...) for _, depBP := range depBPs { packageBuilder.AddDependency(depBP) } diff --git a/package_buildpack_test.go b/pkg/client/package_buildpack_test.go similarity index 87% rename from package_buildpack_test.go rename to pkg/client/package_buildpack_test.go index 478c90c0bc..8f22222681 100644 --- a/package_buildpack_test.go +++ b/pkg/client/package_buildpack_test.go @@ -1,4 +1,4 @@ -package pack_test +package client_test import ( "bytes" @@ -18,19 +18,19 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" pubbldpkg "github.com/buildpacks/pack/buildpackage" - pubcfg "github.com/buildpacks/pack/config" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/buildpackage" cfg "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/client" + pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestPackageBuildpack(t *testing.T) { @@ -41,7 +41,7 @@ func TestPackageBuildpack(t *testing.T) { func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { var ( - subject *pack.Client + subject *client.Client mockController *gomock.Controller mockDownloader *testmocks.MockDownloader mockImageFactory *testmocks.MockImageFactory @@ -58,12 +58,12 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) var err error - subject, err = pack.NewClient( - pack.WithLogger(logging.NewLogWithWriters(&out, &out)), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithDockerClient(mockDockerClient), + subject, err = client.NewClient( + client.WithLogger(logging.NewLogWithWriters(&out, &out)), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithDockerClient(mockDockerClient), ) h.AssertNil(t, err) }) @@ -83,7 +83,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { when("buildpack has issues", func() { when("buildpack has no URI", func() { it("should fail", func() { - err := subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err := subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "Fake-Name", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -100,7 +100,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { bpURL := fmt.Sprintf("https://example.com/bp.%s.tgz", h.RandString(12)) mockDownloader.EXPECT().Download(gomock.Any(), bpURL).Return(nil, image.ErrNotFound).AnyTimes() - err := subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err := subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "Fake-Name", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -118,7 +118,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { bpURL := fmt.Sprintf("https://example.com/bp.%s.tgz", h.RandString(12)) mockDownloader.EXPECT().Download(gomock.Any(), bpURL).Return(fakeBlob, nil).AnyTimes() - err := subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err := subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "Fake-Name", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -150,7 +150,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }}, } - err := subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err := subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "test", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -173,11 +173,11 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { localMockDockerClient := testmocks.NewMockCommonAPIClient(mockController) localMockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: daemonOS}, nil).AnyTimes() - packClientWithExperimental, err := pack.NewClient( - pack.WithDockerClient(localMockDockerClient), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithExperimental(true), + packClientWithExperimental, err := client.NewClient( + client.WithDockerClient(localMockDockerClient), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithExperimental(true), ) h.AssertNil(t, err) @@ -188,8 +188,8 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { bpURL := fmt.Sprintf("https://example.com/bp.%s.tgz", h.RandString(12)) mockDownloader.EXPECT().Download(gomock.Any(), bpURL).Return(fakeBlob, nil).AnyTimes() - h.AssertNil(t, packClientWithExperimental.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ - Format: pack.FormatImage, + h.AssertNil(t, packClientWithExperimental.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ + Format: client.FormatImage, Name: fakeImage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: daemonOS}, @@ -207,13 +207,13 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("fails without experimental on Windows daemons", func() { windowsMockDockerClient := testmocks.NewMockCommonAPIClient(mockController) - packClientWithoutExperimental, err := pack.NewClient( - pack.WithDockerClient(windowsMockDockerClient), - pack.WithExperimental(false), + packClientWithoutExperimental, err := client.NewClient( + client.WithDockerClient(windowsMockDockerClient), + client.WithExperimental(false), ) h.AssertNil(t, err) - err = packClientWithoutExperimental.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err = packClientWithoutExperimental.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Config: pubbldpkg.Config{ Platform: dist.Platform{ OS: "windows", @@ -227,13 +227,13 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { windowsMockDockerClient := testmocks.NewMockCommonAPIClient(mockController) windowsMockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "windows"}, nil).AnyTimes() - packClientWithoutExperimental, err := pack.NewClient( - pack.WithDockerClient(windowsMockDockerClient), - pack.WithExperimental(false), + packClientWithoutExperimental, err := client.NewClient( + client.WithDockerClient(windowsMockDockerClient), + client.WithExperimental(false), ) h.AssertNil(t, err) - err = packClientWithoutExperimental.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err = packClientWithoutExperimental.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Config: pubbldpkg.Config{ Platform: dist.Platform{ OS: "linux", @@ -254,7 +254,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: nestedPackage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -294,7 +294,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { shouldFetchNestedPackage(true, pubcfg.PullAlways) packageImage := shouldCreateLocalPackage() - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packageImage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -321,7 +321,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { shouldFetchNestedPackage(false, pubcfg.PullAlways) packageImage := shouldCreateRemotePackage() - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packageImage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -348,7 +348,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { shouldFetchNestedPackage(false, pubcfg.PullNever) packageImage := shouldCreateRemotePackage() - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packageImage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -374,7 +374,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should fail without trying to retrieve nested image from registry", func() { shouldNotFindNestedPackageWhenCallingImageFetcherWith(true, pubcfg.PullNever) - h.AssertError(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertError(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "some/package", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -399,7 +399,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() - h.AssertError(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertError(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "some/package", Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -428,11 +428,11 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { localMockDockerClient := testmocks.NewMockCommonAPIClient(mockController) localMockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: imageOS}, nil).AnyTimes() - packClientWithExperimental, err := pack.NewClient( - pack.WithDockerClient(localMockDockerClient), - pack.WithLogger(logging.NewLogWithWriters(&out, &out)), - pack.WithDownloader(mockDownloader), - pack.WithExperimental(true), + packClientWithExperimental, err := client.NewClient( + client.WithDockerClient(localMockDockerClient), + client.WithLogger(logging.NewLogWithWriters(&out, &out)), + client.WithDownloader(mockDownloader), + client.WithExperimental(true), ) h.AssertNil(t, err) @@ -441,8 +441,8 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), bpURL).Return(fakeBlob, nil).AnyTimes() packagePath := filepath.Join(tmpDir, h.RandString(12)+"-test.cnb") - h.AssertNil(t, packClientWithExperimental.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ - Format: pack.FormatFile, + h.AssertNil(t, packClientWithExperimental.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ + Format: client.FormatFile, Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: imageOS}, @@ -498,7 +498,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { nestedPackage = fakes.NewImage("nested/package-"+h.RandString(12), "", nil) mockImageFactory.EXPECT().NewImage(nestedPackage.Name(), false, "linux").Return(nestedPackage, nil) - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: nestedPackage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -514,7 +514,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should pull and use local nested package image", func() { packagePath := filepath.Join(tmpDir, "test.cnb") - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -523,7 +523,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, })) assertPackageBPFileHasBuildpacks(t, packagePath, []dist.BuildpackDescriptor{packageDescriptor, childDescriptor}) @@ -534,7 +534,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should work", func() { packagePath := filepath.Join(tmpDir, "test.cnb") - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -543,7 +543,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, })) assertPackageBPFileHasBuildpacks(t, packagePath, []dist.BuildpackDescriptor{packageDescriptor, childDescriptor}) @@ -556,7 +556,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { packagePath := filepath.Join(tmpDir, "test.cnb") - err = subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err = subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -565,7 +565,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, }) h.AssertError(t, err, "downloading buildpack") }) @@ -579,7 +579,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { packagePath := filepath.Join(tmpDir, "test.cnb") - err = subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err = subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -588,9 +588,9 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, }) - h.AssertError(t, err, "creating buildpack") + h.AssertError(t, err, "packaging dependencies") }) }) }) @@ -613,7 +613,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { nestedPackage = fakes.NewImage("nested/package-"+h.RandString(12), "", nil) mockImageFactory.EXPECT().NewImage(nestedPackage.Name(), false, "linux").Return(nestedPackage, nil) - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: nestedPackage.Name(), Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -629,7 +629,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should include both of them", func() { packagePath := filepath.Join(tmpDir, "test.cnb") - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -639,7 +639,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, })) assertPackageBPFileHasBuildpacks(t, packagePath, []dist.BuildpackDescriptor{packageDescriptor, childDescriptor, secondChildDescriptor}) @@ -655,14 +655,14 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { dependencyPackageURI, err := paths.FilePathToURI(dependencyPackagePath, "") h.AssertNil(t, err) - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: dependencyPackagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, Buildpack: dist.BuildpackURI{URI: createBuildpack(childDescriptor)}, }, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, })) mockDownloader.EXPECT().Download(gomock.Any(), dependencyPackageURI).Return(blob.NewBlob(dependencyPackagePath), nil).AnyTimes() @@ -671,7 +671,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should open file and correctly add buildpacks", func() { packagePath := filepath.Join(tmpDir, "test.cnb") - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -680,7 +680,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, })) assertPackageBPFileHasBuildpacks(t, packagePath, []dist.BuildpackDescriptor{packageDescriptor, childDescriptor}) @@ -756,7 +756,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should open file and correctly add buildpacks", func() { packagePath := filepath.Join(tmpDir, "test.cnb") - h.AssertNil(t, subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: packagePath, Config: pubbldpkg.Config{ Platform: dist.Platform{OS: "linux"}, @@ -765,7 +765,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { }, Publish: false, PullPolicy: pubcfg.PullAlways, - Format: pack.FormatFile, + Format: client.FormatFile, Registry: "some-registry", })) @@ -779,7 +779,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it("should error", func() { mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() - err := subject.PackageBuildpack(context.TODO(), pack.PackageBuildpackOptions{ + err := subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "some-buildpack", Format: "invalid-format", Config: pubbldpkg.Config{ diff --git a/pull_buildpack.go b/pkg/client/pull_buildpack.go similarity index 95% rename from pull_buildpack.go rename to pkg/client/pull_buildpack.go index 5edcba13b0..ff9e5feaa2 100644 --- a/pull_buildpack.go +++ b/pkg/client/pull_buildpack.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -6,11 +6,11 @@ import ( "github.com/pkg/errors" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // PullBuildpackOptions are options available for PullBuildpack diff --git a/pull_buildpack_test.go b/pkg/client/pull_buildpack_test.go similarity index 81% rename from pull_buildpack_test.go rename to pkg/client/pull_buildpack_test.go index 34ace793b6..fc0375178e 100644 --- a/pull_buildpack_test.go +++ b/pkg/client/pull_buildpack_test.go @@ -1,4 +1,4 @@ -package pack_test +package client_test import ( "bytes" @@ -14,14 +14,14 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack" - "github.com/buildpacks/pack/config" cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" - "github.com/buildpacks/pack/testmocks" ) func TestPullBuildpack(t *testing.T) { @@ -32,7 +32,7 @@ func TestPullBuildpack(t *testing.T) { func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { var ( - subject *pack.Client + subject *client.Client mockController *gomock.Controller mockDownloader *testmocks.MockDownloader mockImageFactory *testmocks.MockImageFactory @@ -49,12 +49,12 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) var err error - subject, err = pack.NewClient( - pack.WithLogger(logging.NewLogWithWriters(&out, &out)), - pack.WithDownloader(mockDownloader), - pack.WithImageFactory(mockImageFactory), - pack.WithFetcher(mockImageFetcher), - pack.WithDockerClient(mockDockerClient), + subject, err = client.NewClient( + client.WithLogger(logging.NewLogWithWriters(&out, &out)), + client.WithDownloader(mockDownloader), + client.WithImageFactory(mockImageFactory), + client.WithFetcher(mockImageFetcher), + client.WithDockerClient(mockDockerClient), ) h.AssertNil(t, err) }) @@ -65,7 +65,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { when("buildpack has issues", func() { it("should fail if not in the registry", func() { - err := subject.PullBuildpack(context.TODO(), pack.PullBuildpackOptions{ + err := subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "invalid/image", RegistryName: registry.DefaultRegistryName, }) @@ -73,14 +73,14 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("should fail if it's a URI type", func() { - err := subject.PullBuildpack(context.TODO(), pack.PullBuildpackOptions{ + err := subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "file://some-file", }) h.AssertError(t, err, "unsupported buildpack URI type: 'URILocator'") }) it("should fail if not a valid URI", func() { - err := subject.PullBuildpack(context.TODO(), pack.PullBuildpackOptions{ + err := subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "G@Rb*g3_", }) h.AssertError(t, err, "invalid buildpack URI") @@ -94,7 +94,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, packageImage.SetLabel("io.buildpacks.buildpack.layers", `{}`)) mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(packageImage, nil) - h.AssertNil(t, subject.PullBuildpack(context.TODO(), pack.PullBuildpackOptions{ + h.AssertNil(t, subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "example.com/some/package:1.0.0", })) }) @@ -145,7 +145,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { }) it("should fetch the image", func() { - h.AssertNil(t, subject.PullBuildpack(context.TODO(), pack.PullBuildpackOptions{ + h.AssertNil(t, subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "example/foo@1.1.0", RegistryName: "some-registry", })) diff --git a/rebase.go b/pkg/client/rebase.go similarity index 96% rename from rebase.go rename to pkg/client/rebase.go index 3e4e194f90..5e5e379aec 100644 --- a/rebase.go +++ b/pkg/client/rebase.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -7,12 +7,12 @@ import ( "github.com/buildpacks/lifecycle/platform" "github.com/pkg/errors" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // RebaseOptions is a configuration struct that controls image rebase behavior. diff --git a/rebase_test.go b/pkg/client/rebase_test.go similarity index 99% rename from rebase_test.go rename to pkg/client/rebase_test.go index abce6f08d9..9d8119b4ef 100644 --- a/rebase_test.go +++ b/pkg/client/rebase_test.go @@ -1,12 +1,10 @@ -package pack +package client import ( "bytes" "context" "testing" - "github.com/buildpacks/pack/config" - "github.com/buildpacks/imgutil/fakes" "github.com/heroku/color" "github.com/sclevine/spec" @@ -14,6 +12,7 @@ import ( ifakes "github.com/buildpacks/pack/internal/fakes" "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/config" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/register_buildpack.go b/pkg/client/register_buildpack.go similarity index 96% rename from register_buildpack.go rename to pkg/client/register_buildpack.go index 2dfa2de6a1..5d015ebe8b 100644 --- a/register_buildpack.go +++ b/pkg/client/register_buildpack.go @@ -1,4 +1,4 @@ -package pack +package client import ( "context" @@ -7,11 +7,11 @@ import ( "runtime" "strings" - "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/image" "github.com/buildpacks/pack/internal/registry" + "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // RegisterBuildpackOptions is a configuration struct that controls the diff --git a/register_buildpack_test.go b/pkg/client/register_buildpack_test.go similarity index 99% rename from register_buildpack_test.go rename to pkg/client/register_buildpack_test.go index 0032e9b254..db7cc84cd2 100644 --- a/register_buildpack_test.go +++ b/pkg/client/register_buildpack_test.go @@ -1,4 +1,4 @@ -package pack +package client import ( "bytes" @@ -6,15 +6,14 @@ import ( "testing" "github.com/buildpacks/imgutil/fakes" + "github.com/heroku/color" + "github.com/sclevine/spec" + "github.com/sclevine/spec/report" ifakes "github.com/buildpacks/pack/internal/fakes" "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" h "github.com/buildpacks/pack/testhelpers" - - "github.com/heroku/color" - "github.com/sclevine/spec" - "github.com/sclevine/spec/report" ) func TestRegisterBuildpack(t *testing.T) { diff --git a/pkg/client/testdata/builder.toml b/pkg/client/testdata/builder.toml new file mode 100644 index 0000000000..afea99f8ef --- /dev/null +++ b/pkg/client/testdata/builder.toml @@ -0,0 +1,31 @@ +[[buildpacks]] +id = "some.bp1" +uri = "some-path-1" + +[[buildpacks]] +id = "some/bp2" +uri = "some-path-2" + +[[buildpacks]] +id = "some/bp2" +uri = "some-path-3" + +[[order]] +[[order.group]] + id = "some.bp1" + version = "1.2.3" + +[[order.group]] + id = "some/bp2" + version = "1.2.4" + +[[order]] +[[order.group]] + id = "some.bp1" + version = "1.2.3" + +[stack] +id = "com.example.stack" +build-image = "some/build" +run-image = "some/run" +run-image-mirrors = ["gcr.io/some/run2"] \ No newline at end of file diff --git a/pkg/client/testdata/buildpack-api-0.4/bin/build b/pkg/client/testdata/buildpack-api-0.4/bin/build new file mode 100644 index 0000000000..c76df1a291 --- /dev/null +++ b/pkg/client/testdata/buildpack-api-0.4/bin/build @@ -0,0 +1 @@ +build-contents \ No newline at end of file diff --git a/pkg/client/testdata/buildpack-api-0.4/bin/detect b/pkg/client/testdata/buildpack-api-0.4/bin/detect new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/client/testdata/buildpack-api-0.4/buildpack.toml b/pkg/client/testdata/buildpack-api-0.4/buildpack.toml new file mode 100644 index 0000000000..270e5771c0 --- /dev/null +++ b/pkg/client/testdata/buildpack-api-0.4/buildpack.toml @@ -0,0 +1,10 @@ +api = "0.4" + +[buildpack] +id = "bp.one" +version = "1.2.3" +homepage = "http://one.buildpack" + +[[stacks]] +id = "some.stack.id" +mixins = ["mixinX", "build:mixinY", "run:mixinZ"] diff --git a/pkg/client/testdata/buildpack/bin/build b/pkg/client/testdata/buildpack/bin/build new file mode 100644 index 0000000000..c76df1a291 --- /dev/null +++ b/pkg/client/testdata/buildpack/bin/build @@ -0,0 +1 @@ +build-contents \ No newline at end of file diff --git a/pkg/client/testdata/buildpack/bin/detect b/pkg/client/testdata/buildpack/bin/detect new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/client/testdata/buildpack/buildpack.toml b/pkg/client/testdata/buildpack/buildpack.toml new file mode 100644 index 0000000000..131cb045f6 --- /dev/null +++ b/pkg/client/testdata/buildpack/buildpack.toml @@ -0,0 +1,10 @@ +api = "0.3" + +[buildpack] +id = "bp.one" +version = "1.2.3" +homepage = "http://one.buildpack" + +[[stacks]] +id = "some.stack.id" +mixins = ["mixinX", "build:mixinY", "run:mixinZ"] diff --git a/pkg/client/testdata/buildpack2/bin/build b/pkg/client/testdata/buildpack2/bin/build new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/client/testdata/buildpack2/bin/detect b/pkg/client/testdata/buildpack2/bin/detect new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/client/testdata/buildpack2/buildpack.toml b/pkg/client/testdata/buildpack2/buildpack.toml new file mode 100644 index 0000000000..61a175d81d --- /dev/null +++ b/pkg/client/testdata/buildpack2/buildpack.toml @@ -0,0 +1,9 @@ +api = "0.3" + +[buildpack] +id = "some-other-buildpack-id" +version = "some-other-buildpack-version" + +[[stacks]] +id = "some.stack.id" +mixins = ["mixinA", "build:mixinB", "run:mixinC"] diff --git a/pkg/client/testdata/downloader/dirA/file.txt b/pkg/client/testdata/downloader/dirA/file.txt new file mode 100644 index 0000000000..c6187e4d11 --- /dev/null +++ b/pkg/client/testdata/downloader/dirA/file.txt @@ -0,0 +1 @@ +some file contents \ No newline at end of file diff --git a/pkg/client/testdata/empty-file b/pkg/client/testdata/empty-file new file mode 100644 index 0000000000..e69de29bb2 diff --git a/pkg/client/testdata/jar-file.jar b/pkg/client/testdata/jar-file.jar new file mode 100644 index 0000000000000000000000000000000000000000..0b703153c67ffe4d23fa45bbc37735b8055cea68 GIT binary patch literal 739 zcmWIWW@Zs#;Nak3m=f~Rj{ymAGO#fCx`sIFdiuHP|2xINz|0Wf&CUT*!30$nfK#&w zPz7AGucM!*n`>~0p0C?y-!rFuymj?1@_OrPojY@WbCAIm;|EWR^t^m^Jbf>gu43V0 zaQ)IFY9h1Rt5~E-yW2acxVu!u=JTYlCY3uYc7mN?(7~$U2(-Wnh!IYhh~|E7psYt~ zPENjFa!z7#ac+RG_hAQt+RHVjhPQ6b`W2bM@AM_1Pfjb2h;_vKy zbpBFv6MKDwz1N&xC&67CtT*T1+f%za{=WQthQ5pC35!w}_kLBg;@fp&!-L2df@g$h zp8Par!B6(>EPr+8b2(+}7#Bt^-Kdeb$Rg3jUwNir)xWzHa<*=cLaCb-bhu}pbz60j z^Yf}19mOk8oNM)%^v6RmHXjLk6RsF6+oZEWn7`oO6}&oY%_`$fQTsQ2V+O_S z18Ty6#X2ZqpaOVIgOUllR^-?MB?| zY-t5I10%~ Date: Thu, 28 Oct 2021 12:58:31 -0500 Subject: [PATCH 02/15] WIP: Fix version setting Signed-off-by: Javier Romero --- cmd/cmd.go | 6 +++--- pkg/client/build.go | 4 ++-- pkg/client/client.go | 24 +++++++++++++++++++++--- pkg/client/create_builder.go | 2 +- pkg/client/version.go | 6 ++++++ pkg/client/pack.go => version.go | 2 +- 6 files changed, 34 insertions(+), 10 deletions(-) create mode 100644 pkg/client/version.go rename pkg/client/pack.go => version.go (86%) diff --git a/cmd/cmd.go b/cmd/cmd.go index 637f612a58..c536dceff5 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -108,10 +108,10 @@ func NewPackCommand(logger ConfigurableLogger) (*cobra.Command, error) { } rootCmd.AddCommand(commands.CompletionCommand(logger, packHome)) - rootCmd.AddCommand(commands.Report(logger, client.Version, cfgPath)) - rootCmd.AddCommand(commands.Version(logger, client.Version)) + rootCmd.AddCommand(commands.Report(logger, packClient.Version(), cfgPath)) + rootCmd.AddCommand(commands.Version(logger, packClient.Version())) - rootCmd.Version = client.Version + rootCmd.Version = packClient.Version() rootCmd.SetVersionTemplate(`{{.Version}}{{"\n"}}`) rootCmd.SetOut(logging.GetWriterForLevel(logger, logging.InfoLevel)) rootCmd.SetErr(logging.GetWriterForLevel(logger, logging.ErrorLevel)) diff --git a/pkg/client/build.go b/pkg/client/build.go index 84af2fdbd3..9b225f98cf 100644 --- a/pkg/client/build.go +++ b/pkg/client/build.go @@ -282,7 +282,7 @@ func (c *Client) Build(ctx context.Context, opts BuildOptions) error { ) if !supportsPlatformAPI(builderPlatformAPIs) { - c.logger.Debugf("pack %s supports Platform API(s): %s", Version, strings.Join(build.SupportedPlatformAPIVersions.AsStrings(), ", ")) + c.logger.Debugf("pack %s supports Platform API(s): %s", c.version, strings.Join(build.SupportedPlatformAPIVersions.AsStrings(), ", ")) c.logger.Debugf("Builder %s supports Platform API(s): %s", style.Symbol(opts.Builder), strings.Join(builderPlatformAPIs.AsStrings(), ", ")) return errors.Errorf("Builder %s is incompatible with this version of pack", style.Symbol(opts.Builder)) } @@ -796,7 +796,7 @@ func (c *Client) createEphemeralBuilder(rawBuilderImage imgutil.Image, env map[s bldr.SetOrder(order) } - if err := bldr.Save(c.logger, builder.CreatorMetadata{Version: Version}); err != nil { + if err := bldr.Save(c.logger, builder.CreatorMetadata{Version: c.version}); err != nil { return nil, err } return bldr, nil diff --git a/pkg/client/client.go b/pkg/client/client.go index 3e09a9815e..b1be390e47 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -1,3 +1,17 @@ +/* +Package client provides all the functionally provided by pack as a library through a go api. + +Prerequisites + +In order to use most functionality, you will need an OCI runtime such as Docker or podman installed. + +References + +This package provides functionality to create and manipulate all artifacts outlined in the Cloud Native Buildpacks specification. +An introduction to these artifacts and their usage can be found at https://buildpacks.io/docs/. + +The formal specification of the pack platform provides can be found at: https://github.com/buildpacks/spec. +*/ package client import ( @@ -6,6 +20,7 @@ import ( "path/filepath" "github.com/buildpacks/imgutil" + "github.com/buildpacks/pack" dockerClient "github.com/docker/docker/client" "github.com/google/go-containerregistry/pkg/authn" "github.com/pkg/errors" @@ -77,6 +92,7 @@ type Client struct { buildpackDownloader BuildpackDownloader experimental bool registryMirrors map[string]string + version string } // ClientOption is a type of function that mutate settings on the client. @@ -155,10 +171,12 @@ const DockerAPIVersion = "1.38" // NewClient allocates and returns a Client configured with the specified options. func NewClient(opts ...ClientOption) (*Client, error) { - var client Client + client := &Client{ + version: pack.Version, + } for _, opt := range opts { - opt(&client) + opt(client) } if client.logger == nil { @@ -205,7 +223,7 @@ func NewClient(opts ...ClientOption) (*Client, error) { client.lifecycleExecutor = build.NewLifecycleExecutor(client.logger, client.docker) - return &client, nil + return client, nil } type registryResolver struct { diff --git a/pkg/client/create_builder.go b/pkg/client/create_builder.go index 5bda3a3ffc..41f8818227 100644 --- a/pkg/client/create_builder.go +++ b/pkg/client/create_builder.go @@ -60,7 +60,7 @@ func (c *Client) CreateBuilder(ctx context.Context, opts CreateBuilderOptions) e bldr.SetOrder(opts.Config.Order) bldr.SetStack(opts.Config.Stack) - return bldr.Save(c.logger, builder.CreatorMetadata{Version: Version}) + return bldr.Save(c.logger, builder.CreatorMetadata{Version: c.version}) } func (c *Client) validateConfig(ctx context.Context, opts CreateBuilderOptions) error { diff --git a/pkg/client/version.go b/pkg/client/version.go new file mode 100644 index 0000000000..a3533e8866 --- /dev/null +++ b/pkg/client/version.go @@ -0,0 +1,6 @@ +package client + +// Version returns the version of the client +func (c *Client) Version() string { + return c.version +} diff --git a/pkg/client/pack.go b/version.go similarity index 86% rename from pkg/client/pack.go rename to version.go index f4175841ac..6d858250f9 100644 --- a/pkg/client/pack.go +++ b/version.go @@ -1,4 +1,4 @@ -package client +package pack var ( // Version is the version of `pack`. It is injected at compile time. From 2936d7c3d2d6c7924cedfdcd42382cf88821df4d Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Thu, 28 Oct 2021 12:59:25 -0500 Subject: [PATCH 03/15] Make client example of build executable Signed-off-by: Javier Romero --- pkg/client/doc.go | 17 ----------------- .../{doc_test.go => example_build_test.go} | 19 ++++--------------- 2 files changed, 4 insertions(+), 32 deletions(-) delete mode 100644 pkg/client/doc.go rename pkg/client/{doc_test.go => example_build_test.go} (68%) diff --git a/pkg/client/doc.go b/pkg/client/doc.go deleted file mode 100644 index d840a14905..0000000000 --- a/pkg/client/doc.go +++ /dev/null @@ -1,17 +0,0 @@ -/* -Package pack is the reference implementation of a Cloud Native Buildpacks platform. Its purpose is to simplify the transformation -of application source code, into a runnable OCI images. - -Prerequisites - -In order to use most pack functionality, you will need to have Docker installed. -For easy installation instructions see: https://docs.docker.com/desktop/. - -References - -This package provides functionality to create and manipulate all artifacts outlined in the Cloud Native Buildpacks specification. -An introduction to these artifacts and their usage can be found at https://buildpacks.io/docs/. - -The formal specification of the pack platform provides can be found at: https://github.com/buildpacks/spec. -*/ -package client diff --git a/pkg/client/doc_test.go b/pkg/client/example_build_test.go similarity index 68% rename from pkg/client/doc_test.go rename to pkg/client/example_build_test.go index a613135d62..b10c877a06 100644 --- a/pkg/client/doc_test.go +++ b/pkg/client/example_build_test.go @@ -3,7 +3,7 @@ package client_test import ( "context" "fmt" - "math/rand" + "path/filepath" "github.com/buildpacks/pack/pkg/client" ) @@ -23,28 +23,16 @@ func Example_build() { // replace this with the location of a sample application // For a list of prepared samples see the 'apps' folder at // https://github.com/buildpacks/samples. - appPath := "local/path/to/application/root" - - // randomly select a builder to use from among the following - builderList := []string{ - "gcr.io/buildpacks/builder:v1", - "heroku/buildpacks:20", - "gcr.io/paketo-buildpacks/builder:base", - } - - randomIndex := rand.Intn(len(builderList)) - randomBuilder := builderList[randomIndex] + appPath := filepath.Join("testdata", "some-app") // initialize our options buildOpts := client.BuildOptions{ Image: "pack-lib-test-image:0.0.1", - Builder: randomBuilder, + Builder: "cnbs/sample-builder:bionic", AppPath: appPath, TrustBuilder: func(string) bool { return true }, } - fmt.Println("building application image") - // build an image err = pack.Build(context, buildOpts) if err != nil { @@ -52,4 +40,5 @@ func Example_build() { } fmt.Println("build completed") + // Output: build completed } From c9c8c9de8af0a6984863369255dd67d14dce4bf4 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Thu, 28 Oct 2021 21:45:31 -0500 Subject: [PATCH 04/15] Normalize buildpack.Downloader, blob.Downloader, image.Fetcher Signed-off-by: Javier Romero --- pkg/blob/downloader.go | 16 ++--- pkg/blob/downloader_test.go | 3 +- .../buildpack_downloader.go => downloader.go} | 10 +-- ..._downloader_test.go => downloader_test.go} | 47 +++++--------- .../testdata/buildpack/bin/build | 0 .../testdata/buildpack/bin/detect | 0 .../testdata/buildpack/buildpack.toml | 0 pkg/client/build.go | 14 ++--- pkg/client/build_test.go | 4 +- pkg/client/client.go | 63 ++++++++++++++----- pkg/client/client_test.go | 2 +- pkg/client/create_builder.go | 4 +- pkg/client/create_builder_test.go | 10 +-- pkg/client/inspect_buildpack.go | 2 +- pkg/client/inspect_buildpack_test.go | 4 +- pkg/client/package_buildpack.go | 4 +- pkg/client/package_buildpack_test.go | 4 +- pkg/client/pull_buildpack_test.go | 4 +- pkg/image/factory.go | 31 --------- pkg/image/fetcher_test.go | 44 ++++++------- pkg/testmocks/mock_blob_downloader.go | 50 +++++++++++++++ pkg/testmocks/mock_buildpack_downloader.go | 4 +- pkg/testmocks/mock_downloader.go | 50 --------------- testmocks/mock_registry_resolver.go | 48 ++++++++++++++ 24 files changed, 224 insertions(+), 194 deletions(-) rename pkg/buildpack/{downloader/buildpack_downloader.go => downloader.go} (93%) rename pkg/buildpack/{downloader/buildpack_downloader_test.go => downloader_test.go} (89%) rename pkg/buildpack/{downloader => }/testdata/buildpack/bin/build (100%) rename pkg/buildpack/{downloader => }/testdata/buildpack/bin/detect (100%) rename pkg/buildpack/{downloader => }/testdata/buildpack/buildpack.toml (100%) delete mode 100644 pkg/image/factory.go create mode 100644 pkg/testmocks/mock_blob_downloader.go delete mode 100644 pkg/testmocks/mock_downloader.go create mode 100644 testmocks/mock_registry_resolver.go diff --git a/pkg/blob/downloader.go b/pkg/blob/downloader.go index 6f538f9683..fe9b5ead37 100644 --- a/pkg/blob/downloader.go +++ b/pkg/blob/downloader.go @@ -24,19 +24,19 @@ const ( cacheVersion = "2" ) -type downloader struct { +type Downloader struct { logger logging.Logger baseCacheDir string } -func NewDownloader(logger logging.Logger, baseCacheDir string) *downloader { //nolint:golint,gosimple - return &downloader{ +func NewDownloader(logger logging.Logger, baseCacheDir string) *Downloader { //nolint:golint,gosimple + return &Downloader{ logger: logger, baseCacheDir: baseCacheDir, } } -func (d *downloader) Download(ctx context.Context, pathOrURI string) (Blob, error) { +func (d *Downloader) Download(ctx context.Context, pathOrURI string) (Blob, error) { if paths.IsURI(pathOrURI) { parsedURL, err := url.Parse(pathOrURI) if err != nil { @@ -64,7 +64,7 @@ func (d *downloader) Download(ctx context.Context, pathOrURI string) (Blob, erro return &blob{path: path}, nil } -func (d *downloader) handleFile(path string) string { +func (d *Downloader) handleFile(path string) string { path, err := filepath.Abs(path) if err != nil { return "" @@ -73,7 +73,7 @@ func (d *downloader) handleFile(path string) string { return path } -func (d *downloader) handleHTTP(ctx context.Context, uri string) (string, error) { +func (d *Downloader) handleHTTP(ctx context.Context, uri string) (string, error) { cacheDir := d.versionedCacheDir() if err := os.MkdirAll(cacheDir, 0750); err != nil { @@ -123,7 +123,7 @@ func (d *downloader) handleHTTP(ctx context.Context, uri string) (string, error) return cachePath, nil } -func (d *downloader) downloadAsStream(ctx context.Context, uri string, etag string) (io.ReadCloser, string, error) { +func (d *Downloader) downloadAsStream(ctx context.Context, uri string, etag string) (io.ReadCloser, string, error) { req, err := http.NewRequest("GET", uri, nil) if err != nil { return nil, "", err @@ -171,7 +171,7 @@ type progressReader struct { io.Closer } -func (d *downloader) versionedCacheDir() string { +func (d *Downloader) versionedCacheDir() string { return filepath.Join(d.baseCacheDir, cacheDirPrefix+cacheVersion) } diff --git a/pkg/blob/downloader_test.go b/pkg/blob/downloader_test.go index 657b6f5e2a..2415d146b4 100644 --- a/pkg/blob/downloader_test.go +++ b/pkg/blob/downloader_test.go @@ -17,7 +17,6 @@ import ( "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/client" h "github.com/buildpacks/pack/testhelpers" ) @@ -32,7 +31,7 @@ func testDownloader(t *testing.T, when spec.G, it spec.S) { var ( cacheDir string err error - subject client.Downloader + subject *blob.Downloader ) it.Before(func() { diff --git a/pkg/buildpack/downloader/buildpack_downloader.go b/pkg/buildpack/downloader.go similarity index 93% rename from pkg/buildpack/downloader/buildpack_downloader.go rename to pkg/buildpack/downloader.go index 938bff1c67..dd7adee018 100644 --- a/pkg/buildpack/downloader/buildpack_downloader.go +++ b/pkg/buildpack/downloader.go @@ -1,4 +1,4 @@ -package downloader +package buildpack import ( "context" @@ -27,7 +27,7 @@ type Downloader interface { Download(ctx context.Context, pathOrURI string) (blob.Blob, error) } -//go:generate mockgen -package testmocks -destination ../../testmocks/mock_registry_resolver.go github.com/buildpacks/pack/pkg/buildpack/downloader RegistryResolver +//go:generate mockgen -package testmocks -destination ../../testmocks/mock_registry_resolver.go github.com/buildpacks/pack/pkg/buildpack RegistryResolver type RegistryResolver interface { Resolve(registryName, bpURI string) (string, error) @@ -40,7 +40,7 @@ type buildpackDownloader struct { registryResolver RegistryResolver } -func NewBuildpackDownloader(logger logging.Logger, imageFetcher ImageFetcher, downloader Downloader, registryResolver RegistryResolver) *buildpackDownloader { //nolint:golint,gosimple +func NewDownloader(logger logging.Logger, imageFetcher ImageFetcher, downloader Downloader, registryResolver RegistryResolver) *buildpackDownloader { //nolint:golint,gosimple return &buildpackDownloader{ logger: logger, imageFetcher: imageFetcher, @@ -49,7 +49,7 @@ func NewBuildpackDownloader(logger logging.Logger, imageFetcher ImageFetcher, do } } -type BuildpackDownloadOptions struct { +type DownloadOptions struct { // Buildpack registry name. Defines where all registry buildpacks will be pulled from. RegistryName string @@ -67,7 +67,7 @@ type BuildpackDownloadOptions struct { PullPolicy config.PullPolicy } -func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, opts BuildpackDownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { +func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, opts DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { var err error var locatorType buildpack.LocatorType if buildpackURI == "" && opts.ImageName != "" { diff --git a/pkg/buildpack/downloader/buildpack_downloader_test.go b/pkg/buildpack/downloader_test.go similarity index 89% rename from pkg/buildpack/downloader/buildpack_downloader_test.go rename to pkg/buildpack/downloader_test.go index 9117659819..1f0566ab9f 100644 --- a/pkg/buildpack/downloader/buildpack_downloader_test.go +++ b/pkg/buildpack/downloader_test.go @@ -1,4 +1,4 @@ -package downloader_test +package buildpack_test import ( "bytes" @@ -25,7 +25,7 @@ import ( "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/config" image "github.com/buildpacks/pack/pkg/image" @@ -42,7 +42,7 @@ func TestBuildpackDownloader(t *testing.T) { func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { var ( mockController *gomock.Controller - mockDownloader *testmocks.MockDownloader + mockDownloader *testmocks.MockBlobDownloader mockImageFactory *testmocks.MockImageFactory mockImageFetcher *testmocks.MockImageFetcher mockRegistryResolver *testmocks.MockRegistryResolver @@ -93,7 +93,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { it.Before(func() { logger = ilogging.NewLogWithWriters(&out, &out, ilogging.WithVerbose()) mockController = gomock.NewController(t) - mockDownloader = testmocks.NewMockDownloader(mockController) + mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockRegistryResolver = testmocks.NewMockRegistryResolver(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) @@ -101,7 +101,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz").Return(blob.NewBlob(filepath.Join("testdata", "buildpack")), nil).AnyTimes() mockDownloader.EXPECT().Download(gomock.Any(), "some/buildpack/dir").Return(blob.NewBlob(filepath.Join("testdata", "buildpack")), nil).AnyTimes() - buildpackDownloader = downloader.NewBuildpackDownloader(logger, mockImageFetcher, mockDownloader, mockRegistryResolver) + buildpackDownloader = buildpack.NewDownloader(logger, mockImageFetcher, mockDownloader, mockRegistryResolver) mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() @@ -117,34 +117,17 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { var err error tmpDir, err = ioutil.TempDir("", "buildpack-downloader-test") h.AssertNil(t, err) - - // registryFixture := h.CreateRegistryFixture(t, tmpDir, filepath.Join("testdata", "registry")) - - // packHome := filepath.Join(tmpDir, ".pack") - // configPath := filepath.Join(packHome, "config.toml") - - // h.AssertNil(t, cfg.Write(cfg.Config{ - // Registries: []cfg.Registry{ - // { - // Name: "some-registry", - // Type: "github", - // URL: registryFixture, - // }, - // }, - // }, configPath)) - // h.AssertNil(t, err) }) it.After(func() { mockController.Finish() h.AssertNil(t, os.RemoveAll(tmpDir)) - // os.Unsetenv("PACK_HOME") }) when("#DownloadBuildpack", func() { var ( packageImage *fakes.Image - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ImageOS: "linux"} + buildpackDownloadOptions = buildpack.DownloadOptions{ImageOS: "linux"} ) shouldFetchPackageImageWith := func(demon bool, pull config.PullPolicy) { @@ -158,7 +141,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=true and pull-policy=always", func() { it("should pull and use local package image", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ RegistryName: "some-registry", ImageOS: "linux", Daemon: true, @@ -174,7 +157,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("ambigious URI provided", func() { it("should find package in registry", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ RegistryName: "some-registry", ImageOS: "linux", Daemon: true, @@ -201,7 +184,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("image key is provided", func() { it("should succeed", func() { packageImage = createPackage("some/package:tag") - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ Daemon: true, PullPolicy: config.PullAlways, ImageOS: "linux", @@ -217,7 +200,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=true and pull-policy=always", func() { it("should pull and use local package image", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, @@ -233,7 +216,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=false and pull-policy=always", func() { it("should use remote package image", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, @@ -249,7 +232,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=false and pull-policy=always", func() { it("should use remote package URI", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", Daemon: false, PullPolicy: config.PullAlways, @@ -263,7 +246,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("publish=true and pull-policy=never", func() { it("should push to registry and not pull package image", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, @@ -279,7 +262,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("daemon=true pull-policy=never and there is no local package image", func() { it("should fail without trying to retrieve package image from registry", func() { - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, @@ -304,7 +287,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { buildpackPath := filepath.Join("testdata", "buildpack") buildpackURI, _ := paths.FilePathToURI(buildpackPath, "") mockDownloader.EXPECT().Download(gomock.Any(), buildpackURI).Return(blob.NewBlob(buildpackPath), nil).AnyTimes() - buildpackDownloadOptions = downloader.BuildpackDownloadOptions{ + buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", RelativeBaseDir: "testdata", } diff --git a/pkg/buildpack/downloader/testdata/buildpack/bin/build b/pkg/buildpack/testdata/buildpack/bin/build similarity index 100% rename from pkg/buildpack/downloader/testdata/buildpack/bin/build rename to pkg/buildpack/testdata/buildpack/bin/build diff --git a/pkg/buildpack/downloader/testdata/buildpack/bin/detect b/pkg/buildpack/testdata/buildpack/bin/detect similarity index 100% rename from pkg/buildpack/downloader/testdata/buildpack/bin/detect rename to pkg/buildpack/testdata/buildpack/bin/detect diff --git a/pkg/buildpack/downloader/testdata/buildpack/buildpack.toml b/pkg/buildpack/testdata/buildpack/buildpack.toml similarity index 100% rename from pkg/buildpack/downloader/testdata/buildpack/buildpack.toml rename to pkg/buildpack/testdata/buildpack/buildpack.toml diff --git a/pkg/client/build.go b/pkg/client/build.go index 9b225f98cf..7fb8db97f1 100644 --- a/pkg/client/build.go +++ b/pkg/client/build.go @@ -23,7 +23,7 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/buildpack" + ibuildpack "github.com/buildpacks/pack/internal/buildpack" internalConfig "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" pname "github.com/buildpacks/pack/internal/name" @@ -33,7 +33,7 @@ import ( "github.com/buildpacks/pack/internal/termui" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" projectTypes "github.com/buildpacks/pack/pkg/project/types" @@ -713,13 +713,13 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima order = dist.Order{{Group: []dist.BuildpackRef{}}} for _, bp := range declaredBPs { - locatorType, err := buildpack.GetLocatorType(bp, relativeBaseDir, builderBPs) + locatorType, err := ibuildpack.GetLocatorType(bp, relativeBaseDir, builderBPs) if err != nil { return nil, nil, err } switch locatorType { - case buildpack.FromBuilderLocator: + case ibuildpack.FromBuilderLocator: switch { case len(order) == 0 || len(order[0].Group) == 0: order = builderOrder @@ -736,8 +736,8 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima order = newOrder } - case buildpack.IDLocator: - id, version := buildpack.ParseIDLocator(bp) + case ibuildpack.IDLocator: + id, version := ibuildpack.ParseIDLocator(bp) order = appendBuildpackToOrder(order, dist.BuildpackInfo{ ID: id, Version: version, @@ -747,7 +747,7 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima if err != nil { return fetchedBPs, order, errors.Wrapf(err, "getting OS from %s", style.Symbol(builderImage.Name())) } - mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, bp, downloader.BuildpackDownloadOptions{ + mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, bp, buildpack.DownloadOptions{ RegistryName: registry, ImageOS: imageOS, RelativeBaseDir: relativeBaseDir, diff --git a/pkg/client/build_test.go b/pkg/client/build_test.go index fa6f1be806..9637a378ee 100644 --- a/pkg/client/build_test.go +++ b/pkg/client/build_test.go @@ -42,7 +42,7 @@ import ( rg "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/config" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" @@ -126,7 +126,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) blobDownloader := blob.NewDownloader(logger, dlCacheDir) - buildpackDownloader := downloader.NewBuildpackDownloader(logger, fakeImageFetcher, blobDownloader, ®istryResolver{logger: logger}) + buildpackDownloader := buildpack.NewDownloader(logger, fakeImageFetcher, blobDownloader, ®istryResolver{logger: logger}) subject = &Client{ logger: logger, imageFetcher: fakeImageFetcher, diff --git a/pkg/client/client.go b/pkg/client/client.go index b1be390e47..25f77dbc80 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -20,6 +20,8 @@ import ( "path/filepath" "github.com/buildpacks/imgutil" + "github.com/buildpacks/imgutil/local" + "github.com/buildpacks/imgutil/remote" "github.com/buildpacks/pack" dockerClient "github.com/docker/docker/client" "github.com/google/go-containerregistry/pkg/authn" @@ -31,7 +33,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/image" ) @@ -53,10 +55,10 @@ type ImageFetcher interface { Fetch(ctx context.Context, name string, options image.FetchOptions) (imgutil.Image, error) } -//go:generate mockgen -package testmocks -destination ../testmocks/mock_downloader.go github.com/buildpacks/pack/pkg/client Downloader +//go:generate mockgen -package testmocks -destination ../testmocks/mock_blob_downloader.go github.com/buildpacks/pack/pkg/client BlobDownloader -// Downloader is an interface for collecting both remote and local assets. -type Downloader interface { +// BlobDownloader is an interface for collecting both remote and local assets as blobs. +type BlobDownloader interface { // Download collects both local and remote assets and provides a blob object // used to read asset contents. Download(ctx context.Context, pathOrURI string) (blob.Blob, error) @@ -76,23 +78,26 @@ type ImageFactory interface { // BuildpackDownloader is an interface for downloading and extracting buildpacks from various sources type BuildpackDownloader interface { // Download parses a buildpack URI and downloads the buildpack and any dependencies buildpacks from the appropriate source - Download(ctx context.Context, buildpackURI string, opts downloader.BuildpackDownloadOptions) (dist.Buildpack, []dist.Buildpack, error) + Download(ctx context.Context, buildpackURI string, opts buildpack.DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) } // Client is an orchestration object, it contains all parameters needed to // build an app image using Cloud Native Buildpacks. // All settings on this object should be changed through ClientOption functions. type Client struct { - logger logging.Logger + logger logging.Logger + docker dockerClient.CommonAPIClient + + keychain authn.Keychain + imageFactory ImageFactory imageFetcher ImageFetcher - downloader Downloader + downloader BlobDownloader lifecycleExecutor LifecycleExecutor - docker dockerClient.CommonAPIClient - imageFactory ImageFactory buildpackDownloader BuildpackDownloader - experimental bool - registryMirrors map[string]string - version string + + experimental bool + registryMirrors map[string]string + version string } // ClientOption is a type of function that mutate settings on the client. @@ -123,7 +128,7 @@ func WithFetcher(f ImageFetcher) ClientOption { // WithDownloader supply your own downloader. // A Downloader is used to gather buildpacks from both remote urls, or local sources. -func WithDownloader(d Downloader) ClientOption { +func WithDownloader(d BlobDownloader) ClientOption { return func(c *Client) { c.downloader = d } @@ -167,12 +172,20 @@ func WithRegistryMirrors(registryMirrors map[string]string) ClientOption { } } +// WithKeychain sets keychain of credentials to image registries +func WithKeychain(keychain authn.Keychain) ClientOption { + return func(c *Client) { + c.keychain = keychain + } +} + const DockerAPIVersion = "1.38" // NewClient allocates and returns a Client configured with the specified options. func NewClient(opts ...ClientOption) (*Client, error) { client := &Client{ - version: pack.Version, + version: pack.Version, + keychain: authn.DefaultKeychain, } for _, opt := range opts { @@ -207,11 +220,14 @@ func NewClient(opts ...ClientOption) (*Client, error) { } if client.imageFactory == nil { - client.imageFactory = image.NewFactory(client.docker, authn.DefaultKeychain) + client.imageFactory = &imageFactory{ + dockerClient: client.docker, + keychain: client.keychain, + } } if client.buildpackDownloader == nil { - client.buildpackDownloader = downloader.NewBuildpackDownloader( + client.buildpackDownloader = buildpack.NewDownloader( client.logger, client.imageFetcher, client.downloader, @@ -243,3 +259,18 @@ func (r *registryResolver) Resolve(registryName, bpName string) (string, error) return regBuildpack.Address, nil } + +type imageFactory struct { + dockerClient dockerClient.CommonAPIClient + keychain authn.Keychain +} + +func (f *imageFactory) NewImage(repoName string, daemon bool, imageOS string) (imgutil.Image, error) { + platform := imgutil.Platform{OS: imageOS} + + if daemon { + return local.NewImage(repoName, f.dockerClient, local.WithDefaultPlatform(platform)) + } + + return remote.NewImage(repoName, f.keychain, remote.WithDefaultPlatform(platform)) +} diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index 00ce946a81..d020987bdf 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -78,7 +78,7 @@ func testClient(t *testing.T, when spec.G, it spec.S) { when("#WithDownloader", func() { it("uses image factory provided", func() { mockController := gomock.NewController(t) - mockDownloader := testmocks.NewMockDownloader(mockController) + mockDownloader := testmocks.NewMockBlobDownloader(mockController) cl, err := NewClient(WithDownloader(mockDownloader)) h.AssertNil(t, err) h.AssertSameInstance(t, cl.downloader, mockDownloader) diff --git a/pkg/client/create_builder.go b/pkg/client/create_builder.go index 41f8818227..39a00fabbf 100644 --- a/pkg/client/create_builder.go +++ b/pkg/client/create_builder.go @@ -13,7 +13,7 @@ import ( "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -210,7 +210,7 @@ func (c *Client) addBuildpacksToBuilder(ctx context.Context, opts CreateBuilderO return errors.Wrapf(err, "getting OS from %s", style.Symbol(bldr.Image().Name())) } - mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, b.URI, downloader.BuildpackDownloadOptions{ + mainBP, depBPs, err := c.buildpackDownloader.Download(ctx, b.URI, buildpack.DownloadOptions{ RegistryName: opts.Registry, ImageOS: imageOS, RelativeBaseDir: opts.RelativeBaseDir, diff --git a/pkg/client/create_builder_test.go b/pkg/client/create_builder_test.go index cfa753fe10..40732f0615 100644 --- a/pkg/client/create_builder_test.go +++ b/pkg/client/create_builder_test.go @@ -30,7 +30,7 @@ import ( "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" @@ -48,7 +48,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { when("#CreateBuilder", func() { var ( mockController *gomock.Controller - mockDownloader *testmocks.MockDownloader + mockDownloader *testmocks.MockBlobDownloader mockBuildpackDownloader *testmocks.MockBuildpackDownloader mockImageFactory *testmocks.MockImageFactory mockImageFetcher *testmocks.MockImageFetcher @@ -76,7 +76,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) return buildpack } - var shouldCallBuildpackDownloaderWith = func(uri string, buildpackDownloadOptions downloader.BuildpackDownloadOptions) { + var shouldCallBuildpackDownloaderWith = func(uri string, buildpackDownloadOptions buildpack.DownloadOptions) { buildpack := createBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.3"), Info: dist.BuildpackInfo{ID: "example/foo", Version: "1.1.0"}, @@ -88,7 +88,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { it.Before(func() { logger = ilogging.NewLogWithWriters(&out, &out, ilogging.WithVerbose()) mockController = gomock.NewController(t) - mockDownloader = testmocks.NewMockDownloader(mockController) + mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) @@ -725,7 +725,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }, ) - shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", downloader.BuildpackDownloadOptions{Daemon: true, PullPolicy: config.PullAlways, RegistryName: "some-"}) + shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", buildpack.DownloadOptions{Daemon: true, PullPolicy: config.PullAlways, RegistryName: "some-"}) h.AssertNil(t, subject.CreateBuilder(context.TODO(), opts)) }) }) diff --git a/pkg/client/inspect_buildpack.go b/pkg/client/inspect_buildpack.go index 9b59b0a978..568d9fc2c3 100644 --- a/pkg/client/inspect_buildpack.go +++ b/pkg/client/inspect_buildpack.go @@ -85,7 +85,7 @@ func metadataFromRegistry(client *Client, name, registry string) (buildpackMd bu return buildpackMd, layersMd, nil } -func metadataFromArchive(downloader Downloader, path string) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { +func metadataFromArchive(downloader BlobDownloader, path string) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { imgBlob, err := downloader.Download(context.Background(), path) if err != nil { return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to download archive: %q", err) diff --git a/pkg/client/inspect_buildpack_test.go b/pkg/client/inspect_buildpack_test.go index af403b6227..51cd224463 100644 --- a/pkg/client/inspect_buildpack_test.go +++ b/pkg/client/inspect_buildpack_test.go @@ -162,7 +162,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { buildpackImage *fakes.Image apiVersion *api.Version expectedInfo *client.BuildpackInfo - mockDownloader *testmocks.MockDownloader + mockDownloader *testmocks.MockBlobDownloader tmpDir string buildpackPath string @@ -171,7 +171,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) - mockDownloader = testmocks.NewMockDownloader(mockController) + mockDownloader = testmocks.NewMockBlobDownloader(mockController) subject = &client.Client{} client.WithLogger(logging.NewLogWithWriters(&out, &out))(subject) diff --git a/pkg/client/package_buildpack.go b/pkg/client/package_buildpack.go index c475422f45..f68c61b878 100644 --- a/pkg/client/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -12,7 +12,7 @@ import ( "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/buildpack/downloader" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/config" ) @@ -95,7 +95,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti for _, dep := range opts.Config.Dependencies { var depBPs []dist.Buildpack - mainBP, deps, err := c.buildpackDownloader.Download(ctx, dep.URI, downloader.BuildpackDownloadOptions{ + mainBP, deps, err := c.buildpackDownloader.Download(ctx, dep.URI, buildpack.DownloadOptions{ RegistryName: opts.Registry, RelativeBaseDir: opts.RelativeBaseDir, ImageOS: "linux", diff --git a/pkg/client/package_buildpack_test.go b/pkg/client/package_buildpack_test.go index 8f22222681..39847e5085 100644 --- a/pkg/client/package_buildpack_test.go +++ b/pkg/client/package_buildpack_test.go @@ -43,7 +43,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { var ( subject *client.Client mockController *gomock.Controller - mockDownloader *testmocks.MockDownloader + mockDownloader *testmocks.MockBlobDownloader mockImageFactory *testmocks.MockImageFactory mockImageFetcher *testmocks.MockImageFetcher mockDockerClient *testmocks.MockCommonAPIClient @@ -52,7 +52,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) - mockDownloader = testmocks.NewMockDownloader(mockController) + mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) diff --git a/pkg/client/pull_buildpack_test.go b/pkg/client/pull_buildpack_test.go index fc0375178e..a56ad08bcc 100644 --- a/pkg/client/pull_buildpack_test.go +++ b/pkg/client/pull_buildpack_test.go @@ -34,7 +34,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { var ( subject *client.Client mockController *gomock.Controller - mockDownloader *testmocks.MockDownloader + mockDownloader *testmocks.MockBlobDownloader mockImageFactory *testmocks.MockImageFactory mockImageFetcher *testmocks.MockImageFetcher mockDockerClient *testmocks.MockCommonAPIClient @@ -43,7 +43,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) - mockDownloader = testmocks.NewMockDownloader(mockController) + mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockImageFactory = testmocks.NewMockImageFactory(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) mockDockerClient = testmocks.NewMockCommonAPIClient(mockController) diff --git a/pkg/image/factory.go b/pkg/image/factory.go deleted file mode 100644 index 327bea5682..0000000000 --- a/pkg/image/factory.go +++ /dev/null @@ -1,31 +0,0 @@ -package image - -import ( - "github.com/buildpacks/imgutil" - "github.com/buildpacks/imgutil/local" - "github.com/buildpacks/imgutil/remote" - "github.com/docker/docker/client" - "github.com/google/go-containerregistry/pkg/authn" -) - -type DefaultImageFactory struct { - dockerClient client.CommonAPIClient - keychain authn.Keychain -} - -func NewFactory(dockerClient client.CommonAPIClient, keychain authn.Keychain) *DefaultImageFactory { - return &DefaultImageFactory{ - dockerClient: dockerClient, - keychain: keychain, - } -} - -func (f *DefaultImageFactory) NewImage(repoName string, daemon bool, imageOS string) (imgutil.Image, error) { - platform := imgutil.Platform{OS: imageOS} - - if daemon { - return local.NewImage(repoName, f.dockerClient, local.WithDefaultPlatform(platform)) - } - - return remote.NewImage(repoName, f.keychain, remote.WithDefaultPlatform(platform)) -} diff --git a/pkg/image/fetcher_test.go b/pkg/image/fetcher_test.go index ab05c9d4aa..64873b258b 100644 --- a/pkg/image/fetcher_test.go +++ b/pkg/image/fetcher_test.go @@ -48,16 +48,16 @@ func TestFetcher(t *testing.T) { func testFetcher(t *testing.T, when spec.G, it spec.S) { var ( - fetcher *image.Fetcher - repoName string - repo string - outBuf bytes.Buffer + imageFetcher *image.Fetcher + repoName string + repo string + outBuf bytes.Buffer ) it.Before(func() { repo = "some-org/" + h.RandString(10) repoName = registryConfig.RepoName(repo) - fetcher = image.NewFetcher(logging.NewLogWithWriters(&outBuf, &outBuf), docker) + imageFetcher = image.NewFetcher(logging.NewLogWithWriters(&outBuf, &outBuf), docker) }) when("#Fetch", func() { @@ -72,14 +72,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the remote image", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) h.AssertNil(t, err) }) }) when("there is no remote image", func() { it("returns an error", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist in registry", repoName)) }) }) @@ -95,14 +95,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the remote image", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertNil(t, err) }) }) when("there is no remote image", func() { it("returns an error", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist in registry", repoName)) }) }) @@ -129,14 +129,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -164,7 +164,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { var outCons *color.Console outCons, output = h.MockWriterAndOutput() logger = logging.NewLogWithWriters(outCons, outCons) - fetcher = image.NewFetcher(logger, docker) + imageFetcher = image.NewFetcher(logger, docker) }) it.After(func() { @@ -172,14 +172,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("pull the image and return the local copy", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) h.AssertNil(t, err) h.AssertNotEq(t, output(), "") }) it("doesn't log anything in quiet mode", func() { logger.WantQuiet(true) - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) h.AssertNil(t, err) h.AssertEq(t, output(), "") }) @@ -199,14 +199,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -214,7 +214,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("image platform is specified", func() { it("passes the platform argument to the daemon", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways, Platform: "some-unsupported-platform"}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways, Platform: "some-unsupported-platform"}) h.AssertError(t, err, "unknown operating system or architecture") }) }) @@ -267,7 +267,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - fetchedImg, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertNil(t, err) h.AssertNotContains(t, outBuf.String(), "Pulling image") @@ -281,7 +281,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("there is no local image", func() { it("returns the remote image", func() { - fetchedImg, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertNil(t, err) fetchedImgLabel, err := fetchedImg.Label(label) @@ -305,14 +305,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -320,7 +320,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("image platform is specified", func() { it("passes the platform argument to the daemon", func() { - _, err := fetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent, Platform: "some-unsupported-platform"}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent, Platform: "some-unsupported-platform"}) h.AssertError(t, err, "unknown operating system or architecture") }) }) diff --git a/pkg/testmocks/mock_blob_downloader.go b/pkg/testmocks/mock_blob_downloader.go new file mode 100644 index 0000000000..71e148a25d --- /dev/null +++ b/pkg/testmocks/mock_blob_downloader.go @@ -0,0 +1,50 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/buildpacks/pack/pkg/client (interfaces: BlobDownloader) + +// Package testmocks is a generated GoMock package. +package testmocks + +import ( + context "context" + blob "github.com/buildpacks/pack/pkg/blob" + gomock "github.com/golang/mock/gomock" + reflect "reflect" +) + +// MockBlobDownloader is a mock of BlobDownloader interface +type MockBlobDownloader struct { + ctrl *gomock.Controller + recorder *MockBlobDownloaderMockRecorder +} + +// MockBlobDownloaderMockRecorder is the mock recorder for MockBlobDownloader +type MockBlobDownloaderMockRecorder struct { + mock *MockBlobDownloader +} + +// NewMockBlobDownloader creates a new mock instance +func NewMockBlobDownloader(ctrl *gomock.Controller) *MockBlobDownloader { + mock := &MockBlobDownloader{ctrl: ctrl} + mock.recorder = &MockBlobDownloaderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use +func (m *MockBlobDownloader) EXPECT() *MockBlobDownloaderMockRecorder { + return m.recorder +} + +// Download mocks base method +func (m *MockBlobDownloader) Download(arg0 context.Context, arg1 string) (blob.Blob, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Download", arg0, arg1) + ret0, _ := ret[0].(blob.Blob) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Download indicates an expected call of Download +func (mr *MockBlobDownloaderMockRecorder) Download(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Download", reflect.TypeOf((*MockBlobDownloader)(nil).Download), arg0, arg1) +} diff --git a/pkg/testmocks/mock_buildpack_downloader.go b/pkg/testmocks/mock_buildpack_downloader.go index c5becc9651..11d8f834d4 100644 --- a/pkg/testmocks/mock_buildpack_downloader.go +++ b/pkg/testmocks/mock_buildpack_downloader.go @@ -7,7 +7,7 @@ package testmocks import ( context "context" dist "github.com/buildpacks/pack/internal/dist" - downloader "github.com/buildpacks/pack/pkg/buildpack/downloader" + buildpack "github.com/buildpacks/pack/pkg/buildpack" gomock "github.com/golang/mock/gomock" reflect "reflect" ) @@ -36,7 +36,7 @@ func (m *MockBuildpackDownloader) EXPECT() *MockBuildpackDownloaderMockRecorder } // Download mocks base method -func (m *MockBuildpackDownloader) Download(arg0 context.Context, arg1 string, arg2 downloader.BuildpackDownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { +func (m *MockBuildpackDownloader) Download(arg0 context.Context, arg1 string, arg2 buildpack.DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Download", arg0, arg1, arg2) ret0, _ := ret[0].(dist.Buildpack) diff --git a/pkg/testmocks/mock_downloader.go b/pkg/testmocks/mock_downloader.go deleted file mode 100644 index 916cceca1a..0000000000 --- a/pkg/testmocks/mock_downloader.go +++ /dev/null @@ -1,50 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/buildpacks/pack/pkg/client (interfaces: Downloader) - -// Package testmocks is a generated GoMock package. -package testmocks - -import ( - context "context" - blob "github.com/buildpacks/pack/pkg/blob" - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockDownloader is a mock of Downloader interface -type MockDownloader struct { - ctrl *gomock.Controller - recorder *MockDownloaderMockRecorder -} - -// MockDownloaderMockRecorder is the mock recorder for MockDownloader -type MockDownloaderMockRecorder struct { - mock *MockDownloader -} - -// NewMockDownloader creates a new mock instance -func NewMockDownloader(ctrl *gomock.Controller) *MockDownloader { - mock := &MockDownloader{ctrl: ctrl} - mock.recorder = &MockDownloaderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockDownloader) EXPECT() *MockDownloaderMockRecorder { - return m.recorder -} - -// Download mocks base method -func (m *MockDownloader) Download(arg0 context.Context, arg1 string) (blob.Blob, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Download", arg0, arg1) - ret0, _ := ret[0].(blob.Blob) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Download indicates an expected call of Download -func (mr *MockDownloaderMockRecorder) Download(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Download", reflect.TypeOf((*MockDownloader)(nil).Download), arg0, arg1) -} diff --git a/testmocks/mock_registry_resolver.go b/testmocks/mock_registry_resolver.go new file mode 100644 index 0000000000..3697c9de0d --- /dev/null +++ b/testmocks/mock_registry_resolver.go @@ -0,0 +1,48 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/buildpacks/pack/pkg/buildpack (interfaces: RegistryResolver) + +// Package testmocks is a generated GoMock package. +package testmocks + +import ( + gomock "github.com/golang/mock/gomock" + reflect "reflect" +) + +// MockRegistryResolver is a mock of RegistryResolver interface +type MockRegistryResolver struct { + ctrl *gomock.Controller + recorder *MockRegistryResolverMockRecorder +} + +// MockRegistryResolverMockRecorder is the mock recorder for MockRegistryResolver +type MockRegistryResolverMockRecorder struct { + mock *MockRegistryResolver +} + +// NewMockRegistryResolver creates a new mock instance +func NewMockRegistryResolver(ctrl *gomock.Controller) *MockRegistryResolver { + mock := &MockRegistryResolver{ctrl: ctrl} + mock.recorder = &MockRegistryResolverMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use +func (m *MockRegistryResolver) EXPECT() *MockRegistryResolverMockRecorder { + return m.recorder +} + +// Resolve mocks base method +func (m *MockRegistryResolver) Resolve(arg0, arg1 string) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Resolve", arg0, arg1) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Resolve indicates an expected call of Resolve +func (mr *MockRegistryResolverMockRecorder) Resolve(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resolve", reflect.TypeOf((*MockRegistryResolver)(nil).Resolve), arg0, arg1) +} From 3b30bada0611a8806ccdf391810cb8bbc189c676 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Thu, 28 Oct 2021 22:00:38 -0500 Subject: [PATCH 05/15] Move pull policy into image package Signed-off-by: Javier Romero --- acceptance/acceptance_test.go | 13 ++-- acceptance/config/asset_manager.go | 2 +- acceptance/config/github_asset_fetcher.go | 2 +- .../builder/fakes/fake_inspectable_fetcher.go | 3 +- internal/builder/inspect.go | 3 +- internal/builder/inspect_test.go | 4 +- internal/commands/build.go | 4 +- internal/commands/build_test.go | 12 ++-- internal/commands/builder_create.go | 6 +- internal/commands/buildpack_package.go | 6 +- internal/commands/buildpack_package_test.go | 10 +-- internal/commands/config_pull_policy.go | 9 ++- internal/commands/create_builder.go | 4 +- internal/commands/package_buildpack.go | 4 +- internal/commands/package_buildpack_test.go | 10 +-- internal/commands/rebase.go | 4 +- internal/commands/rebase_test.go | 12 ++-- internal/fakes/fake_image_fetcher.go | 10 ++- pkg/buildpack/downloader.go | 3 +- pkg/buildpack/downloader_test.go | 37 ++++++----- pkg/client/build.go | 7 +-- pkg/client/build_test.go | 24 ++++---- pkg/client/create_builder.go | 3 +- pkg/client/create_builder_test.go | 31 +++++----- pkg/client/inspect_builder_test.go | 8 +-- pkg/client/inspect_buildpack.go | 3 +- pkg/client/inspect_buildpack_test.go | 13 ++-- pkg/client/inspect_image.go | 3 +- pkg/client/inspect_image_test.go | 15 +++-- pkg/client/package_buildpack.go | 4 +- pkg/client/package_buildpack_test.go | 61 +++++++++---------- pkg/client/pull_buildpack.go | 5 +- pkg/client/pull_buildpack_test.go | 5 +- pkg/client/rebase.go | 3 +- pkg/client/rebase_test.go | 6 +- pkg/client/register_buildpack.go | 3 +- pkg/image/fetcher.go | 7 +-- pkg/image/fetcher_test.go | 33 +++++----- pkg/{config => image}/pull_policy.go | 2 +- pkg/{config => image}/pull_policy_test.go | 28 ++++----- 40 files changed, 199 insertions(+), 223 deletions(-) rename pkg/{config => image}/pull_policy.go (98%) rename pkg/{config => image}/pull_policy_test.go (55%) diff --git a/acceptance/acceptance_test.go b/acceptance/acceptance_test.go index 9f200ccea0..6ba6b69573 100644 --- a/acceptance/acceptance_test.go +++ b/acceptance/acceptance_test.go @@ -33,7 +33,6 @@ import ( "github.com/buildpacks/pack/acceptance/config" "github.com/buildpacks/pack/acceptance/invoke" "github.com/buildpacks/pack/acceptance/managers" - pubcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/internal/cache" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" @@ -306,7 +305,7 @@ func testWithoutSpecificBuilderRequirement( pack.JustRunSuccessfully( "buildpack", "package", packageName, "-c", aggregatePackageToml, - "--pull-policy", pubcfg.PullNever.String()) + "--pull-policy", "never") assertImage.ExistsLocally(packageName) }) @@ -330,7 +329,7 @@ func testWithoutSpecificBuilderRequirement( output, err := pack.Run( "buildpack", "package", packageName, "-c", aggregatePackageToml, - "--pull-policy", pubcfg.PullNever.String(), + "--pull-policy", "never", ) assert.NotNil(err) @@ -2341,7 +2340,7 @@ include = [ "*.jar", "media/mountain.jpg", "/media/person.png", ] "-p", filepath.Join("testdata", "mock_app"), "--builder", builderName, "--run-image", runBefore, - "--pull-policy", pubcfg.PullNever.String(), + "--pull-policy", "never", ) origID = h.ImageID(t, repoName) assertImage.RunsWithOutput( @@ -2378,7 +2377,7 @@ include = [ "*.jar", "media/mountain.jpg", "/media/person.png", ] output := pack.RunSuccessfully( "rebase", repoName, "--run-image", runAfter, - "--pull-policy", pubcfg.PullNever.String(), + "--pull-policy", "never", ) assert.Contains(output, fmt.Sprintf("Successfully rebased image '%s'", repoName)) @@ -2404,7 +2403,7 @@ include = [ "*.jar", "media/mountain.jpg", "/media/person.png", ] }) it("prefers the local mirror", func() { - output := pack.RunSuccessfully("rebase", repoName, "--pull-policy", pubcfg.PullNever.String()) + output := pack.RunSuccessfully("rebase", repoName, "--pull-policy", "never") assertOutput := assertions.NewOutputAssertionManager(t, output) assertOutput.ReportsSelectingRunImageMirrorFromLocalConfig(localRunImageMirror) @@ -2426,7 +2425,7 @@ include = [ "*.jar", "media/mountain.jpg", "/media/person.png", ] }) it("selects the best mirror", func() { - output := pack.RunSuccessfully("rebase", repoName, "--pull-policy", pubcfg.PullNever.String()) + output := pack.RunSuccessfully("rebase", repoName, "--pull-policy", "never") assertOutput := assertions.NewOutputAssertionManager(t, output) assertOutput.ReportsSelectingRunImageMirror(runImageMirror) diff --git a/acceptance/config/asset_manager.go b/acceptance/config/asset_manager.go index 61c3946026..1a02632891 100644 --- a/acceptance/config/asset_manager.go +++ b/acceptance/config/asset_manager.go @@ -12,10 +12,10 @@ import ( "testing" acceptanceOS "github.com/buildpacks/pack/acceptance/os" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/blob" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/acceptance/config/github_asset_fetcher.go b/acceptance/config/github_asset_fetcher.go index 918f4afaf6..0cb67f7f46 100644 --- a/acceptance/config/github_asset_fetcher.go +++ b/acceptance/config/github_asset_fetcher.go @@ -26,8 +26,8 @@ import ( "github.com/pkg/errors" "golang.org/x/oauth2" - "github.com/buildpacks/pack/internal/blob" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/blob" ) const ( diff --git a/internal/builder/fakes/fake_inspectable_fetcher.go b/internal/builder/fakes/fake_inspectable_fetcher.go index 2f7125735b..3c3b65f9c1 100644 --- a/internal/builder/fakes/fake_inspectable_fetcher.go +++ b/internal/builder/fakes/fake_inspectable_fetcher.go @@ -4,7 +4,6 @@ import ( "context" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -16,7 +15,7 @@ type FakeInspectableFetcher struct { ReceivedName string ReceivedDaemon bool - ReceivedPullPolicy config.PullPolicy + ReceivedPullPolicy image.PullPolicy } func (f *FakeInspectableFetcher) Fetch(ctx context.Context, name string, options image.FetchOptions) (builder.Inspectable, error) { diff --git a/internal/builder/inspect.go b/internal/builder/inspect.go index 331a3a4fc7..80af793598 100644 --- a/internal/builder/inspect.go +++ b/internal/builder/inspect.go @@ -8,7 +8,6 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -64,7 +63,7 @@ func NewInspector(fetcher InspectableFetcher, factory LabelManagerFactory, calcu } func (i *Inspector) Inspect(name string, daemon bool, orderDetectionDepth int) (Info, error) { - inspectable, err := i.imageFetcher.Fetch(context.Background(), name, image.FetchOptions{Daemon: daemon, PullPolicy: config.PullNever}) + inspectable, err := i.imageFetcher.Fetch(context.Background(), name, image.FetchOptions{Daemon: daemon, PullPolicy: image.PullNever}) if err != nil { return Info{}, fmt.Errorf("fetching builder image: %w", err) } diff --git a/internal/builder/inspect_test.go b/internal/builder/inspect_test.go index df183ee1a1..9fd9c8bb27 100644 --- a/internal/builder/inspect_test.go +++ b/internal/builder/inspect_test.go @@ -10,7 +10,7 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/fakes" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" "github.com/heroku/color" @@ -164,7 +164,7 @@ func testInspect(t *testing.T, when spec.G, it spec.S) { assert.Equal(fetcher.CallCount, 1) assert.Equal(fetcher.ReceivedName, testBuilderName) assert.Equal(fetcher.ReceivedDaemon, true) - assert.Equal(fetcher.ReceivedPullPolicy, config.PullNever) + assert.Equal(fetcher.ReceivedPullPolicy, image.PullNever) }) it("instantiates a builder label manager with the correct inspectable", func() { diff --git a/internal/commands/build.go b/internal/commands/build.go index 9c78418339..6a7210445f 100644 --- a/internal/commands/build.go +++ b/internal/commands/build.go @@ -14,7 +14,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/project" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) @@ -111,7 +111,7 @@ func Build(logger logging.Logger, cfg config.Config, packClient PackClient) *cob if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - pullPolicy, err := pubcfg.ParsePullPolicy(stringPolicy) + pullPolicy, err := image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrapf(err, "parsing pull policy %s", flags.Policy) } diff --git a/internal/commands/build_test.go b/internal/commands/build_test.go index fdf485aa1f..c6aec94c64 100644 --- a/internal/commands/build_test.go +++ b/internal/commands/build_test.go @@ -22,7 +22,7 @@ import ( "github.com/buildpacks/pack/internal/config" ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -141,7 +141,7 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { when("--pull-policy", func() { it("sets pull-policy=never", func() { mockClient.EXPECT(). - Build(gomock.Any(), EqBuildOptionsWithPullPolicy(pubcfg.PullNever)). + Build(gomock.Any(), EqBuildOptionsWithPullPolicy(image.PullNever)). Return(nil) command.SetArgs([]string{"image", "--builder", "my-builder", "--pull-policy", "never"}) @@ -154,7 +154,7 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { }) it("takes precedence over a configured pull policy", func() { mockClient.EXPECT(). - Build(gomock.Any(), EqBuildOptionsWithPullPolicy(pubcfg.PullNever)). + Build(gomock.Any(), EqBuildOptionsWithPullPolicy(image.PullNever)). Return(nil) cfg := config.Config{PullPolicy: "if-not-present"} @@ -170,7 +170,7 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { when("no pull policy set in config", func() { it("uses the default policy", func() { mockClient.EXPECT(). - Build(gomock.Any(), EqBuildOptionsWithPullPolicy(pubcfg.PullAlways)). + Build(gomock.Any(), EqBuildOptionsWithPullPolicy(image.PullAlways)). Return(nil) command.SetArgs([]string{"image", "--builder", "my-builder"}) @@ -180,7 +180,7 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { when("pull policy is set in config", func() { it("uses the set policy", func() { mockClient.EXPECT(). - Build(gomock.Any(), EqBuildOptionsWithPullPolicy(pubcfg.PullNever)). + Build(gomock.Any(), EqBuildOptionsWithPullPolicy(image.PullNever)). Return(nil) cfg := config.Config{PullPolicy: "never"} @@ -793,7 +793,7 @@ func EqBuildOptionsDefaultProcess(defaultProc string) gomock.Matcher { } } -func EqBuildOptionsWithPullPolicy(policy pubcfg.PullPolicy) gomock.Matcher { +func EqBuildOptionsWithPullPolicy(policy image.PullPolicy) gomock.Matcher { return buildOptionsMatcher{ description: fmt.Sprintf("PullPolicy=%s", policy), equals: func(o client.BuildOptions) bool { diff --git a/internal/commands/builder_create.go b/internal/commands/builder_create.go index 488868b6db..7d79bda4d8 100644 --- a/internal/commands/builder_create.go +++ b/internal/commands/builder_create.go @@ -12,7 +12,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // BuilderCreateFlags define flags provided to the CreateBuilder command @@ -47,7 +47,7 @@ Creating a custom builder allows you to control what buildpacks are used and wha if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - pullPolicy, err := pubcfg.ParsePullPolicy(stringPolicy) + pullPolicy, err := image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrapf(err, "parsing pull policy %s", flags.Policy) } @@ -95,7 +95,7 @@ Creating a custom builder allows you to control what buildpacks are used and wha } func validateCreateFlags(flags *BuilderCreateFlags, cfg config.Config) error { - if flags.Publish && flags.Policy == pubcfg.PullNever.String() { + if flags.Publish && flags.Policy == image.PullNever.String() { return errors.Errorf("--publish and --pull-policy never cannot be used together. The --publish flag requires the use of remote images.") } diff --git a/internal/commands/buildpack_package.go b/internal/commands/buildpack_package.go index cb162de91d..573576f528 100644 --- a/internal/commands/buildpack_package.go +++ b/internal/commands/buildpack_package.go @@ -12,7 +12,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // BuildpackPackageFlags define flags provided to the BuildpackPackage command @@ -58,7 +58,7 @@ func BuildpackPackage(logger logging.Logger, cfg config.Config, packager Buildpa if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - pullPolicy, err := pubcfg.ParsePullPolicy(stringPolicy) + pullPolicy, err := image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrap(err, "parsing pull policy") } @@ -126,7 +126,7 @@ func BuildpackPackage(logger logging.Logger, cfg config.Config, packager Buildpa } func validateBuildpackPackageFlags(p *BuildpackPackageFlags) error { - if p.Publish && p.Policy == pubcfg.PullNever.String() { + if p.Publish && p.Policy == image.PullNever.String() { return errors.Errorf("--publish and --pull-policy never cannot be used together. The --publish flag requires the use of remote images.") } if p.PackageTomlPath != "" && p.Path != "" { diff --git a/internal/commands/buildpack_package_test.go b/internal/commands/buildpack_package_test.go index 393c450cde..89f5dc856d 100644 --- a/internal/commands/buildpack_package_test.go +++ b/internal/commands/buildpack_package_test.go @@ -18,7 +18,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -151,7 +151,7 @@ func testPackageCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, cmd.Execute()) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullNever) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullNever) }) it("pull-policy=always sets policy", func() { @@ -160,7 +160,7 @@ func testPackageCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, cmd.Execute()) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullAlways) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullAlways) }) }) when("no --pull-policy", func() { @@ -175,7 +175,7 @@ func testPackageCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, cmd.Execute()) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullAlways) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullAlways) }) it("uses the configured pull policy when policy configured", func() { cmd := packageCommand( @@ -192,7 +192,7 @@ func testPackageCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullNever) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullNever) }) }) }) diff --git a/internal/commands/config_pull_policy.go b/internal/commands/config_pull_policy.go index 17db5af955..fa0d5413fa 100644 --- a/internal/commands/config_pull_policy.go +++ b/internal/commands/config_pull_policy.go @@ -6,11 +6,10 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - pubcfg "github.com/buildpacks/pack/pkg/config" - "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/image" ) func ConfigPullPolicy(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { @@ -37,7 +36,7 @@ func ConfigPullPolicy(logger logging.Logger, cfg config.Config, cfgPath string) return errors.Wrapf(err, "writing config to %s", cfgPath) } - pullPolicy, err := pubcfg.ParsePullPolicy(cfg.PullPolicy) + pullPolicy, err := image.ParsePullPolicy(cfg.PullPolicy) if err != nil { return err } @@ -45,7 +44,7 @@ func ConfigPullPolicy(logger logging.Logger, cfg config.Config, cfgPath string) logger.Infof("Successfully unset pull policy %s", style.Symbol(oldPullPolicy)) logger.Infof("Pull policy has been set to %s", style.Symbol(pullPolicy.String())) case len(args) == 0: // list - pullPolicy, err := pubcfg.ParsePullPolicy(cfg.PullPolicy) + pullPolicy, err := image.ParsePullPolicy(cfg.PullPolicy) if err != nil { return err } @@ -59,7 +58,7 @@ func ConfigPullPolicy(logger logging.Logger, cfg config.Config, cfgPath string) return nil } - pullPolicy, err := pubcfg.ParsePullPolicy(newPullPolicy) + pullPolicy, err := image.ParsePullPolicy(newPullPolicy) if err != nil { return err } diff --git a/internal/commands/create_builder.go b/internal/commands/create_builder.go index 6887502b69..8bb0248dc9 100644 --- a/internal/commands/create_builder.go +++ b/internal/commands/create_builder.go @@ -12,7 +12,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // Deprecated: Use 'builder create' instead. @@ -43,7 +43,7 @@ Creating a custom builder allows you to control what buildpacks are used and wha if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - pullPolicy, err := pubcfg.ParsePullPolicy(stringPolicy) + pullPolicy, err := image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrapf(err, "parsing pull policy %s", flags.Policy) } diff --git a/internal/commands/package_buildpack.go b/internal/commands/package_buildpack.go index ea179f2088..013962d5c2 100644 --- a/internal/commands/package_buildpack.go +++ b/internal/commands/package_buildpack.go @@ -11,7 +11,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) // Deprecated: use BuildpackPackage instead @@ -41,7 +41,7 @@ func PackageBuildpack(logger logging.Logger, cfg config.Config, packager Buildpa if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - pullPolicy, err := pubcfg.ParsePullPolicy(stringPolicy) + pullPolicy, err := image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrap(err, "parsing pull policy") } diff --git a/internal/commands/package_buildpack_test.go b/internal/commands/package_buildpack_test.go index 9a0877f6ad..26ea17117e 100644 --- a/internal/commands/package_buildpack_test.go +++ b/internal/commands/package_buildpack_test.go @@ -17,7 +17,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/dist" ilogging "github.com/buildpacks/pack/internal/logging" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -116,7 +116,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullNever) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullNever) }) it("pull-policy=always sets policy", func() { @@ -127,7 +127,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) receivedOptions := fakeBuildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullAlways) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullAlways) }) it("takes precedence over a configured pull policy", func() { logger := ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) @@ -147,7 +147,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) receivedOptions := buildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullNever) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullNever) }) }) when("configured pull policy", func() { @@ -167,7 +167,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) receivedOptions := buildpackPackager.CreateCalledWithOptions - h.AssertEq(t, receivedOptions.PullPolicy, pubcfg.PullNever) + h.AssertEq(t, receivedOptions.PullPolicy, image.PullNever) }) }) }) diff --git a/internal/commands/rebase.go b/internal/commands/rebase.go index b1fd3d613e..9912328852 100644 --- a/internal/commands/rebase.go +++ b/internal/commands/rebase.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" @@ -33,7 +33,7 @@ func Rebase(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Co if stringPolicy == "" { stringPolicy = cfg.PullPolicy } - opts.PullPolicy, err = pubcfg.ParsePullPolicy(stringPolicy) + opts.PullPolicy, err = image.ParsePullPolicy(stringPolicy) if err != nil { return errors.Wrapf(err, "parsing pull policy %s", stringPolicy) } diff --git a/internal/commands/rebase_test.go b/internal/commands/rebase_test.go index bdc7451040..3a4e1fbcb0 100644 --- a/internal/commands/rebase_test.go +++ b/internal/commands/rebase_test.go @@ -7,7 +7,7 @@ import ( "github.com/heroku/color" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" "github.com/golang/mock/gomock" "github.com/sclevine/spec" @@ -76,7 +76,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { opts = client.RebaseOptions{ RepoName: repoName, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, RunImage: "", AdditionalMirrors: map[string][]string{ runImage: {testMirror1, testMirror2}, @@ -95,7 +95,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { when("--pull-policy never", func() { it("works", func() { - opts.PullPolicy = pubcfg.PullNever + opts.PullPolicy = image.PullNever mockClient.EXPECT(). Rebase(gomock.Any(), opts). Return(nil) @@ -104,7 +104,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, command.Execute()) }) it("takes precedence over config policy", func() { - opts.PullPolicy = pubcfg.PullNever + opts.PullPolicy = image.PullNever mockClient.EXPECT(). Rebase(gomock.Any(), opts). Return(nil) @@ -126,7 +126,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { when("--pull-policy not set", func() { when("no policy set in config", func() { it("uses the default policy", func() { - opts.PullPolicy = pubcfg.PullAlways + opts.PullPolicy = image.PullAlways mockClient.EXPECT(). Rebase(gomock.Any(), opts). Return(nil) @@ -137,7 +137,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { }) when("policy is set in config", func() { it("uses set policy", func() { - opts.PullPolicy = pubcfg.PullIfNotPresent + opts.PullPolicy = image.PullIfNotPresent mockClient.EXPECT(). Rebase(gomock.Any(), opts). Return(nil) diff --git a/internal/fakes/fake_image_fetcher.go b/internal/fakes/fake_image_fetcher.go index 26476e5d15..c0a331f616 100644 --- a/internal/fakes/fake_image_fetcher.go +++ b/internal/fakes/fake_image_fetcher.go @@ -3,8 +3,6 @@ package fakes import ( "context" - "github.com/buildpacks/pack/pkg/config" - "github.com/buildpacks/imgutil" "github.com/pkg/errors" @@ -13,7 +11,7 @@ import ( type FetchArgs struct { Daemon bool - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy Platform string } @@ -56,10 +54,10 @@ func (f *FakeImageFetcher) Fetch(ctx context.Context, name string, options image return ri, nil } -func shouldPull(localFound, remoteFound bool, policy config.PullPolicy) bool { - if remoteFound && !localFound && policy == config.PullIfNotPresent { +func shouldPull(localFound, remoteFound bool, policy image.PullPolicy) bool { + if remoteFound && !localFound && policy == image.PullIfNotPresent { return true } - return remoteFound && policy == config.PullAlways + return remoteFound && policy == image.PullAlways } diff --git a/pkg/buildpack/downloader.go b/pkg/buildpack/downloader.go index dd7adee018..1e19308be7 100644 --- a/pkg/buildpack/downloader.go +++ b/pkg/buildpack/downloader.go @@ -15,7 +15,6 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -64,7 +63,7 @@ type DownloadOptions struct { Daemon bool - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy } func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, opts DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { diff --git a/pkg/buildpack/downloader_test.go b/pkg/buildpack/downloader_test.go index 1f0566ab9f..21c36ba74c 100644 --- a/pkg/buildpack/downloader_test.go +++ b/pkg/buildpack/downloader_test.go @@ -27,8 +27,7 @@ import ( "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack/pkg/config" - image "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -130,7 +129,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { buildpackDownloadOptions = buildpack.DownloadOptions{ImageOS: "linux"} ) - shouldFetchPackageImageWith := func(demon bool, pull config.PullPolicy) { + shouldFetchPackageImageWith := func(demon bool, pull image.PullPolicy) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: demon, PullPolicy: pull}).Return(packageImage, nil) } @@ -145,10 +144,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { RegistryName: "some-registry", ImageOS: "linux", Daemon: true, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } - shouldFetchPackageImageWith(true, config.PullAlways) + shouldFetchPackageImageWith(true, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "urn:cnb:registry:example/foo@1.1.0", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -161,10 +160,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { RegistryName: "some-registry", ImageOS: "linux", Daemon: true, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } - shouldFetchPackageImageWith(true, config.PullAlways) + shouldFetchPackageImageWith(true, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "example/foo@1.1.0", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -186,12 +185,12 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { packageImage = createPackage("some/package:tag") buildpackDownloadOptions = buildpack.DownloadOptions{ Daemon: true, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, ImageOS: "linux", ImageName: "some/package:tag", } - shouldFetchPackageImageWith(true, config.PullAlways) + shouldFetchPackageImageWith(true, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -204,10 +203,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } - shouldFetchPackageImageWith(true, config.PullAlways) + shouldFetchPackageImageWith(true, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -220,10 +219,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } - shouldFetchPackageImageWith(false, config.PullAlways) + shouldFetchPackageImageWith(false, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -235,9 +234,9 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { buildpackDownloadOptions = buildpack.DownloadOptions{ ImageOS: "linux", Daemon: false, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } - shouldFetchPackageImageWith(false, config.PullAlways) + shouldFetchPackageImageWith(false, image.PullAlways) mainBP, _, err := buildpackDownloader.Download(context.TODO(), packageImage.Name(), buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -250,10 +249,10 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { ImageOS: "linux", ImageName: packageImage.Name(), Daemon: false, - PullPolicy: config.PullNever, + PullPolicy: image.PullNever, } - shouldFetchPackageImageWith(false, config.PullNever) + shouldFetchPackageImageWith(false, image.PullNever) mainBP, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "example/foo") @@ -266,7 +265,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { ImageOS: "linux", ImageName: packageImage.Name(), Daemon: true, - PullPolicy: config.PullNever, + PullPolicy: image.PullNever, } prepareFetcherWithMissingPackageImage() _, _, err := buildpackDownloader.Download(context.TODO(), "", buildpackDownloadOptions) @@ -340,7 +339,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { when("can't download image from registry", func() { it("errors", func() { packageImage := fakes.NewImage("example.com/some/package@sha256:74eb48882e835d8767f62940d453eb96ed2737de3a16573881dcea7dea769df7", "", nil) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}).Return(nil, errors.New("failed to pull")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}).Return(nil, errors.New("failed to pull")) buildpackDownloadOptions.RegistryName = "some-registry" _, _, err := buildpackDownloader.Download(context.TODO(), "urn:cnb:registry:example/foo@1.1.0", buildpackDownloadOptions) diff --git a/pkg/client/build.go b/pkg/client/build.go index 7fb8db97f1..604a9d26b7 100644 --- a/pkg/client/build.go +++ b/pkg/client/build.go @@ -34,7 +34,6 @@ import ( "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/buildpack" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) @@ -143,7 +142,7 @@ type BuildOptions struct { DefaultProcessType string // Strategy for updating local images before a build. - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy // ProjectDescriptorBaseDir is the base directory to find relative resources referenced by the ProjectDescriptor ProjectDescriptorBaseDir string @@ -470,7 +469,7 @@ func (c *Client) getBuilder(img imgutil.Image) (*builder.Builder, error) { return bldr, nil } -func (c *Client) validateRunImage(context context.Context, name string, pullPolicy config.PullPolicy, publish bool, expectedStack string) (imgutil.Image, error) { +func (c *Client) validateRunImage(context context.Context, name string, pullPolicy image.PullPolicy, publish bool, expectedStack string) (imgutil.Image, error) { if name == "" { return nil, errors.New("run image must be specified") } @@ -856,7 +855,7 @@ func (c *Client) logImageNameAndSha(ctx context.Context, publish bool, imageRef return nil } - img, err := c.imageFetcher.Fetch(ctx, imageRef.Name(), image.FetchOptions{Daemon: !publish, PullPolicy: config.PullNever}) + img, err := c.imageFetcher.Fetch(ctx, imageRef.Name(), image.FetchOptions{Daemon: !publish, PullPolicy: image.PullNever}) if err != nil { return errors.Wrap(err, "fetching built image") } diff --git a/pkg/client/build_test.go b/pkg/client/build_test.go index 9637a378ee..a595a2158f 100644 --- a/pkg/client/build_test.go +++ b/pkg/client/build_test.go @@ -43,7 +43,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" - "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -1667,7 +1667,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { args := fakeImageFetcher.FetchCalls[fakeLifecycleImage.Name()] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) h.AssertEq(t, args.Platform, "linux/amd64") }) }) @@ -1730,11 +1730,11 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { args := fakeImageFetcher.FetchCalls["default/run"] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) args = fakeImageFetcher.FetchCalls[defaultBuilderName] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) }) when("builder is untrusted", func() { @@ -1751,7 +1751,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { args := fakeImageFetcher.FetchCalls[fakeLifecycleImage.Name()] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) h.AssertEq(t, args.Platform, "linux/amd64") }) @@ -1822,20 +1822,20 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, subject.Build(context.TODO(), BuildOptions{ Image: "some/app", Builder: defaultBuilderName, - PullPolicy: config.PullNever, + PullPolicy: image.PullNever, })) args := fakeImageFetcher.FetchCalls["default/run"] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullNever) + h.AssertEq(t, args.PullPolicy, image.PullNever) args = fakeImageFetcher.FetchCalls[defaultBuilderName] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullNever) + h.AssertEq(t, args.PullPolicy, image.PullNever) args = fakeImageFetcher.FetchCalls["buildpacksio/lifecycle:0.11.3"] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullNever) + h.AssertEq(t, args.PullPolicy, image.PullNever) h.AssertEq(t, args.Platform, "linux/amd64") }) }) @@ -1845,16 +1845,16 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, subject.Build(context.TODO(), BuildOptions{ Image: "some/app", Builder: defaultBuilderName, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, })) args := fakeImageFetcher.FetchCalls["default/run"] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) args = fakeImageFetcher.FetchCalls[defaultBuilderName] h.AssertEq(t, args.Daemon, true) - h.AssertEq(t, args.PullPolicy, config.PullAlways) + h.AssertEq(t, args.PullPolicy, image.PullAlways) }) }) }) diff --git a/pkg/client/create_builder.go b/pkg/client/create_builder.go index 39a00fabbf..bcdc2e5074 100644 --- a/pkg/client/create_builder.go +++ b/pkg/client/create_builder.go @@ -14,7 +14,6 @@ import ( "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/buildpack" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -38,7 +37,7 @@ type CreateBuilderOptions struct { Registry string // Strategy for updating images before a build. - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy } // CreateBuilder creates and saves a builder image to a registry with the provided options. diff --git a/pkg/client/create_builder_test.go b/pkg/client/create_builder_test.go index 40732f0615..b63bde836f 100644 --- a/pkg/client/create_builder_test.go +++ b/pkg/client/create_builder_test.go @@ -32,7 +32,6 @@ import ( "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" @@ -159,7 +158,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { Lifecycle: pubbldr.LifecycleConfig{URI: "file:///some-lifecycle"}, }, Publish: false, - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, } tmpDir, err = ioutil.TempDir("", "create-builder-test") @@ -194,7 +193,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }) it("should fail when the stack ID from the builder config does not match the stack ID from the build image", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(fakeBuildImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(fakeBuildImage, nil) h.AssertNil(t, fakeBuildImage.SetLabel("io.buildpacks.stack.id", "other.stack.id")) prepareFetcherWithRunImages() @@ -282,13 +281,13 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }) it("should warn when the run image cannot be found", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(fakeBuildImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(fakeBuildImage, nil) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "localhost:5000/some/run-image", image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "localhost:5000/some/run-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "localhost:5000/some/run-image", image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "localhost:5000/some/run-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nil, errors.Wrap(image.ErrNotFound, "yikes")) err := subject.CreateBuilder(context.TODO(), opts) h.AssertNil(t, err) @@ -297,14 +296,14 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }) it("should fail when not publish and the run image cannot be fetched", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(nil, errors.New("yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nil, errors.New("yikes")) err := subject.CreateBuilder(context.TODO(), opts) h.AssertError(t, err, "failed to fetch image: yikes") }) it("should fail when publish and the run image cannot be fetched", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}).Return(nil, errors.New("yikes")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/run-image", image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}).Return(nil, errors.New("yikes")) opts.Publish = true err := subject.CreateBuilder(context.TODO(), opts) @@ -343,7 +342,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { when("build image not found", func() { it("should fail", func() { prepareFetcherWithRunImages() - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(nil, image.ErrNotFound) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nil, image.ErrNotFound) err := subject.CreateBuilder(context.TODO(), opts) h.AssertError(t, err, "fetch build image: not found") @@ -355,7 +354,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { fakeImage := fakeBadImageStruct{} prepareFetcherWithRunImages() - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(fakeImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(fakeImage, nil) err := subject.CreateBuilder(context.TODO(), opts) h.AssertError(t, err, "failed to create builder: invalid build-image") @@ -377,7 +376,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { prepareFetcherWithRunImages() h.AssertNil(t, fakeBuildImage.SetOS("windows")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(fakeBuildImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(fakeBuildImage, nil) err = packClientWithExperimental.CreateBuilder(context.TODO(), opts) h.AssertNil(t, err) @@ -389,7 +388,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { prepareFetcherWithRunImages() h.AssertNil(t, fakeBuildImage.SetOS("windows")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(fakeBuildImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(fakeBuildImage, nil) err := subject.CreateBuilder(context.TODO(), opts) h.AssertError(t, err, "failed to create builder: Windows containers support is currently experimental.") @@ -712,7 +711,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { prepareFetcherWithRunImages() opts.BuilderName = "some/builder" opts.Publish = false - opts.PullPolicy = config.PullAlways + opts.PullPolicy = image.PullAlways opts.Registry = "some-registry" opts.Config.Buildpacks = append( opts.Config.Buildpacks, @@ -725,7 +724,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { }, ) - shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", buildpack.DownloadOptions{Daemon: true, PullPolicy: config.PullAlways, RegistryName: "some-"}) + shouldCallBuildpackDownloaderWith("urn:cnb:registry:example/foo@1.1.0", buildpack.DownloadOptions{Daemon: true, PullPolicy: image.PullAlways, RegistryName: "some-"}) h.AssertNil(t, subject.CreateBuilder(context.TODO(), opts)) }) }) diff --git a/pkg/client/inspect_builder_test.go b/pkg/client/inspect_builder_test.go index 4e175846dc..8e141a7b7d 100644 --- a/pkg/client/inspect_builder_test.go +++ b/pkg/client/inspect_builder_test.go @@ -7,8 +7,6 @@ import ( pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/pkg/config" - "github.com/buildpacks/imgutil/fakes" "github.com/buildpacks/lifecycle/api" "github.com/golang/mock/gomock" @@ -71,9 +69,9 @@ func testInspectBuilder(t *testing.T, when spec.G, it spec.S) { when(fmt.Sprintf("daemon is %t", useDaemon), func() { it.Before(func() { if useDaemon { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(builderImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(builderImage, nil) } else { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: false, PullPolicy: config.PullNever}).Return(builderImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: false, PullPolicy: image.PullNever}).Return(builderImage, nil) } }) @@ -406,7 +404,7 @@ func testInspectBuilder(t *testing.T, when spec.G, it spec.S) { it.Before(func() { notFoundImage := fakes.NewImage("", "", nil) notFoundImage.Delete() - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(nil, errors.Wrap(image.ErrNotFound, "some-error")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/builder", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(nil, errors.Wrap(image.ErrNotFound, "some-error")) }) it("return nil metadata", func() { diff --git a/pkg/client/inspect_buildpack.go b/pkg/client/inspect_buildpack.go index 568d9fc2c3..727d3493fa 100644 --- a/pkg/client/inspect_buildpack.go +++ b/pkg/client/inspect_buildpack.go @@ -11,7 +11,6 @@ import ( "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -109,7 +108,7 @@ func metadataFromArchive(downloader BlobDownloader, path string) (buildpackMd bu func metadataFromImage(client *Client, name string, daemon bool) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { imageName := buildpack.ParsePackageLocator(name) - img, err := client.imageFetcher.Fetch(context.Background(), imageName, image.FetchOptions{Daemon: daemon, PullPolicy: config.PullNever}) + img, err := client.imageFetcher.Fetch(context.Background(), imageName, image.FetchOptions{Daemon: daemon, PullPolicy: image.PullNever}) if err != nil { return buildpackage.Metadata{}, dist.BuildpackLayers{}, err } diff --git a/pkg/client/inspect_buildpack_test.go b/pkg/client/inspect_buildpack_test.go index 51cd224463..ac6a9cb31a 100644 --- a/pkg/client/inspect_buildpack_test.go +++ b/pkg/client/inspect_buildpack_test.go @@ -28,7 +28,6 @@ import ( "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" @@ -378,7 +377,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch( gomock.Any(), "example.com/some/package@sha256:8c27fe111c11b722081701dfed3bd55e039b9ce92865473cf4cdfa918071c566", - image.FetchOptions{Daemon: false, PullPolicy: config.PullNever}).Return(buildpackImage, nil) + image.FetchOptions{Daemon: false, PullPolicy: image.PullNever}).Return(buildpackImage, nil) }) it.After(func() { @@ -425,9 +424,9 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { it.Before(func() { expectedInfo.Location = buildpack.PackageLocator if useDaemon { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/buildpack", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(buildpackImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/buildpack", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(buildpackImage, nil) } else { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/buildpack", image.FetchOptions{Daemon: false, PullPolicy: config.PullNever}).Return(buildpackImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/buildpack", image.FetchOptions{Daemon: false, PullPolicy: image.PullNever}).Return(buildpackImage, nil) } }) @@ -461,7 +460,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { when("buildpack image", func() { when("unable to fetch buildpack image", func() { it.Before(func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing/buildpack", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(nil, errors.Wrapf(image.ErrNotFound, "big bad error")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing/buildpack", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(nil, errors.Wrapf(image.ErrNotFound, "big bad error")) }) it("returns an ErrNotFound error", func() { inspectOptions := client.InspectBuildpackOptions{ @@ -477,7 +476,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { it.Before(func() { fakeImage := fakes.NewImage("empty", "", nil) h.AssertNil(t, fakeImage.SetLabel(dist.BuildpackLayersLabel, ":::")) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing-metadata/buildpack", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(fakeImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "missing-metadata/buildpack", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(fakeImage, nil) }) it("returns an error", func() { inspectOptions := client.InspectBuildpackOptions{ @@ -599,7 +598,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch( gomock.Any(), "example.com/some/package@sha256:2560f05307e8de9d830f144d09556e19dd1eb7d928aee900ed02208ae9727e7a", - image.FetchOptions{Daemon: false, PullPolicy: config.PullNever}).Return(nil, image.ErrNotFound) + image.FetchOptions{Daemon: false, PullPolicy: image.PullNever}).Return(nil, image.ErrNotFound) }) it("returns an untyped error", func() { registryBuildpack := "urn:cnb:registry:example/foo" diff --git a/pkg/client/inspect_image.go b/pkg/client/inspect_image.go index 4287dbe61f..7566dc265d 100644 --- a/pkg/client/inspect_image.go +++ b/pkg/client/inspect_image.go @@ -11,7 +11,6 @@ import ( "github.com/pkg/errors" "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -86,7 +85,7 @@ const ( // If daemon is true, first the local registry will be searched for the image. // Otherwise it assumes the image is remote. func (c *Client) InspectImage(name string, daemon bool) (*ImageInfo, error) { - img, err := c.imageFetcher.Fetch(context.Background(), name, image.FetchOptions{Daemon: daemon, PullPolicy: config.PullNever}) + img, err := c.imageFetcher.Fetch(context.Background(), name, image.FetchOptions{Daemon: daemon, PullPolicy: image.PullNever}) if err != nil { if errors.Cause(err) == image.ErrNotFound { return nil, nil diff --git a/pkg/client/inspect_image_test.go b/pkg/client/inspect_image_test.go index 296c3d6e5e..e2e723c1f9 100644 --- a/pkg/client/inspect_image_test.go +++ b/pkg/client/inspect_image_test.go @@ -16,7 +16,6 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" @@ -116,9 +115,9 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { when(fmt.Sprintf("daemon is %t", useDaemon), func() { it.Before(func() { if useDaemon { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/image", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(mockImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/image", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(mockImage, nil) } else { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/image", image.FetchOptions{Daemon: false, PullPolicy: config.PullNever}).Return(mockImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/image", image.FetchOptions{Daemon: false, PullPolicy: image.PullNever}).Return(mockImage, nil) } }) @@ -538,7 +537,7 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { when("the image doesn't exist", func() { it("returns nil", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "not/some-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(nil, image.ErrNotFound) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "not/some-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(nil, image.ErrNotFound) info, err := subject.InspectImage("not/some-image", true) h.AssertNil(t, err) @@ -548,7 +547,7 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { when("there is an error fetching the image", func() { it("returns the error", func() { - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "not/some-image", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(nil, errors.New("some-error")) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "not/some-image", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(nil, errors.New("some-error")) _, err := subject.InspectImage("not/some-image", true) h.AssertError(t, err, "some-error") @@ -558,7 +557,7 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { when("the image is missing labels", func() { it("returns empty data", func() { mockImageFetcher.EXPECT(). - Fetch(gomock.Any(), "missing/labels", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}). + Fetch(gomock.Any(), "missing/labels", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}). Return(fakes.NewImage("missing/labels", "", nil), nil) info, err := subject.InspectImage("missing/labels", true) h.AssertNil(t, err) @@ -572,7 +571,7 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { it.Before(func() { badImage = fakes.NewImage("bad/image", "", nil) mockImageFetcher.EXPECT(). - Fetch(gomock.Any(), "bad/image", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}). + Fetch(gomock.Any(), "bad/image", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}). Return(badImage, nil) }) @@ -592,7 +591,7 @@ func testInspectImage(t *testing.T, when spec.G, it spec.S) { when("lifecycle version is 0.4.x or earlier", func() { it("includes an empty base image reference", func() { oldImage := fakes.NewImage("old/image", "", nil) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), "old/image", image.FetchOptions{Daemon: true, PullPolicy: config.PullNever}).Return(oldImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), "old/image", image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}).Return(oldImage, nil) h.AssertNil(t, oldImage.SetLabel( "io.buildpacks.lifecycle.metadata", diff --git a/pkg/client/package_buildpack.go b/pkg/client/package_buildpack.go index f68c61b878..b57ddc1fc9 100644 --- a/pkg/client/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -13,7 +13,7 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" - "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" ) const ( @@ -47,7 +47,7 @@ type PackageBuildpackOptions struct { Publish bool // Strategy for updating images before packaging. - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy // Name of the buildpack registry. Used to // add buildpacks to a package. diff --git a/pkg/client/package_buildpack_test.go b/pkg/client/package_buildpack_test.go index 39847e5085..7744854682 100644 --- a/pkg/client/package_buildpack_test.go +++ b/pkg/client/package_buildpack_test.go @@ -27,7 +27,6 @@ import ( "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/client" - pubcfg "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" @@ -158,7 +157,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: dependencyPath}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, }) h.AssertError(t, err, "inspecting buildpack blob") @@ -199,7 +198,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Stacks: []dist.Stack{{ID: "some.stack.id"}}, })}, }, - PullPolicy: pubcfg.PullNever, + PullPolicy: image.PullNever, })) } }) @@ -265,15 +264,15 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { })}, }, Publish: true, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, })) }) - shouldFetchNestedPackage := func(demon bool, pull pubcfg.PullPolicy) { + shouldFetchNestedPackage := func(demon bool, pull image.PullPolicy) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: demon, PullPolicy: pull}).Return(nestedPackage, nil) } - shouldNotFindNestedPackageWhenCallingImageFetcherWith := func(demon bool, pull pubcfg.PullPolicy) { + shouldNotFindNestedPackageWhenCallingImageFetcherWith := func(demon bool, pull image.PullPolicy) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: demon, PullPolicy: pull}).Return(nil, image.ErrNotFound) } @@ -291,7 +290,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { when("publish=false and pull-policy=always", func() { it("should pull and use local nested package image", func() { - shouldFetchNestedPackage(true, pubcfg.PullAlways) + shouldFetchNestedPackage(true, image.PullAlways) packageImage := shouldCreateLocalPackage() h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ @@ -311,14 +310,14 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: nestedPackage.Name()}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, })) }) }) when("publish=true and pull-policy=always", func() { it("should use remote nested package image", func() { - shouldFetchNestedPackage(false, pubcfg.PullAlways) + shouldFetchNestedPackage(false, image.PullAlways) packageImage := shouldCreateRemotePackage() h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ @@ -338,14 +337,14 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: nestedPackage.Name()}}}, }, Publish: true, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, })) }) }) when("publish=true and pull-policy=never", func() { it("should push to registry and not pull nested package image", func() { - shouldFetchNestedPackage(false, pubcfg.PullNever) + shouldFetchNestedPackage(false, image.PullNever) packageImage := shouldCreateRemotePackage() h.AssertNil(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ @@ -365,14 +364,14 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: nestedPackage.Name()}}}, }, Publish: true, - PullPolicy: pubcfg.PullNever, + PullPolicy: image.PullNever, })) }) }) when("publish=false pull-policy=never and there is no local image", func() { it("should fail without trying to retrieve nested image from registry", func() { - shouldNotFindNestedPackageWhenCallingImageFetcherWith(true, pubcfg.PullNever) + shouldNotFindNestedPackageWhenCallingImageFetcherWith(true, image.PullNever) h.AssertError(t, subject.PackageBuildpack(context.TODO(), client.PackageBuildpackOptions{ Name: "some/package", @@ -386,7 +385,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: nestedPackage.Name()}}}, }, Publish: false, - PullPolicy: pubcfg.PullNever, + PullPolicy: image.PullNever, }), "not found") }) }) @@ -395,7 +394,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { when("nested package is not a valid package", func() { it("should error", func() { notPackageImage := fakes.NewImage("not/package", "", nil) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), notPackageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}).Return(notPackageImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), notPackageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(notPackageImage, nil) mockDockerClient.EXPECT().Info(context.TODO()).Return(types.Info{OSType: "linux"}, nil).AnyTimes() @@ -411,7 +410,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: notPackageImage.Name()}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, }), "extracting buildpacks from 'not/package': could not find label 'io.buildpacks.buildpackage.metadata'") }) }) @@ -452,7 +451,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Stacks: []dist.Stack{{ID: "some.stack.id"}}, })}, }, - PullPolicy: pubcfg.PullNever, + PullPolicy: image.PullNever, })) } }) @@ -505,10 +504,10 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Buildpack: dist.BuildpackURI{URI: createBuildpack(childDescriptor)}, }, Publish: true, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, })) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}).Return(nestedPackage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nestedPackage, nil) }) it("should pull and use local nested package image", func() { @@ -522,7 +521,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{ImageRef: dist.ImageRef{ImageName: nestedPackage.Name()}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, })) @@ -542,7 +541,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: createBuildpack(childDescriptor)}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, })) @@ -564,7 +563,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: bpURL}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, }) h.AssertError(t, err, "downloading buildpack") @@ -587,7 +586,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: bpURL}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, }) h.AssertError(t, err, "packaging dependencies") @@ -620,10 +619,10 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Buildpack: dist.BuildpackURI{URI: createBuildpack(childDescriptor)}, }, Publish: true, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, })) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}).Return(nestedPackage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), nestedPackage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(nestedPackage, nil) }) it("should include both of them", func() { @@ -638,7 +637,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { {BuildpackURI: dist.BuildpackURI{URI: createBuildpack(secondChildDescriptor)}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, })) @@ -661,7 +660,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Platform: dist.Platform{OS: "linux"}, Buildpack: dist.BuildpackURI{URI: createBuildpack(childDescriptor)}, }, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, })) @@ -679,7 +678,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: dependencyPackagePath}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, })) @@ -731,7 +730,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { h.AssertNil(t, err) err = packageImage.SetLabel("io.buildpacks.buildpack.layers", `{"example/foo":{"1.1.0":{"api": "0.2", "layerDiffID":"sha256:xxx", "stacks":[{"id":"some.stack.id"}]}}}`) h.AssertNil(t, err) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}).Return(packageImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(packageImage, nil) packHome := filepath.Join(tmpDir, "packHome") h.AssertNil(t, os.Setenv("PACK_HOME", packHome)) @@ -764,7 +763,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { Dependencies: []dist.ImageOrURI{{BuildpackURI: dist.BuildpackURI{URI: "urn:cnb:registry:example/foo@1.1.0"}}}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, Format: client.FormatFile, Registry: "some-registry", })) @@ -791,7 +790,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { })}, }, Publish: false, - PullPolicy: pubcfg.PullAlways, + PullPolicy: image.PullAlways, }) h.AssertError(t, err, "unknown format: 'invalid-format'") }) diff --git a/pkg/client/pull_buildpack.go b/pkg/client/pull_buildpack.go index ff9e5feaa2..868ab16d27 100644 --- a/pkg/client/pull_buildpack.go +++ b/pkg/client/pull_buildpack.go @@ -9,7 +9,6 @@ import ( "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -35,7 +34,7 @@ func (c *Client) PullBuildpack(ctx context.Context, opts PullBuildpackOptions) e imageName := buildpack.ParsePackageLocator(opts.URI) c.logger.Debugf("Pulling buildpack from image: %s", imageName) - _, err = c.imageFetcher.Fetch(ctx, imageName, image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}) + _, err = c.imageFetcher.Fetch(ctx, imageName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) if err != nil { return errors.Wrapf(err, "fetching image %s", style.Symbol(opts.URI)) } @@ -52,7 +51,7 @@ func (c *Client) PullBuildpack(ctx context.Context, opts PullBuildpackOptions) e return errors.Wrapf(err, "locating in registry %s", style.Symbol(opts.URI)) } - _, err = c.imageFetcher.Fetch(ctx, registryBp.Address, image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}) + _, err = c.imageFetcher.Fetch(ctx, registryBp.Address, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) if err != nil { return errors.Wrapf(err, "fetching image %s", style.Symbol(opts.URI)) } diff --git a/pkg/client/pull_buildpack_test.go b/pkg/client/pull_buildpack_test.go index a56ad08bcc..a62707ecee 100644 --- a/pkg/client/pull_buildpack_test.go +++ b/pkg/client/pull_buildpack_test.go @@ -18,7 +18,6 @@ import ( "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" @@ -92,7 +91,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { packageImage := fakes.NewImage("example.com/some/package:1.0.0", "", nil) h.AssertNil(t, packageImage.SetLabel("io.buildpacks.buildpackage.metadata", `{}`)) h.AssertNil(t, packageImage.SetLabel("io.buildpacks.buildpack.layers", `{}`)) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(packageImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(packageImage, nil) h.AssertNil(t, subject.PullBuildpack(context.TODO(), client.PullBuildpackOptions{ URI: "example.com/some/package:1.0.0", @@ -122,7 +121,7 @@ func testPullBuildpack(t *testing.T, when spec.G, it spec.S) { packageImage := fakes.NewImage("example.com/some/package@sha256:74eb48882e835d8767f62940d453eb96ed2737de3a16573881dcea7dea769df7", "", nil) packageImage.SetLabel("io.buildpacks.buildpackage.metadata", `{}`) packageImage.SetLabel("io.buildpacks.buildpack.layers", `{}`) - mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: config.PullAlways}).Return(packageImage, nil) + mockImageFetcher.EXPECT().Fetch(gomock.Any(), packageImage.Name(), image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}).Return(packageImage, nil) packHome := filepath.Join(tmpDir, "packHome") h.AssertNil(t, os.Setenv("PACK_HOME", packHome)) diff --git a/pkg/client/rebase.go b/pkg/client/rebase.go index 5e5e379aec..3eb0b3680a 100644 --- a/pkg/client/rebase.go +++ b/pkg/client/rebase.go @@ -11,7 +11,6 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -24,7 +23,7 @@ type RebaseOptions struct { Publish bool // Strategy for pulling images during rebase. - PullPolicy config.PullPolicy + PullPolicy image.PullPolicy // Image to rebase against. This image must have // the same StackID as the previous run image. diff --git a/pkg/client/rebase_test.go b/pkg/client/rebase_test.go index 9d8119b4ef..103242e1b4 100644 --- a/pkg/client/rebase_test.go +++ b/pkg/client/rebase_test.go @@ -12,7 +12,7 @@ import ( ifakes "github.com/buildpacks/pack/internal/fakes" "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -179,7 +179,7 @@ func testRebase(t *testing.T, when spec.G, it spec.S) { it("updates the local image", func() { h.AssertNil(t, subject.Rebase(context.TODO(), RebaseOptions{ RepoName: "some/app", - PullPolicy: config.PullAlways, + PullPolicy: image.PullAlways, })) h.AssertEq(t, fakeAppImage.Base(), "some/run") lbl, _ := fakeAppImage.Label("io.buildpacks.lifecycle.metadata") @@ -191,7 +191,7 @@ func testRebase(t *testing.T, when spec.G, it spec.S) { it("uses local image", func() { h.AssertNil(t, subject.Rebase(context.TODO(), RebaseOptions{ RepoName: "some/app", - PullPolicy: config.PullNever, + PullPolicy: image.PullNever, })) h.AssertEq(t, fakeAppImage.Base(), "some/run") lbl, _ := fakeAppImage.Label("io.buildpacks.lifecycle.metadata") diff --git a/pkg/client/register_buildpack.go b/pkg/client/register_buildpack.go index 5d015ebe8b..9df1e0c08d 100644 --- a/pkg/client/register_buildpack.go +++ b/pkg/client/register_buildpack.go @@ -10,7 +10,6 @@ import ( "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/registry" - "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" ) @@ -26,7 +25,7 @@ type RegisterBuildpackOptions struct { // RegisterBuildpack updates the Buildpack Registry with to include a new buildpack specified in // the opts argument func (c *Client) RegisterBuildpack(ctx context.Context, opts RegisterBuildpackOptions) error { - appImage, err := c.imageFetcher.Fetch(ctx, opts.ImageName, image.FetchOptions{Daemon: false, PullPolicy: config.PullAlways}) + appImage, err := c.imageFetcher.Fetch(ctx, opts.ImageName, image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}) if err != nil { return err } diff --git a/pkg/image/fetcher.go b/pkg/image/fetcher.go index 2752fb26e4..14f4e71238 100644 --- a/pkg/image/fetcher.go +++ b/pkg/image/fetcher.go @@ -21,7 +21,6 @@ import ( pname "github.com/buildpacks/pack/internal/name" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/logging" - "github.com/buildpacks/pack/pkg/config" ) // FetcherOption is a type of function that mutate settings on the client. @@ -44,7 +43,7 @@ type Fetcher struct { type FetchOptions struct { Daemon bool Platform string - PullPolicy config.PullPolicy + PullPolicy PullPolicy } func NewFetcher(logger logging.Logger, docker client.CommonAPIClient, opts ...FetcherOption) *Fetcher { @@ -73,10 +72,10 @@ func (f *Fetcher) Fetch(ctx context.Context, name string, options FetchOptions) } switch options.PullPolicy { - case config.PullNever: + case PullNever: img, err := f.fetchDaemonImage(name) return img, err - case config.PullIfNotPresent: + case PullIfNotPresent: img, err := f.fetchDaemonImage(name) if err == nil || !errors.Is(err, ErrNotFound) { return img, err diff --git a/pkg/image/fetcher_test.go b/pkg/image/fetcher_test.go index 64873b258b..c7e7b7206b 100644 --- a/pkg/image/fetcher_test.go +++ b/pkg/image/fetcher_test.go @@ -18,7 +18,6 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/logging" - pubcfg "github.com/buildpacks/pack/pkg/config" "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -72,14 +71,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the remote image", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}) h.AssertNil(t, err) }) }) when("there is no remote image", func() { it("returns an error", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: image.PullAlways}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist in registry", repoName)) }) }) @@ -95,14 +94,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the remote image", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: image.PullIfNotPresent}) h.AssertNil(t, err) }) }) when("there is no remote image", func() { it("returns an error", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: false, PullPolicy: image.PullIfNotPresent}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist in registry", repoName)) }) }) @@ -129,14 +128,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullNever}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullNever}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -172,14 +171,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("pull the image and return the local copy", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) h.AssertNil(t, err) h.AssertNotEq(t, output(), "") }) it("doesn't log anything in quiet mode", func() { logger.WantQuiet(true) - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) h.AssertNil(t, err) h.AssertEq(t, output(), "") }) @@ -199,14 +198,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -214,7 +213,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("image platform is specified", func() { it("passes the platform argument to the daemon", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullAlways, Platform: "some-unsupported-platform"}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullAlways, Platform: "some-unsupported-platform"}) h.AssertError(t, err, "unknown operating system or architecture") }) }) @@ -267,7 +266,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullIfNotPresent}) h.AssertNil(t, err) h.AssertNotContains(t, outBuf.String(), "Pulling image") @@ -281,7 +280,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("there is no local image", func() { it("returns the remote image", func() { - fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + fetchedImg, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullIfNotPresent}) h.AssertNil(t, err) fetchedImgLabel, err := fetchedImg.Label(label) @@ -305,14 +304,14 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { }) it("returns the local image", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullIfNotPresent}) h.AssertNil(t, err) }) }) when("there is no local image", func() { it("returns an error", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullIfNotPresent}) h.AssertError(t, err, fmt.Sprintf("image '%s' does not exist on the daemon", repoName)) }) }) @@ -320,7 +319,7 @@ func testFetcher(t *testing.T, when spec.G, it spec.S) { when("image platform is specified", func() { it("passes the platform argument to the daemon", func() { - _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: pubcfg.PullIfNotPresent, Platform: "some-unsupported-platform"}) + _, err := imageFetcher.Fetch(context.TODO(), repoName, image.FetchOptions{Daemon: true, PullPolicy: image.PullIfNotPresent, Platform: "some-unsupported-platform"}) h.AssertError(t, err, "unknown operating system or architecture") }) }) diff --git a/pkg/config/pull_policy.go b/pkg/image/pull_policy.go similarity index 98% rename from pkg/config/pull_policy.go rename to pkg/image/pull_policy.go index f31a911536..f08678ac5a 100644 --- a/pkg/config/pull_policy.go +++ b/pkg/image/pull_policy.go @@ -1,4 +1,4 @@ -package config +package image import ( "github.com/pkg/errors" diff --git a/pkg/config/pull_policy_test.go b/pkg/image/pull_policy_test.go similarity index 55% rename from pkg/config/pull_policy_test.go rename to pkg/image/pull_policy_test.go index 0ff16fc9e1..22cba1174b 100644 --- a/pkg/config/pull_policy_test.go +++ b/pkg/image/pull_policy_test.go @@ -1,4 +1,4 @@ -package config_test +package image_test import ( "testing" @@ -6,7 +6,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/pkg/config" + "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" ) @@ -17,40 +17,40 @@ func TestPullPolicy(t *testing.T) { func testPullPolicy(t *testing.T, when spec.G, it spec.S) { when("#ParsePullPolicy", func() { it("returns PullNever for never", func() { - policy, err := config.ParsePullPolicy("never") + policy, err := image.ParsePullPolicy("never") h.AssertNil(t, err) - h.AssertEq(t, policy, config.PullNever) + h.AssertEq(t, policy, image.PullNever) }) it("returns PullAlways for always", func() { - policy, err := config.ParsePullPolicy("always") + policy, err := image.ParsePullPolicy("always") h.AssertNil(t, err) - h.AssertEq(t, policy, config.PullAlways) + h.AssertEq(t, policy, image.PullAlways) }) it("returns PullIfNotPresent for if-not-present", func() { - policy, err := config.ParsePullPolicy("if-not-present") + policy, err := image.ParsePullPolicy("if-not-present") h.AssertNil(t, err) - h.AssertEq(t, policy, config.PullIfNotPresent) + h.AssertEq(t, policy, image.PullIfNotPresent) }) it("defaults to PullAlways, if empty string", func() { - policy, err := config.ParsePullPolicy("") + policy, err := image.ParsePullPolicy("") h.AssertNil(t, err) - h.AssertEq(t, policy, config.PullAlways) + h.AssertEq(t, policy, image.PullAlways) }) it("returns error for unknown string", func() { - _, err := config.ParsePullPolicy("fake-policy-here") + _, err := image.ParsePullPolicy("fake-policy-here") h.AssertError(t, err, "invalid pull policy") }) }) when("#String", func() { it("returns the right String value", func() { - h.AssertEq(t, config.PullAlways.String(), "always") - h.AssertEq(t, config.PullNever.String(), "never") - h.AssertEq(t, config.PullIfNotPresent.String(), "if-not-present") + h.AssertEq(t, image.PullAlways.String(), "always") + h.AssertEq(t, image.PullNever.String(), "never") + h.AssertEq(t, image.PullIfNotPresent.String(), "if-not-present") }) }) } From c20ff8f68812b98d2f883154906fbb6f53974551 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Thu, 28 Oct 2021 22:15:47 -0500 Subject: [PATCH 06/15] Verify issue #1245 is resolved by example Signed-off-by: Javier Romero --- pkg/client/example_fetcher_test.go | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 pkg/client/example_fetcher_test.go diff --git a/pkg/client/example_fetcher_test.go b/pkg/client/example_fetcher_test.go new file mode 100644 index 0000000000..26adb6fa5e --- /dev/null +++ b/pkg/client/example_fetcher_test.go @@ -0,0 +1,51 @@ +package client_test + +import ( + "context" + "errors" + "fmt" + "path/filepath" + + "github.com/buildpacks/imgutil" + "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/image" +) + +// This example shows how to replace the image fetcher component +func Example_fetcher() { + // create a context object + context := context.Background() + + // initialize a pack client + pack, err := client.NewClient(client.WithFetcher(&fetcher{})) + if err != nil { + panic(err) + } + + // replace this with the location of a sample application + // For a list of prepared samples see the 'apps' folder at + // https://github.com/buildpacks/samples. + appPath := filepath.Join("testdata", "some-app") + + // initialize our options + buildOpts := client.BuildOptions{ + Image: "pack-lib-test-image:0.0.1", + Builder: "cnbs/sample-builder:bionic", + AppPath: appPath, + TrustBuilder: func(string) bool { return true }, + } + + // build an image + _ = pack.Build(context, buildOpts) + + // Output: custom fetcher called +} + +var _ client.ImageFetcher = (*fetcher)(nil) + +type fetcher struct{} + +func (f *fetcher) Fetch(_ context.Context, imageName string, _ image.FetchOptions) (imgutil.Image, error) { + fmt.Println("custom fetcher called") + return nil, errors.New("not implemented") +} From bec10bb11bb576932f44914cfad748d78a0abedf Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Mon, 1 Nov 2021 13:26:06 -0500 Subject: [PATCH 07/15] Make BuildpackDownloader publically available Before this change, the BuildpackDownloader leaked internal packages making it unusable as a library. The primary changes were to move dist and logging package to pkg. Signed-off-by: Javier Romero --- benchmarks/build_test.go | 4 +- builder/config_reader.go | 2 +- builder/detection_order.go | 2 +- buildpackage/config_reader.go | 4 +- cmd/cmd.go | 6 +- cmd/pack/main.go | 4 +- internal/build/lifecycle_execution.go | 2 +- internal/build/lifecycle_execution_test.go | 8 +- internal/build/lifecycle_executor.go | 2 +- internal/build/phase_config_provider.go | 2 +- internal/build/phase_config_provider_test.go | 5 +- internal/build/phase_test.go | 7 +- internal/builder/builder.go | 17 +-- internal/builder/builder_test.go | 32 ++--- .../builder/detection_order_calculator.go | 2 +- .../detection_order_calculator_test.go | 2 +- .../fakes/fake_detection_calculator.go | 2 +- internal/builder/fakes/fake_label_manager.go | 2 +- internal/builder/inspect.go | 2 +- internal/builder/inspect_test.go | 2 +- internal/builder/label_manager.go | 2 +- internal/builder/label_manager_test.go | 2 +- internal/builder/metadata.go | 2 +- internal/builder/writer/factory.go | 2 +- internal/builder/writer/human_readable.go | 4 +- .../builder/writer/human_readable_test.go | 36 +++--- internal/builder/writer/json_test.go | 24 ++-- .../builder/writer/shared_builder_test.go | 2 +- internal/builder/writer/structured_format.go | 4 +- internal/builder/writer/toml_test.go | 24 ++-- internal/builder/writer/yaml_test.go | 24 ++-- internal/buildpack/testdata/some-bp/.gitkeep | 0 internal/commands/add_registry.go | 2 +- internal/commands/add_registry_test.go | 4 +- internal/commands/build.go | 2 +- internal/commands/build_test.go | 6 +- internal/commands/builder.go | 2 +- internal/commands/builder_create.go | 2 +- internal/commands/builder_create_test.go | 5 +- internal/commands/builder_inspect.go | 2 +- internal/commands/builder_inspect_test.go | 5 +- internal/commands/builder_suggest.go | 2 +- internal/commands/builder_suggest_test.go | 5 +- internal/commands/builder_test.go | 5 +- internal/commands/buildpack.go | 2 +- internal/commands/buildpack_inspect.go | 2 +- internal/commands/buildpack_inspect_test.go | 14 +-- internal/commands/buildpack_new.go | 4 +- internal/commands/buildpack_new_test.go | 8 +- internal/commands/buildpack_package.go | 2 +- internal/commands/buildpack_package_test.go | 14 +-- internal/commands/buildpack_pull.go | 2 +- internal/commands/buildpack_pull_test.go | 5 +- internal/commands/buildpack_register.go | 2 +- internal/commands/buildpack_register_test.go | 5 +- internal/commands/buildpack_test.go | 5 +- internal/commands/buildpack_yank.go | 2 +- internal/commands/buildpack_yank_test.go | 5 +- internal/commands/commands.go | 2 +- internal/commands/completion.go | 2 +- internal/commands/completion_test.go | 5 +- internal/commands/config.go | 2 +- internal/commands/config_default_builder.go | 2 +- .../commands/config_default_builder_test.go | 5 +- internal/commands/config_experimental.go | 2 +- internal/commands/config_experimental_test.go | 5 +- internal/commands/config_lifecycle_image.go | 2 +- .../commands/config_lifecycle_image_test.go | 5 +- internal/commands/config_pull_policy.go | 2 +- internal/commands/config_pull_policy_test.go | 5 +- internal/commands/config_registries.go | 2 +- .../commands/config_registries_default.go | 2 +- .../config_registries_default_test.go | 4 +- internal/commands/config_registries_test.go | 11 +- internal/commands/config_registry_mirrors.go | 2 +- .../commands/config_registry_mirrors_test.go | 5 +- internal/commands/config_run_image_mirrors.go | 2 +- .../commands/config_run_image_mirrors_test.go | 5 +- internal/commands/config_test.go | 5 +- internal/commands/config_trusted_builder.go | 2 +- .../commands/config_trusted_builder_test.go | 5 +- internal/commands/create_builder.go | 2 +- internal/commands/create_builder_test.go | 5 +- .../commands/fakes/fake_builder_writer.go | 2 +- .../fakes/fake_inspect_image_writer.go | 2 +- internal/commands/inspect_builder.go | 2 +- internal/commands/inspect_builder_test.go | 5 +- internal/commands/inspect_buildpack.go | 9 +- internal/commands/inspect_buildpack_test.go | 14 +-- internal/commands/inspect_image.go | 2 +- internal/commands/inspect_image_test.go | 5 +- internal/commands/list_registries.go | 2 +- internal/commands/list_registries_test.go | 7 +- internal/commands/list_trusted_builders.go | 2 +- .../commands/list_trusted_builders_test.go | 5 +- internal/commands/package_buildpack.go | 2 +- internal/commands/package_buildpack_test.go | 24 ++-- internal/commands/rebase.go | 2 +- internal/commands/rebase_test.go | 5 +- internal/commands/register_buildpack.go | 2 +- internal/commands/register_buildpack_test.go | 5 +- internal/commands/remove_registry.go | 2 +- internal/commands/remove_registry_test.go | 4 +- internal/commands/report.go | 2 +- internal/commands/report_test.go | 5 +- internal/commands/set_default_builder.go | 2 +- internal/commands/set_default_builder_test.go | 5 +- internal/commands/set_default_registry.go | 2 +- .../commands/set_default_registry_test.go | 4 +- internal/commands/set_run_image_mirrors.go | 2 +- .../commands/set_run_image_mirrors_test.go | 5 +- internal/commands/stack.go | 2 +- internal/commands/stack_suggest.go | 2 +- internal/commands/stack_suggest_test.go | 2 +- internal/commands/suggest_builders.go | 2 +- internal/commands/suggest_builders_test.go | 5 +- internal/commands/suggest_stacks.go | 2 +- internal/commands/suggest_stacks_test.go | 2 +- internal/commands/trust_builder.go | 2 +- internal/commands/trust_builder_test.go | 5 +- internal/commands/untrust_builder.go | 2 +- internal/commands/untrust_builder_test.go | 5 +- internal/commands/version.go | 2 +- internal/commands/version_test.go | 2 +- internal/commands/yank_buildpack.go | 2 +- internal/commands/yank_buildpack_test.go | 5 +- internal/fakes/fake_buildpack.go | 5 +- internal/fakes/fake_buildpack_blob.go | 5 +- internal/fakes/fake_buildpack_tar.go | 2 +- internal/fakes/fake_images.go | 2 +- internal/fakes/fake_package.go | 9 +- internal/inspectimage/bom_display.go | 2 +- internal/inspectimage/info_display.go | 2 +- internal/inspectimage/writer/bom_json_test.go | 8 +- internal/inspectimage/writer/bom_yaml_test.go | 8 +- internal/inspectimage/writer/factory.go | 2 +- .../inspectimage/writer/human_readable.go | 2 +- .../writer/human_readable_test.go | 18 +-- internal/inspectimage/writer/json_test.go | 8 +- .../writer/structured_bom_format.go | 2 +- .../writer/structured_bom_format_test.go | 8 +- .../inspectimage/writer/structured_format.go | 2 +- .../writer/structured_format_test.go | 8 +- internal/inspectimage/writer/toml_test.go | 8 +- internal/inspectimage/writer/yaml_test.go | 8 +- internal/logging/log_writer.go | 73 ------------ internal/logging/log_writer_test.go | 111 ------------------ internal/name/name.go | 7 +- internal/name/name_test.go | 4 +- internal/registry/git_test.go | 5 +- internal/registry/registry_cache.go | 4 +- internal/registry/registry_cache_test.go | 5 +- internal/stack/merge.go | 2 +- internal/stack/merge_test.go | 2 +- internal/term/term.go | 25 ++++ internal/term/term_test.go | 39 ++++++ pkg/blob/downloader.go | 31 +++-- pkg/blob/downloader_test.go | 23 +++- .../buildpackage => pkg/buildpack}/builder.go | 19 +-- .../buildpack}/builder_test.go | 68 +++++------ {internal/dist => pkg/buildpack}/buildpack.go | 93 +++++++-------- .../dist => pkg/buildpack}/buildpack_test.go | 35 +++--- .../buildpack}/buildpackage.go | 5 +- pkg/buildpack/downloader.go | 54 +++++---- pkg/buildpack/downloader_test.go | 7 +- {internal => pkg}/buildpack/locator_type.go | 2 +- .../buildpack/locator_type_test.go | 8 +- .../buildpack}/oci_layout_package.go | 14 +-- .../buildpack}/oci_layout_package_test.go | 19 ++- .../buildpackage => pkg/buildpack}/package.go | 10 +- {internal => pkg}/buildpack/parse_name.go | 0 .../buildpack/parse_name_test.go | 2 +- .../buildpack}/testdata/hello-universe.cnb | Bin .../buildpack}/testdata/package.toml | 0 pkg/client/build.go | 21 ++-- pkg/client/build_test.go | 13 +- pkg/client/client.go | 7 +- pkg/client/client_test.go | 4 +- pkg/client/common.go | 2 +- pkg/client/common_test.go | 13 +- pkg/client/create_builder.go | 5 +- pkg/client/create_builder_test.go | 22 ++-- .../example_buildpack_downloader_test.go | 51 ++++++++ pkg/client/inspect_builder.go | 2 +- pkg/client/inspect_builder_test.go | 4 +- pkg/client/inspect_buildpack.go | 43 ++++--- pkg/client/inspect_buildpack_test.go | 13 +- pkg/client/inspect_image.go | 2 +- pkg/client/inspect_image_test.go | 2 +- pkg/client/new_buildpack.go | 2 +- pkg/client/new_buildpack_test.go | 2 +- pkg/client/package_buildpack.go | 10 +- pkg/client/package_buildpack_test.go | 10 +- pkg/client/pull_buildpack.go | 4 +- pkg/client/pull_buildpack_test.go | 2 +- pkg/client/rebase.go | 2 +- pkg/client/rebase_test.go | 2 +- pkg/client/register_buildpack.go | 6 +- pkg/client/register_buildpack_test.go | 2 +- pkg/client/yank_buildpack_test.go | 2 +- pkg/dist/buildpack.go | 39 ++++++ .../dist/buildpack_descriptor.go | 0 .../dist/buildpack_descriptor_test.go | 2 +- {internal => pkg}/dist/dist.go | 15 --- {internal => pkg}/dist/dist_test.go | 2 +- pkg/dist/distribution.go | 3 + {internal => pkg}/dist/image.go | 0 {internal => pkg}/dist/layers.go | 39 +++--- pkg/image/fetcher.go | 6 +- pkg/image/fetcher_test.go | 2 +- .../logging/logger_simple.go | 28 ++--- .../logging/logger_simple_test.go | 11 +- .../logging/logger_writers.go | 95 ++++++++++++--- .../logging/logger_writers_test.go | 41 ++----- {logging => pkg/logging}/logging.go | 9 +- {logging => pkg/logging}/logging_test.go | 21 ++-- {logging => pkg/logging}/prefix_writer.go | 0 .../logging}/prefix_writer_test.go | 2 +- .../dist => pkg}/testmocks/mock_buildpack.go | 4 +- pkg/testmocks/mock_buildpack_downloader.go | 7 +- pkg/testmocks/mock_registry_resolver.go | 2 +- testhelpers/testhelpers.go | 6 +- testmocks/mock_registry_resolver.go | 48 -------- 223 files changed, 967 insertions(+), 1051 deletions(-) delete mode 100644 internal/buildpack/testdata/some-bp/.gitkeep delete mode 100644 internal/logging/log_writer.go delete mode 100644 internal/logging/log_writer_test.go create mode 100644 internal/term/term.go create mode 100644 internal/term/term_test.go rename {internal/buildpackage => pkg/buildpack}/builder.go (93%) rename {internal/buildpackage => pkg/buildpack}/builder_test.go (91%) rename {internal/dist => pkg/buildpack}/buildpack.go (69%) rename {internal/dist => pkg/buildpack}/buildpack_test.go (93%) rename {internal/buildpackage => pkg/buildpack}/buildpackage.go (68%) rename {internal => pkg}/buildpack/locator_type.go (98%) rename {internal => pkg}/buildpack/locator_type_test.go (96%) rename {internal/buildpackage => pkg/buildpack}/oci_layout_package.go (90%) rename {internal/buildpackage => pkg/buildpack}/oci_layout_package_test.go (75%) rename {internal/buildpackage => pkg/buildpack}/package.go (86%) rename {internal => pkg}/buildpack/parse_name.go (100%) rename {internal => pkg}/buildpack/parse_name_test.go (98%) rename {internal/buildpackage => pkg/buildpack}/testdata/hello-universe.cnb (100%) rename {internal/buildpackage => pkg/buildpack}/testdata/package.toml (100%) create mode 100644 pkg/client/example_buildpack_downloader_test.go create mode 100644 pkg/dist/buildpack.go rename {internal => pkg}/dist/buildpack_descriptor.go (100%) rename {internal => pkg}/dist/buildpack_descriptor_test.go (98%) rename {internal => pkg}/dist/dist.go (76%) rename {internal => pkg}/dist/dist_test.go (98%) create mode 100644 pkg/dist/distribution.go rename {internal => pkg}/dist/image.go (100%) rename {internal => pkg}/dist/layers.go (52%) rename logging/default_logger.go => pkg/logging/logger_simple.go (51%) rename logging/default_logger_test.go => pkg/logging/logger_simple_test.go (88%) rename internal/logging/logging.go => pkg/logging/logger_writers.go (63%) rename internal/logging/logging_test.go => pkg/logging/logger_writers_test.go (83%) rename {logging => pkg/logging}/logging.go (81%) rename {logging => pkg/logging}/logging_test.go (79%) rename {logging => pkg/logging}/prefix_writer.go (100%) rename {logging => pkg/logging}/prefix_writer_test.go (98%) rename {internal/dist => pkg}/testmocks/mock_buildpack.go (94%) delete mode 100644 testmocks/mock_registry_resolver.go diff --git a/benchmarks/build_test.go b/benchmarks/build_test.go index 14a2675737..b3b0234076 100644 --- a/benchmarks/build_test.go +++ b/benchmarks/build_test.go @@ -14,8 +14,8 @@ import ( "github.com/buildpacks/pack/internal/commands" cfg "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -76,7 +76,7 @@ func BenchmarkBuild(b *testing.B) { func createCmd(b *testing.B, docker *dockerCli.Client) *cobra.Command { outBuf := bytes.Buffer{} - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) packClient, err := client.NewClient(client.WithLogger(logger), client.WithDockerClient(docker), client.WithExperimental(true)) if err != nil { b.Error(errors.Wrap(err, "creating packClient")) diff --git a/builder/config_reader.go b/builder/config_reader.go index 6b0120ec80..66625fbc5b 100644 --- a/builder/config_reader.go +++ b/builder/config_reader.go @@ -9,8 +9,8 @@ import ( "github.com/pkg/errors" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/dist" ) // Config is a builder configuration file diff --git a/builder/detection_order.go b/builder/detection_order.go index bc33d1ee33..2063f02645 100644 --- a/builder/detection_order.go +++ b/builder/detection_order.go @@ -1,7 +1,7 @@ package builder import ( - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) type DetectionOrderEntry struct { diff --git a/buildpackage/config_reader.go b/buildpackage/config_reader.go index 682e81154e..8dbbafa276 100644 --- a/buildpackage/config_reader.go +++ b/buildpackage/config_reader.go @@ -6,10 +6,10 @@ import ( "github.com/BurntSushi/toml" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" ) const defaultOS = "linux" diff --git a/cmd/cmd.go b/cmd/cmd.go index c536dceff5..1cef31785a 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -10,9 +10,9 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" imagewriter "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/internal/term" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) // ConfigurableLogger defines behavior required by the PackCommand @@ -46,7 +46,7 @@ func NewPackCommand(logger ConfigurableLogger) (*cobra.Command, error) { color.Disable(flag) } - _, canDisplayColor := ilogging.IsTerminal(logging.GetWriterForLevel(logger, logging.InfoLevel)) + _, canDisplayColor := term.IsTerminal(logging.GetWriterForLevel(logger, logging.InfoLevel)) if !canDisplayColor { color.Disable(true) } diff --git a/cmd/pack/main.go b/cmd/pack/main.go index ee08a28ff1..ddebd1cd13 100644 --- a/cmd/pack/main.go +++ b/cmd/pack/main.go @@ -9,12 +9,12 @@ import ( "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/commands" - clilogger "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" ) func main() { // create logger with defaults - logger := clilogger.NewLogWithWriters(color.Stdout(), color.Stderr()) + logger := logging.NewLogWithWriters(color.Stdout(), color.Stderr()) rootCmd, err := cmd.NewPackCommand(logger) if err != nil { diff --git a/internal/build/lifecycle_execution.go b/internal/build/lifecycle_execution.go index 87d82b6304..b50cd5ec10 100644 --- a/internal/build/lifecycle_execution.go +++ b/internal/build/lifecycle_execution.go @@ -17,7 +17,7 @@ import ( "github.com/buildpacks/pack/internal/cache" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) const ( diff --git a/internal/build/lifecycle_execution_test.go b/internal/build/lifecycle_execution_test.go index 0f73160ff4..8ea20d3479 100644 --- a/internal/build/lifecycle_execution_test.go +++ b/internal/build/lifecycle_execution_test.go @@ -25,7 +25,7 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/build/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -105,7 +105,7 @@ func testLifecycleExecution(t *testing.T, when spec.G, it spec.S) { imageName name.Tag fakeBuilder *fakes.FakeBuilder outBuf bytes.Buffer - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters docker *client.Client fakePhaseFactory *fakes.FakePhaseFactory ) @@ -117,7 +117,7 @@ func testLifecycleExecution(t *testing.T, when spec.G, it spec.S) { fakeBuilder, err = fakes.NewFakeBuilder(fakes.WithSupportedPlatformAPIs([]*api.Version{api.MustParse("0.3")})) h.AssertNil(t, err) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) docker, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.38")) h.AssertNil(t, err) fakePhaseFactory = fakes.NewFakePhaseFactory() @@ -2332,7 +2332,7 @@ func newTestLifecycleExecErr(t *testing.T, logVerbose bool, ops ...func(*build.L h.AssertNil(t, err) var outBuf bytes.Buffer - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) if logVerbose { logger.Level = log.DebugLevel } diff --git a/internal/build/lifecycle_executor.go b/internal/build/lifecycle_executor.go index bc5a35dd29..95ccbb214f 100644 --- a/internal/build/lifecycle_executor.go +++ b/internal/build/lifecycle_executor.go @@ -14,7 +14,7 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/cache" "github.com/buildpacks/pack/internal/container" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) var ( diff --git a/internal/build/phase_config_provider.go b/internal/build/phase_config_provider.go index 8f17af4558..c9edc29adf 100644 --- a/internal/build/phase_config_provider.go +++ b/internal/build/phase_config_provider.go @@ -10,7 +10,7 @@ import ( pcontainer "github.com/buildpacks/pack/internal/container" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) const ( diff --git a/internal/build/phase_config_provider_test.go b/internal/build/phase_config_provider_test.go index dba3dca217..a0acf06bc6 100644 --- a/internal/build/phase_config_provider_test.go +++ b/internal/build/phase_config_provider_test.go @@ -18,8 +18,7 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/build/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -299,7 +298,7 @@ func testPhaseConfigProvider(t *testing.T, when spec.G, it spec.S) { when("verbose", func() { it("prints debug information about the phase", func() { var outBuf bytes.Buffer - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) docker, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.38")) h.AssertNil(t, err) diff --git a/internal/build/phase_test.go b/internal/build/phase_test.go index 326fcd428f..d347ba89b8 100644 --- a/internal/build/phase_test.go +++ b/internal/build/phase_test.go @@ -30,9 +30,8 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/build/fakes" "github.com/buildpacks/pack/internal/container" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -80,7 +79,7 @@ func testPhase(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) var err error docker, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion("1.38")) @@ -238,7 +237,7 @@ func testPhase(t *testing.T, when spec.G, it spec.S) { }) it("returns an error", func() { - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) lifecycleExec, err = CreateFakeLifecycleExecution(logger, docker, tmpFakeAppDir, repoName) h.AssertNil(t, err) phaseFactory = build.NewDefaultPhaseFactory(lifecycleExec) diff --git a/internal/builder/builder.go b/internal/builder/builder.go index 87393976eb..7ce61cef9c 100644 --- a/internal/builder/builder.go +++ b/internal/builder/builder.go @@ -19,12 +19,13 @@ import ( "github.com/pkg/errors" "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/stack" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" ) const ( @@ -62,7 +63,7 @@ type Builder struct { layerWriterFactory archive.TarWriterFactory lifecycle Lifecycle lifecycleDescriptor LifecycleDescriptor - additionalBuildpacks []dist.Buildpack + additionalBuildpacks []buildpack.Buildpack metadata Metadata mixins []string env map[string]string @@ -222,7 +223,7 @@ func (b *Builder) GID() int { // Setters // AddBuildpack adds a buildpack to the builder -func (b *Builder) AddBuildpack(bp dist.Buildpack) { +func (b *Builder) AddBuildpack(bp buildpack.Buildpack) { b.additionalBuildpacks = append(b.additionalBuildpacks, bp) b.metadata.Buildpacks = append(b.metadata.Buildpacks, bp.Descriptor().Info) } @@ -375,11 +376,11 @@ func (b *Builder) Save(logger logging.Logger, creatorMetadata CreatorMetadata) e // Helpers -func addBuildpacks(logger logging.Logger, tmpDir string, image imgutil.Image, additionalBuildpacks []dist.Buildpack, bpLayers dist.BuildpackLayers) error { +func addBuildpacks(logger logging.Logger, tmpDir string, image imgutil.Image, additionalBuildpacks []buildpack.Buildpack, bpLayers dist.BuildpackLayers) error { type buildpackToAdd struct { tarPath string diffID string - buildpack dist.Buildpack + buildpack buildpack.Buildpack } buildpacksToAdd := map[string]buildpackToAdd{} @@ -391,7 +392,7 @@ func addBuildpacks(logger logging.Logger, tmpDir string, image imgutil.Image, ad } // create tar file - bpLayerTar, err := dist.BuildpackToLayerTar(bpTmpDir, bp) + bpLayerTar, err := buildpack.BuildpackToLayerTar(bpTmpDir, bp) if err != nil { return err } @@ -495,7 +496,7 @@ func hasBuildpackWithVersion(bps []dist.BuildpackInfo, version string) bool { return false } -func validateBuildpacks(stackID string, mixins []string, lifecycleDescriptor LifecycleDescriptor, allBuildpacks []dist.BuildpackInfo, bpsToValidate []dist.Buildpack) error { +func validateBuildpacks(stackID string, mixins []string, lifecycleDescriptor LifecycleDescriptor, allBuildpacks []dist.BuildpackInfo, bpsToValidate []buildpack.Buildpack) error { bpLookup := map[string]interface{}{} for _, bp := range allBuildpacks { diff --git a/internal/builder/builder_test.go b/internal/builder/builder_test.go index 2c8f8f10c3..6c0744d4a0 100644 --- a/internal/builder/builder_test.go +++ b/internal/builder/builder_test.go @@ -26,11 +26,11 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/testmocks" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -46,16 +46,16 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { subject *builder.Builder mockController *gomock.Controller mockLifecycle *testmocks.MockLifecycle - bp1v1 dist.Buildpack - bp1v2 dist.Buildpack - bp2v1 dist.Buildpack - bpOrder dist.Buildpack + bp1v1 buildpack.Buildpack + bp1v2 buildpack.Buildpack + bp2v1 buildpack.Buildpack + bpOrder buildpack.Buildpack outBuf bytes.Buffer logger logging.Logger ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) baseImage = fakes.NewImage("base/image", "", nil) mockController = gomock.NewController(t) @@ -657,7 +657,7 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { }) when("duplicated buildpack, has different contents", func() { - var bp1v1Alt dist.Buildpack + var bp1v1Alt buildpack.Buildpack it.Before(func() { var err error bp1v1Alt, err = ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ @@ -675,7 +675,7 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { }) it("uses the last buildpack", func() { - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) subject.AddBuildpack(bp1v1) subject.AddBuildpack(bp1v1Alt) @@ -719,11 +719,11 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { when("adding buildpack that already exists on the image", func() { it("skips adding buildpack that already exists", func() { - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) diffID := "4dc0072c61fc2bd7118bbc93a432eae0012082de094455cf0a9fed20e3c44789" bpLayer := dist.BuildpackLayers{ "buildpack-1-id": map[string]dist.BuildpackLayerInfo{ - "buildpack-1-version-1": dist.BuildpackLayerInfo{ + "buildpack-1-version-1": { API: api.MustParse("0.2"), Stacks: nil, Order: nil, @@ -753,7 +753,7 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { when("error adding buildpacks to builder", func() { when("unable to convert buildpack to layer tar", func() { - var bp1v1Err dist.Buildpack + var bp1v1Err buildpack.Buildpack it.Before(func() { var err error bp1v1Err, err = ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ @@ -999,7 +999,7 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { }) it("informs when overriding existing buildpack, and log level is DEBUG", func() { - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) h.AssertNil(t, subject.Save(logger, builder.CreatorMetadata{})) h.AssertEq(t, baseImage.IsSaved(), true) @@ -1330,7 +1330,7 @@ func testBuilder(t *testing.T, when spec.G, it spec.S) { }) } -func assertImageHasBPLayer(t *testing.T, image *fakes.Image, bp dist.Buildpack) { +func assertImageHasBPLayer(t *testing.T, image *fakes.Image, bp buildpack.Buildpack) { t.Helper() dirPath := fmt.Sprintf("/cnb/buildpacks/%s/%s", bp.Descriptor().Info.ID, bp.Descriptor().Info.Version) @@ -1354,7 +1354,7 @@ func assertImageHasBPLayer(t *testing.T, image *fakes.Image, bp dist.Buildpack) ) } -func assertImageHasOrderBpLayer(t *testing.T, image *fakes.Image, bp dist.Buildpack) { +func assertImageHasOrderBpLayer(t *testing.T, image *fakes.Image, bp buildpack.Buildpack) { t.Helper() dirPath := fmt.Sprintf("/cnb/buildpacks/%s/%s", bp.Descriptor().Info.ID, bp.Descriptor().Info.Version) diff --git a/internal/builder/detection_order_calculator.go b/internal/builder/detection_order_calculator.go index bddc95d237..d62ad49057 100644 --- a/internal/builder/detection_order_calculator.go +++ b/internal/builder/detection_order_calculator.go @@ -2,7 +2,7 @@ package builder import ( pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) type DetectionOrderCalculator struct{} diff --git a/internal/builder/detection_order_calculator_test.go b/internal/builder/detection_order_calculator_test.go index 18d78867e1..f84bd4b2e3 100644 --- a/internal/builder/detection_order_calculator_test.go +++ b/internal/builder/detection_order_calculator_test.go @@ -7,7 +7,7 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" "github.com/heroku/color" diff --git a/internal/builder/fakes/fake_detection_calculator.go b/internal/builder/fakes/fake_detection_calculator.go index 2cd923fdfd..e3aa1c52fe 100644 --- a/internal/builder/fakes/fake_detection_calculator.go +++ b/internal/builder/fakes/fake_detection_calculator.go @@ -2,7 +2,7 @@ package fakes import ( "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) type FakeDetectionCalculator struct { diff --git a/internal/builder/fakes/fake_label_manager.go b/internal/builder/fakes/fake_label_manager.go index 63cd99d110..7641b87acb 100644 --- a/internal/builder/fakes/fake_label_manager.go +++ b/internal/builder/fakes/fake_label_manager.go @@ -2,7 +2,7 @@ package fakes import ( "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) type FakeLabelManager struct { diff --git a/internal/builder/inspect.go b/internal/builder/inspect.go index 80af793598..7a3cc6ca09 100644 --- a/internal/builder/inspect.go +++ b/internal/builder/inspect.go @@ -7,7 +7,7 @@ import ( "strings" pubbldr "github.com/buildpacks/pack/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) diff --git a/internal/builder/inspect_test.go b/internal/builder/inspect_test.go index 9fd9c8bb27..6285844f0c 100644 --- a/internal/builder/inspect_test.go +++ b/internal/builder/inspect_test.go @@ -9,7 +9,7 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/fakes" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" h "github.com/buildpacks/pack/testhelpers" diff --git a/internal/builder/label_manager.go b/internal/builder/label_manager.go index 40a04df874..cdbfe760fd 100644 --- a/internal/builder/label_manager.go +++ b/internal/builder/label_manager.go @@ -4,7 +4,7 @@ import ( "encoding/json" "fmt" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/internal/stack" ) diff --git a/internal/builder/label_manager_test.go b/internal/builder/label_manager_test.go index f9452f1d5e..fda7eba4b9 100644 --- a/internal/builder/label_manager_test.go +++ b/internal/builder/label_manager_test.go @@ -13,7 +13,7 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/fakes" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/builder/metadata.go b/internal/builder/metadata.go index b581e7f03c..111ec4ef83 100644 --- a/internal/builder/metadata.go +++ b/internal/builder/metadata.go @@ -1,6 +1,6 @@ package builder -import "github.com/buildpacks/pack/internal/dist" +import "github.com/buildpacks/pack/pkg/dist" const ( OrderLabel = "io.buildpacks.buildpack.order" diff --git a/internal/builder/writer/factory.go b/internal/builder/writer/factory.go index 5dc21858f3..569df9233a 100644 --- a/internal/builder/writer/factory.go +++ b/internal/builder/writer/factory.go @@ -4,8 +4,8 @@ import ( "fmt" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/internal/style" ) diff --git a/internal/builder/writer/human_readable.go b/internal/builder/writer/human_readable.go index e416680e77..6f649c6a28 100644 --- a/internal/builder/writer/human_readable.go +++ b/internal/builder/writer/human_readable.go @@ -13,14 +13,14 @@ import ( "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) const ( diff --git a/internal/builder/writer/human_readable_test.go b/internal/builder/writer/human_readable_test.go index 0b977cf684..a9d5bb5671 100644 --- a/internal/builder/writer/human_readable_test.go +++ b/internal/builder/writer/human_readable_test.go @@ -15,9 +15,9 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -247,7 +247,7 @@ REMOTE: it("prints both local and remote builders in a human readable format", func() { humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -263,7 +263,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, defaultSharedBuildInfo) assert.Nil(err) @@ -278,7 +278,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "unable to find builder 'test-builder' locally or remotely") }) @@ -290,7 +290,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -305,7 +305,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -320,7 +320,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, errors.New(errorMessage), nil, sharedBuilderInfo) assert.Nil(err) @@ -336,7 +336,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, errors.New(errorMessage), sharedBuilderInfo) assert.Nil(err) @@ -353,7 +353,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -368,7 +368,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -380,7 +380,7 @@ REMOTE: it("displays mixins associated with the stack", func() { humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -395,7 +395,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -411,7 +411,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -426,7 +426,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -444,7 +444,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, emptyLocalRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -461,7 +461,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -484,7 +484,7 @@ REMOTE: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) diff --git a/internal/builder/writer/json_test.go b/internal/builder/writer/json_test.go index f8d40534fc..e09b31361e 100644 --- a/internal/builder/writer/json_test.go +++ b/internal/builder/writer/json_test.go @@ -17,9 +17,9 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -308,7 +308,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { it("prints both local remote builders as valid JSON", func() { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -322,7 +322,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { it("returns an error", func() { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, nil, nil, nil, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "unable to find builder 'test-builder' locally or remotely") }) @@ -332,7 +332,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { it("shows null for local builder, and normal output for remote", func() { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, nil, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -348,7 +348,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { it("shows null for remote builder, and normal output for local", func() { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, localInfo, nil, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -366,7 +366,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, expectedErr, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve local info") @@ -380,7 +380,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, expectedErr, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve remote info") @@ -392,7 +392,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { it("displays mixins associated with the stack", func() { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -413,7 +413,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := jsonWriter.Print(logger, emptyLocalRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -431,7 +431,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -449,7 +449,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := jsonWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) diff --git a/internal/builder/writer/shared_builder_test.go b/internal/builder/writer/shared_builder_test.go index 1ca9db4953..4e7629756d 100644 --- a/internal/builder/writer/shared_builder_test.go +++ b/internal/builder/writer/shared_builder_test.go @@ -4,7 +4,7 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) var ( diff --git a/internal/builder/writer/structured_format.go b/internal/builder/writer/structured_format.go index 44ee56481a..173d006d0b 100644 --- a/internal/builder/writer/structured_format.go +++ b/internal/builder/writer/structured_format.go @@ -9,8 +9,8 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" ) type InspectOutput struct { diff --git a/internal/builder/writer/toml_test.go b/internal/builder/writer/toml_test.go index 8e48b69487..89561432cf 100644 --- a/internal/builder/writer/toml_test.go +++ b/internal/builder/writer/toml_test.go @@ -18,9 +18,9 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -335,7 +335,7 @@ default = false it("prints both local remote builders as valid TOML", func() { tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -349,7 +349,7 @@ default = false it("returns an error", func() { tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, nil, nil, nil, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "unable to find builder 'test-builder' locally or remotely") }) @@ -359,7 +359,7 @@ default = false it("shows null for local builder, and normal output for remote", func() { tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, nil, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -375,7 +375,7 @@ default = false it("shows null for remote builder, and normal output for local", func() { tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, localInfo, nil, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -393,7 +393,7 @@ default = false tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, expectedErr, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve local info") @@ -407,7 +407,7 @@ default = false tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, expectedErr, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve remote info") @@ -419,7 +419,7 @@ default = false it("displays mixins associated with the stack", func() { tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -438,7 +438,7 @@ default = false tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := tomlWriter.Print(logger, emptyLocalRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -455,7 +455,7 @@ default = false tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -473,7 +473,7 @@ default = false tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := tomlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) diff --git a/internal/builder/writer/yaml_test.go b/internal/builder/writer/yaml_test.go index 0b04aa23c8..629fbea8c2 100644 --- a/internal/builder/writer/yaml_test.go +++ b/internal/builder/writer/yaml_test.go @@ -18,9 +18,9 @@ import ( "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -232,7 +232,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { it("prints both local remote builders as valid YAML", func() { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -246,7 +246,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { it("returns an error", func() { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, nil, nil, nil, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "unable to find builder 'test-builder' locally or remotely") }) @@ -256,7 +256,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { it("shows null for local builder, and normal output for remote", func() { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, nil, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -272,7 +272,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { it("shows null for remote builder, and normal output for local", func() { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, localInfo, nil, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -290,7 +290,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, expectedErr, nil, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve local info") @@ -304,7 +304,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, expectedErr, sharedBuilderInfo) assert.ErrorWithMessage(err, "preparing output for 'test-builder': failed to retrieve remote info") @@ -316,7 +316,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { it("displays mixins associated with the stack", func() { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -337,7 +337,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := yamlWriter.Print(logger, emptyLocalRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -355,7 +355,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) @@ -373,7 +373,7 @@ func testYAML(t *testing.T, when spec.G, it spec.S) { yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger := logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) err := yamlWriter.Print(logger, localRunImages, localInfo, remoteInfo, nil, nil, sharedBuilderInfo) assert.Nil(err) diff --git a/internal/buildpack/testdata/some-bp/.gitkeep b/internal/buildpack/testdata/some-bp/.gitkeep deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/internal/commands/add_registry.go b/internal/commands/add_registry.go index 99b334bbf5..83d38c9e86 100644 --- a/internal/commands/add_registry.go +++ b/internal/commands/add_registry.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use config registries add instead diff --git a/internal/commands/add_registry_test.go b/internal/commands/add_registry_test.go index 3f6997538f..2583834fcc 100644 --- a/internal/commands/add_registry_test.go +++ b/internal/commands/add_registry_test.go @@ -15,7 +15,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -33,7 +33,7 @@ func testAddRegistryCommand(t *testing.T, when spec.G, it spec.S) { configFile string outBuf bytes.Buffer command *cobra.Command - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) assert = h.NewAssertionManager(t) ) diff --git a/internal/commands/build.go b/internal/commands/build.go index 6a7210445f..0d9202438c 100644 --- a/internal/commands/build.go +++ b/internal/commands/build.go @@ -12,9 +12,9 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/project" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) diff --git a/internal/commands/build_test.go b/internal/commands/build_test.go index c6aec94c64..7ef962abee 100644 --- a/internal/commands/build_test.go +++ b/internal/commands/build_test.go @@ -20,9 +20,9 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -37,7 +37,7 @@ func TestBuildCommand(t *testing.T) { func testBuildCommand(t *testing.T, when spec.G, it spec.S) { var ( command *cobra.Command - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters outBuf bytes.Buffer mockController *gomock.Controller mockClient *testmocks.MockPackClient @@ -45,7 +45,7 @@ func testBuildCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{} mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) diff --git a/internal/commands/builder.go b/internal/commands/builder.go index 8156764acb..50d5efdd1a 100644 --- a/internal/commands/builder.go +++ b/internal/commands/builder.go @@ -5,7 +5,7 @@ import ( builderwriter "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func NewBuilderCommand(logger logging.Logger, cfg config.Config, client PackClient) *cobra.Command { diff --git a/internal/commands/builder_create.go b/internal/commands/builder_create.go index 7d79bda4d8..5ba06f03fc 100644 --- a/internal/commands/builder_create.go +++ b/internal/commands/builder_create.go @@ -10,9 +10,9 @@ import ( "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) // BuilderCreateFlags define flags provided to the CreateBuilder command diff --git a/internal/commands/builder_create_test.go b/internal/commands/builder_create_test.go index 1b14e4f4e3..e7392ca082 100644 --- a/internal/commands/builder_create_test.go +++ b/internal/commands/builder_create_test.go @@ -15,8 +15,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -57,7 +56,7 @@ func testCreateCommand(t *testing.T, when spec.G, it spec.S) { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) command = commands.BuilderCreate(logger, cfg, mockClient) }) diff --git a/internal/commands/builder_inspect.go b/internal/commands/builder_inspect.go index 743a6d616d..e86f91defa 100644 --- a/internal/commands/builder_inspect.go +++ b/internal/commands/builder_inspect.go @@ -6,8 +6,8 @@ import ( "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type BuilderInspector interface { diff --git a/internal/commands/builder_inspect_test.go b/internal/commands/builder_inspect_test.go index d95c9f31c0..67cfc10ad0 100644 --- a/internal/commands/builder_inspect_test.go +++ b/internal/commands/builder_inspect_test.go @@ -16,9 +16,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -73,7 +72,7 @@ func testBuilderInspectCommand(t *testing.T, when spec.G, it spec.S) { DefaultBuilder: "default/builder", RunImages: expectedLocalRunImages, } - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) when("BuilderInspect", func() { diff --git a/internal/commands/builder_suggest.go b/internal/commands/builder_suggest.go index 839b791e25..e62ed43d31 100644 --- a/internal/commands/builder_suggest.go +++ b/internal/commands/builder_suggest.go @@ -3,7 +3,7 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func BuilderSuggest(logger logging.Logger, inspector BuilderInspector) *cobra.Command { diff --git a/internal/commands/builder_suggest_test.go b/internal/commands/builder_suggest_test.go index 81fdd99b49..f12bb0b164 100644 --- a/internal/commands/builder_suggest_test.go +++ b/internal/commands/builder_suggest_test.go @@ -13,9 +13,8 @@ import ( bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testSuggestCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) when("#WriteSuggestedBuilder", func() { diff --git a/internal/commands/builder_test.go b/internal/commands/builder_test.go index b525a3c5fa..801bc873d6 100644 --- a/internal/commands/builder_test.go +++ b/internal/commands/builder_test.go @@ -12,8 +12,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -29,7 +28,7 @@ func testBuilderCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController := gomock.NewController(t) mockClient := testmocks.NewMockPackClient(mockController) cmd = commands.NewBuilderCommand(logger, config.Config{}, mockClient) diff --git a/internal/commands/buildpack.go b/internal/commands/buildpack.go index fea2a7b247..93985be84f 100644 --- a/internal/commands/buildpack.go +++ b/internal/commands/buildpack.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func NewBuildpackCommand(logger logging.Logger, cfg config.Config, client PackClient, packageConfigReader PackageConfigReader) *cobra.Command { diff --git a/internal/commands/buildpack_inspect.go b/internal/commands/buildpack_inspect.go index c381028508..e75c479f89 100644 --- a/internal/commands/buildpack_inspect.go +++ b/internal/commands/buildpack_inspect.go @@ -7,8 +7,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type BuildpackInspectFlags struct { diff --git a/internal/commands/buildpack_inspect_test.go b/internal/commands/buildpack_inspect_test.go index 843b389fa9..db12752243 100644 --- a/internal/commands/buildpack_inspect_test.go +++ b/internal/commands/buildpack_inspect_test.go @@ -13,16 +13,14 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -133,14 +131,14 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{ DefaultRegistryName: "default-registry", } complexInfo = &client.BuildpackInfo{ - BuildpackMetadata: buildpackage.Metadata{ + BuildpackMetadata: buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", Version: "0.0.1", @@ -298,7 +296,7 @@ func testBuildpackInspectCommand(t *testing.T, when spec.G, it spec.S) { } simpleInfo = &client.BuildpackInfo{ - BuildpackMetadata: buildpackage.Metadata{ + BuildpackMetadata: buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/single-buildpack", Version: "0.0.1", diff --git a/internal/commands/buildpack_new.go b/internal/commands/buildpack_new.go index d6a382b4e2..df1508a0d9 100644 --- a/internal/commands/buildpack_new.go +++ b/internal/commands/buildpack_new.go @@ -10,10 +10,10 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/build" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" ) // BuildpackNewFlags define flags provided to the BuildpackNew command diff --git a/internal/commands/buildpack_new_test.go b/internal/commands/buildpack_new_test.go index f0a0414c4e..cb9ab38b7c 100644 --- a/internal/commands/buildpack_new_test.go +++ b/internal/commands/buildpack_new_test.go @@ -7,8 +7,9 @@ import ( "path/filepath" "testing" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" "github.com/golang/mock/gomock" "github.com/heroku/color" @@ -18,7 +19,6 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" - ilogging "github.com/buildpacks/pack/internal/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -31,7 +31,7 @@ func TestBuildpackNewCommand(t *testing.T) { func testBuildpackNewCommand(t *testing.T, when spec.G, it spec.S) { var ( command *cobra.Command - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters outBuf bytes.Buffer mockController *gomock.Controller mockClient *testmocks.MockPackClient @@ -43,7 +43,7 @@ func testBuildpackNewCommand(t *testing.T, when spec.G, it spec.S) { tmpDir, err = ioutil.TempDir("", "build-test") h.AssertNil(t, err) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) diff --git a/internal/commands/buildpack_package.go b/internal/commands/buildpack_package.go index 573576f528..13aea0c97a 100644 --- a/internal/commands/buildpack_package.go +++ b/internal/commands/buildpack_package.go @@ -10,9 +10,9 @@ import ( pubbldpkg "github.com/buildpacks/pack/buildpackage" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) // BuildpackPackageFlags define flags provided to the BuildpackPackage command diff --git a/internal/commands/buildpack_package_test.go b/internal/commands/buildpack_package_test.go index 89f5dc856d..9fc93a4abb 100644 --- a/internal/commands/buildpack_package_test.go +++ b/internal/commands/buildpack_package_test.go @@ -16,9 +16,9 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -30,12 +30,12 @@ func TestPackageCommand(t *testing.T) { func testPackageCommand(t *testing.T, when spec.G, it spec.S) { var ( - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters outBuf bytes.Buffer ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) when("Package#Execute", func() { @@ -280,7 +280,7 @@ func testPackageCommand(t *testing.T, when spec.G, it spec.S) { } type packageCommandConfig struct { - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters packageConfigReader *fakes.FakePackageConfigReader buildpackPackager *fakes.FakeBuildpackPackager clientConfig config.Config @@ -293,7 +293,7 @@ type packageCommandOption func(config *packageCommandConfig) func packageCommand(ops ...packageCommandOption) *cobra.Command { config := &packageCommandConfig{ - logger: ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), + logger: logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), packageConfigReader: fakes.NewFakePackageConfigReader(), buildpackPackager: &fakes.FakeBuildpackPackager{}, clientConfig: config.Config{}, @@ -311,7 +311,7 @@ func packageCommand(ops ...packageCommandOption) *cobra.Command { return cmd } -func withLogger(logger *ilogging.LogWithWriters) packageCommandOption { +func withLogger(logger *logging.LogWithWriters) packageCommandOption { return func(config *packageCommandConfig) { config.logger = logger } diff --git a/internal/commands/buildpack_pull.go b/internal/commands/buildpack_pull.go index 0b19ff09f7..d65fb34605 100644 --- a/internal/commands/buildpack_pull.go +++ b/internal/commands/buildpack_pull.go @@ -5,8 +5,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) // BuildpackPullFlags consist of flags applicable to the `buildpack pull` command diff --git a/internal/commands/buildpack_pull_test.go b/internal/commands/buildpack_pull_test.go index 8114e71c81..da3b6b20a3 100644 --- a/internal/commands/buildpack_pull_test.go +++ b/internal/commands/buildpack_pull_test.go @@ -12,9 +12,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -33,7 +32,7 @@ func testPullBuildpackCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cfg = config.Config{} diff --git a/internal/commands/buildpack_register.go b/internal/commands/buildpack_register.go index 7b3f6d26fc..045e4a27e6 100644 --- a/internal/commands/buildpack_register.go +++ b/internal/commands/buildpack_register.go @@ -5,8 +5,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type BuildpackRegisterFlags struct { diff --git a/internal/commands/buildpack_register_test.go b/internal/commands/buildpack_register_test.go index 9b1d85e9bf..2ffe6d6239 100644 --- a/internal/commands/buildpack_register_test.go +++ b/internal/commands/buildpack_register_test.go @@ -14,8 +14,7 @@ import ( "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -34,7 +33,7 @@ func testRegisterCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cfg = config.Config{} diff --git a/internal/commands/buildpack_test.go b/internal/commands/buildpack_test.go index 3a59fd15bf..761486e494 100644 --- a/internal/commands/buildpack_test.go +++ b/internal/commands/buildpack_test.go @@ -13,8 +13,7 @@ import ( "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -31,7 +30,7 @@ func testBuildpackCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController := gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cmd = commands.NewBuildpackCommand(logger, config.Config{}, mockClient, fakes.NewFakePackageConfigReader()) diff --git a/internal/commands/buildpack_yank.go b/internal/commands/buildpack_yank.go index 52609859fd..ee2e118493 100644 --- a/internal/commands/buildpack_yank.go +++ b/internal/commands/buildpack_yank.go @@ -8,8 +8,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type BuildpackYankFlags struct { diff --git a/internal/commands/buildpack_yank_test.go b/internal/commands/buildpack_yank_test.go index 911f38d3bb..14fd64439a 100644 --- a/internal/commands/buildpack_yank_test.go +++ b/internal/commands/buildpack_yank_test.go @@ -13,9 +13,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testYankCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cfg = config.Config{} diff --git a/internal/commands/commands.go b/internal/commands/commands.go index bf692b6639..fb26d188e8 100644 --- a/internal/commands/commands.go +++ b/internal/commands/commands.go @@ -12,8 +12,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) //go:generate mockgen -package testmocks -destination testmocks/mock_pack_client.go github.com/buildpacks/pack/internal/commands PackClient diff --git a/internal/commands/completion.go b/internal/commands/completion.go index 9a9e591ed9..4cf7e00db7 100644 --- a/internal/commands/completion.go +++ b/internal/commands/completion.go @@ -7,7 +7,7 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) type CompletionFlags struct { diff --git a/internal/commands/completion_test.go b/internal/commands/completion_test.go index 8f5d5f9090..b4b5a679d3 100644 --- a/internal/commands/completion_test.go +++ b/internal/commands/completion_test.go @@ -12,8 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/commands" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -31,7 +30,7 @@ func testCompletionCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) var err error packHome, err = ioutil.TempDir("", "") assert.Nil(err) diff --git a/internal/commands/config.go b/internal/commands/config.go index 3150eff179..a2b087dabc 100644 --- a/internal/commands/config.go +++ b/internal/commands/config.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func NewConfigCommand(logger logging.Logger, cfg config.Config, cfgPath string, client PackClient) *cobra.Command { diff --git a/internal/commands/config_default_builder.go b/internal/commands/config_default_builder.go index 0252feaec3..111eebea70 100644 --- a/internal/commands/config_default_builder.go +++ b/internal/commands/config_default_builder.go @@ -8,7 +8,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) var suggestedBuilderString = "For suggested builders, run `pack builder suggest`." diff --git a/internal/commands/config_default_builder_test.go b/internal/commands/config_default_builder_test.go index dbb345d8d4..a34500d99d 100644 --- a/internal/commands/config_default_builder_test.go +++ b/internal/commands/config_default_builder_test.go @@ -17,10 +17,9 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -46,7 +45,7 @@ func testConfigDefaultBuilder(t *testing.T, when spec.G, it spec.S) { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_experimental.go b/internal/commands/config_experimental.go index f4cedf9ede..0476b515e2 100644 --- a/internal/commands/config_experimental.go +++ b/internal/commands/config_experimental.go @@ -8,7 +8,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func ConfigExperimental(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { diff --git a/internal/commands/config_experimental_test.go b/internal/commands/config_experimental_test.go index b845668ff0..2d49cb43ff 100644 --- a/internal/commands/config_experimental_test.go +++ b/internal/commands/config_experimental_test.go @@ -15,9 +15,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -39,7 +38,7 @@ func testConfigExperimental(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_lifecycle_image.go b/internal/commands/config_lifecycle_image.go index 5997fe6e47..455db1ba23 100644 --- a/internal/commands/config_lifecycle_image.go +++ b/internal/commands/config_lifecycle_image.go @@ -7,7 +7,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func ConfigLifecycleImage(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { diff --git a/internal/commands/config_lifecycle_image_test.go b/internal/commands/config_lifecycle_image_test.go index c8ce0eddc8..71aba269fa 100644 --- a/internal/commands/config_lifecycle_image_test.go +++ b/internal/commands/config_lifecycle_image_test.go @@ -15,8 +15,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -39,7 +38,7 @@ func testConfigLifecycleImageCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configFile = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_pull_policy.go b/internal/commands/config_pull_policy.go index fa0d5413fa..ebeac05e67 100644 --- a/internal/commands/config_pull_policy.go +++ b/internal/commands/config_pull_policy.go @@ -8,8 +8,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) func ConfigPullPolicy(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { diff --git a/internal/commands/config_pull_policy_test.go b/internal/commands/config_pull_policy_test.go index 916ea3fefd..640ef6dee2 100644 --- a/internal/commands/config_pull_policy_test.go +++ b/internal/commands/config_pull_policy_test.go @@ -15,8 +15,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -39,7 +38,7 @@ func testConfigPullPolicyCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configFile = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_registries.go b/internal/commands/config_registries.go index 6f2aaeb5e8..905f331072 100644 --- a/internal/commands/config_registries.go +++ b/internal/commands/config_registries.go @@ -11,7 +11,7 @@ import ( "github.com/buildpacks/pack/internal/slices" "github.com/buildpacks/pack/internal/stringset" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/registry" ) diff --git a/internal/commands/config_registries_default.go b/internal/commands/config_registries_default.go index e60f5bc17d..9e25131680 100644 --- a/internal/commands/config_registries_default.go +++ b/internal/commands/config_registries_default.go @@ -8,7 +8,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func ConfigRegistriesDefault(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { diff --git a/internal/commands/config_registries_default_test.go b/internal/commands/config_registries_default_test.go index 15a7a458a8..4bcaee743f 100644 --- a/internal/commands/config_registries_default_test.go +++ b/internal/commands/config_registries_default_test.go @@ -14,8 +14,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -32,7 +32,7 @@ func testConfigRegistriesDefaultCommand(t *testing.T, when spec.G, it spec.S) { tmpDir string configFile string outBuf bytes.Buffer - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) assert = h.NewAssertionManager(t) ) diff --git a/internal/commands/config_registries_test.go b/internal/commands/config_registries_test.go index e9791d9a97..0c1aba1d7d 100644 --- a/internal/commands/config_registries_test.go +++ b/internal/commands/config_registries_test.go @@ -14,8 +14,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -39,7 +38,7 @@ func testConfigRegistries(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") assert.Nil(err) configPath = filepath.Join(tempPackHome, "config.toml") @@ -87,7 +86,7 @@ func testConfigRegistries(t *testing.T, when spec.G, it spec.S) { when("no args", func() { it("calls list", func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfgWithRegistries = config.Config{ DefaultRegistryName: "private registry", Registries: []config.Registry{ @@ -121,7 +120,7 @@ func testConfigRegistries(t *testing.T, when spec.G, it spec.S) { when("list", func() { var args = []string{"list"} it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cmd = commands.ConfigRegistries(logger, cfgWithRegistries, configPath) cmd.SetArgs(args) }) @@ -135,7 +134,7 @@ func testConfigRegistries(t *testing.T, when spec.G, it spec.S) { }) it("should list registries in verbose mode", func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger = logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) cmd = commands.ConfigRegistries(logger, cfgWithRegistries, configPath) cmd.SetArgs(args) assert.Nil(cmd.Execute()) diff --git a/internal/commands/config_registry_mirrors.go b/internal/commands/config_registry_mirrors.go index 11412f35e9..c2073c0901 100644 --- a/internal/commands/config_registry_mirrors.go +++ b/internal/commands/config_registry_mirrors.go @@ -9,7 +9,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) var registryMirror string diff --git a/internal/commands/config_registry_mirrors_test.go b/internal/commands/config_registry_mirrors_test.go index 7a7fc76df9..d882e85f3b 100644 --- a/internal/commands/config_registry_mirrors_test.go +++ b/internal/commands/config_registry_mirrors_test.go @@ -16,9 +16,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -49,7 +48,7 @@ func testConfigRegistryMirrorsCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_run_image_mirrors.go b/internal/commands/config_run_image_mirrors.go index cd4fce215e..530a07ac96 100644 --- a/internal/commands/config_run_image_mirrors.go +++ b/internal/commands/config_run_image_mirrors.go @@ -11,7 +11,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/stringset" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) var mirrors []string diff --git a/internal/commands/config_run_image_mirrors_test.go b/internal/commands/config_run_image_mirrors_test.go index 2d5fcd8fb2..d6fa9517ee 100644 --- a/internal/commands/config_run_image_mirrors_test.go +++ b/internal/commands/config_run_image_mirrors_test.go @@ -16,9 +16,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -56,7 +55,7 @@ func testConfigRunImageMirrorsCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_test.go b/internal/commands/config_test.go index 2e60dcd003..1f4ce9dc23 100644 --- a/internal/commands/config_test.go +++ b/internal/commands/config_test.go @@ -16,8 +16,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -43,7 +42,7 @@ func testConfigCommand(t *testing.T, when spec.G, it spec.S) { mockController := gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/config_trusted_builder.go b/internal/commands/config_trusted_builder.go index 46f4078bbe..d281a4fde4 100644 --- a/internal/commands/config_trusted_builder.go +++ b/internal/commands/config_trusted_builder.go @@ -9,7 +9,7 @@ import ( bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func ConfigTrustedBuilder(logger logging.Logger, cfg config.Config, cfgPath string) *cobra.Command { diff --git a/internal/commands/config_trusted_builder_test.go b/internal/commands/config_trusted_builder_test.go index e1a2f6c8d5..6a0e157135 100644 --- a/internal/commands/config_trusted_builder_test.go +++ b/internal/commands/config_trusted_builder_test.go @@ -15,9 +15,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -39,7 +38,7 @@ func testTrustedBuilderCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/create_builder.go b/internal/commands/create_builder.go index 8bb0248dc9..a713c32ea1 100644 --- a/internal/commands/create_builder.go +++ b/internal/commands/create_builder.go @@ -10,9 +10,9 @@ import ( "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use 'builder create' instead. diff --git a/internal/commands/create_builder_test.go b/internal/commands/create_builder_test.go index 84f0d0c6a7..9701bac94e 100644 --- a/internal/commands/create_builder_test.go +++ b/internal/commands/create_builder_test.go @@ -15,8 +15,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -47,7 +46,7 @@ func testCreateBuilderCommand(t *testing.T, when spec.G, it spec.S) { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) command = commands.CreateBuilder(logger, cfg, mockClient) }) diff --git a/internal/commands/fakes/fake_builder_writer.go b/internal/commands/fakes/fake_builder_writer.go index f7e2b7a2d0..a86d23f959 100644 --- a/internal/commands/fakes/fake_builder_writer.go +++ b/internal/commands/fakes/fake_builder_writer.go @@ -3,8 +3,8 @@ package fakes import ( "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type FakeBuilderWriter struct { diff --git a/internal/commands/fakes/fake_inspect_image_writer.go b/internal/commands/fakes/fake_inspect_image_writer.go index 7978ed5b0b..d1a12109ff 100644 --- a/internal/commands/fakes/fake_inspect_image_writer.go +++ b/internal/commands/fakes/fake_inspect_image_writer.go @@ -2,8 +2,8 @@ package fakes import ( "github.com/buildpacks/pack/internal/inspectimage" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) type FakeInspectImageWriter struct { diff --git a/internal/commands/inspect_builder.go b/internal/commands/inspect_builder.go index 8afa0e3fd6..5fd58352b8 100644 --- a/internal/commands/inspect_builder.go +++ b/internal/commands/inspect_builder.go @@ -6,8 +6,8 @@ import ( "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use builder inspect instead. diff --git a/internal/commands/inspect_builder_test.go b/internal/commands/inspect_builder_test.go index 9ab7d9e191..69f27cd7db 100644 --- a/internal/commands/inspect_builder_test.go +++ b/internal/commands/inspect_builder_test.go @@ -12,9 +12,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testInspectBuilderCommand(t *testing.T, when spec.G, it spec.S) { DefaultBuilder: "default/builder", RunImages: expectedLocalRunImages, } - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) when("InspectBuilder", func() { diff --git a/internal/commands/inspect_buildpack.go b/internal/commands/inspect_buildpack.go index 69d4d28c3c..91fb480267 100644 --- a/internal/commands/inspect_buildpack.go +++ b/internal/commands/inspect_buildpack.go @@ -11,13 +11,12 @@ import ( "github.com/pkg/errors" "github.com/spf13/cobra" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" strs "github.com/buildpacks/pack/internal/strings" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" ) const inspectBuildpackTemplate = ` @@ -132,7 +131,7 @@ func inspectBuildpackOutput(info *client.BuildpackInfo, prefix string, flags Bui err = tpl.Execute(buf, &struct { Location string - Metadata buildpackage.Metadata + Metadata buildpack.Metadata ListMixins bool Buildpacks string Order string diff --git a/internal/commands/inspect_buildpack_test.go b/internal/commands/inspect_buildpack_test.go index cdf74c8607..200290d0f6 100644 --- a/internal/commands/inspect_buildpack_test.go +++ b/internal/commands/inspect_buildpack_test.go @@ -13,16 +13,14 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -53,14 +51,14 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{ DefaultRegistry: "default-registry", } complexInfo = &client.BuildpackInfo{ - BuildpackMetadata: buildpackage.Metadata{ + BuildpackMetadata: buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", Version: "0.0.1", @@ -215,7 +213,7 @@ func testInspectBuildpackCommand(t *testing.T, when spec.G, it spec.S) { } simpleInfo = &client.BuildpackInfo{ - BuildpackMetadata: buildpackage.Metadata{ + BuildpackMetadata: buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/single-buildpack", Version: "0.0.1", diff --git a/internal/commands/inspect_image.go b/internal/commands/inspect_image.go index 5f858b55a8..45bc7b394f 100644 --- a/internal/commands/inspect_image.go +++ b/internal/commands/inspect_image.go @@ -8,7 +8,7 @@ import ( "github.com/buildpacks/pack/internal/inspectimage/writer" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) //go:generate mockgen -package testmocks -destination testmocks/mock_inspect_image_writer_factory.go github.com/buildpacks/pack/internal/commands InspectImageWriterFactory diff --git a/internal/commands/inspect_image_test.go b/internal/commands/inspect_image_test.go index 26276b887b..983b112a50 100644 --- a/internal/commands/inspect_image_test.go +++ b/internal/commands/inspect_image_test.go @@ -16,9 +16,8 @@ import ( "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -68,7 +67,7 @@ func testInspectImageCommand(t *testing.T, when spec.G, it spec.S) { cfg = config.Config{} mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) it.After(func() { diff --git a/internal/commands/list_registries.go b/internal/commands/list_registries.go index e1ccdd348c..5f5317021a 100644 --- a/internal/commands/list_registries.go +++ b/internal/commands/list_registries.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use config registries list instead diff --git a/internal/commands/list_registries_test.go b/internal/commands/list_registries_test.go index 96e27fa459..22bb12a957 100644 --- a/internal/commands/list_registries_test.go +++ b/internal/commands/list_registries_test.go @@ -14,8 +14,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func TestListRegistries(t *testing.T) { @@ -34,7 +33,7 @@ func testListRegistriesCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{ DefaultRegistryName: "private registry", Registries: []config.Registry{ @@ -70,7 +69,7 @@ func testListRegistriesCommand(t *testing.T, when spec.G, it spec.S) { }) it("should list registries in verbose mode", func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf, ilogging.WithVerbose()) + logger = logging.NewLogWithWriters(&outBuf, &outBuf, logging.WithVerbose()) command = commands.ListBuildpackRegistries(logger, cfg) command.SetArgs([]string{}) diff --git a/internal/commands/list_trusted_builders.go b/internal/commands/list_trusted_builders.go index 59d533e3f5..5dec6dc87f 100644 --- a/internal/commands/list_trusted_builders.go +++ b/internal/commands/list_trusted_builders.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `config trusted-builders list` instead diff --git a/internal/commands/list_trusted_builders_test.go b/internal/commands/list_trusted_builders_test.go index 1424205b99..c08a58bb21 100644 --- a/internal/commands/list_trusted_builders_test.go +++ b/internal/commands/list_trusted_builders_test.go @@ -13,8 +13,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -35,7 +34,7 @@ func testListTrustedBuildersCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) command = commands.ListTrustedBuilders(logger, config.Config{}) tempPackHome, err = ioutil.TempDir("", "pack-home") diff --git a/internal/commands/package_buildpack.go b/internal/commands/package_buildpack.go index 013962d5c2..5fa89e9a0b 100644 --- a/internal/commands/package_buildpack.go +++ b/internal/commands/package_buildpack.go @@ -9,9 +9,9 @@ import ( pubbldpkg "github.com/buildpacks/pack/buildpackage" "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: use BuildpackPackage instead diff --git a/internal/commands/package_buildpack_test.go b/internal/commands/package_buildpack_test.go index 26ea17117e..585d477edb 100644 --- a/internal/commands/package_buildpack_test.go +++ b/internal/commands/package_buildpack_test.go @@ -15,9 +15,9 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/fakes" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -32,7 +32,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("valid package config", func() { it("prints deprecation warning", func() { var outBuf bytes.Buffer - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) cmd := packageBuildpackCommand(withLogger(logger)) h.AssertNil(t, cmd.Execute()) h.AssertContains(t, outBuf.String(), "Warning: Command 'pack package-buildpack' has been deprecated, please use 'pack buildpack package' instead") @@ -98,7 +98,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) fakeBuildpackPackager = &fakes.FakeBuildpackPackager{} cmd = packageBuildpackCommand(withLogger(logger), withBuildpackPackager(fakeBuildpackPackager)) @@ -130,7 +130,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { h.AssertEq(t, receivedOptions.PullPolicy, image.PullAlways) }) it("takes precedence over a configured pull policy", func() { - logger := ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) + logger := logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) configReader := fakes.NewFakePackageConfigReader() buildpackPackager := &fakes.FakeBuildpackPackager{} clientConfig := config.Config{PullPolicy: "if-not-present"} @@ -152,7 +152,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { }) when("configured pull policy", func() { it("uses the configured pull policy", func() { - logger := ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) + logger := logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) configReader := fakes.NewFakePackageConfigReader() buildpackPackager := &fakes.FakeBuildpackPackager{} clientConfig := config.Config{PullPolicy: "never"} @@ -176,7 +176,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("invalid flags", func() { when("both --publish and --pull-policy never flags are specified", func() { it("errors with a descriptive message", func() { - logger := ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) + logger := logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) configReader := fakes.NewFakePackageConfigReader() buildpackPackager := &fakes.FakeBuildpackPackager{} clientConfig := config.Config{} @@ -201,7 +201,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { expectedErr := errors.New("it went wrong") packageBuildpackCommand := packageBuildpackCommand( - withLogger(ilogging.NewLogWithWriters(outBuf, outBuf)), + withLogger(logging.NewLogWithWriters(outBuf, outBuf)), withPackageConfigReader( fakes.NewFakePackageConfigReader(whereReadReturns(pubbldpkg.Config{}, expectedErr)), ), @@ -218,7 +218,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { outBuf := &bytes.Buffer{} config := &packageCommandConfig{ - logger: ilogging.NewLogWithWriters(outBuf, outBuf), + logger: logging.NewLogWithWriters(outBuf, outBuf), packageConfigReader: fakes.NewFakePackageConfigReader(), buildpackPackager: &fakes.FakeBuildpackPackager{}, @@ -237,7 +237,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("no config path is specified", func() { it("creates a default config", func() { config := &packageCommandConfig{ - logger: ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), + logger: logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), packageConfigReader: fakes.NewFakePackageConfigReader(), buildpackPackager: &fakes.FakeBuildpackPackager{}, @@ -257,7 +257,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { when("--pull-policy unknown-policy", func() { it("fails to run", func() { - logger := ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) + logger := logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}) configReader := fakes.NewFakePackageConfigReader() buildpackPackager := &fakes.FakeBuildpackPackager{} clientConfig := config.Config{} @@ -278,7 +278,7 @@ func testPackageBuildpackCommand(t *testing.T, when spec.G, it spec.S) { func packageBuildpackCommand(ops ...packageCommandOption) *cobra.Command { config := &packageCommandConfig{ - logger: ilogging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), + logger: logging.NewLogWithWriters(&bytes.Buffer{}, &bytes.Buffer{}), packageConfigReader: fakes.NewFakePackageConfigReader(), buildpackPackager: &fakes.FakeBuildpackPackager{}, clientConfig: config.Config{}, diff --git a/internal/commands/rebase.go b/internal/commands/rebase.go index 9912328852..21c56a1c7f 100644 --- a/internal/commands/rebase.go +++ b/internal/commands/rebase.go @@ -10,7 +10,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func Rebase(logger logging.Logger, cfg config.Config, pack PackClient) *cobra.Command { diff --git a/internal/commands/rebase_test.go b/internal/commands/rebase_test.go index 3a4e1fbcb0..b3a9b2a5cf 100644 --- a/internal/commands/rebase_test.go +++ b/internal/commands/rebase_test.go @@ -17,8 +17,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -40,7 +39,7 @@ func testRebaseCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{} mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) diff --git a/internal/commands/register_buildpack.go b/internal/commands/register_buildpack.go index fecb2e4ac9..08de68e5b6 100644 --- a/internal/commands/register_buildpack.go +++ b/internal/commands/register_buildpack.go @@ -7,7 +7,7 @@ import ( "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use BuildpackRegister instead diff --git a/internal/commands/register_buildpack_test.go b/internal/commands/register_buildpack_test.go index ef8e8b3656..f4060c1b64 100644 --- a/internal/commands/register_buildpack_test.go +++ b/internal/commands/register_buildpack_test.go @@ -14,8 +14,7 @@ import ( "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -34,7 +33,7 @@ func testRegisterBuildpackCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cfg = config.Config{} diff --git a/internal/commands/remove_registry.go b/internal/commands/remove_registry.go index f13bc5cecd..245ba2774e 100644 --- a/internal/commands/remove_registry.go +++ b/internal/commands/remove_registry.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use config registries remove instead diff --git a/internal/commands/remove_registry_test.go b/internal/commands/remove_registry_test.go index 9c3271eddf..7d185809f7 100644 --- a/internal/commands/remove_registry_test.go +++ b/internal/commands/remove_registry_test.go @@ -13,7 +13,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -28,7 +28,7 @@ func testRemoveRegistryCommand(t *testing.T, when spec.G, it spec.S) { when("#RemoveRegistry", func() { var ( outBuf bytes.Buffer - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tmpDir string configFile string cfg config.Config diff --git a/internal/commands/report.go b/internal/commands/report.go index 55ac13632b..535a34e211 100644 --- a/internal/commands/report.go +++ b/internal/commands/report.go @@ -15,7 +15,7 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func Report(logger logging.Logger, version, cfgPath string) *cobra.Command { diff --git a/internal/commands/report_test.go b/internal/commands/report_test.go index 503d431ba5..e69ad87596 100644 --- a/internal/commands/report_test.go +++ b/internal/commands/report_test.go @@ -13,8 +13,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/commands" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -35,7 +34,7 @@ func testReportCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) diff --git a/internal/commands/set_default_builder.go b/internal/commands/set_default_builder.go index d3a87d3437..a292e82e96 100644 --- a/internal/commands/set_default_builder.go +++ b/internal/commands/set_default_builder.go @@ -7,7 +7,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `pack config default-builder` diff --git a/internal/commands/set_default_builder_test.go b/internal/commands/set_default_builder_test.go index 6a5bcda872..b3606e660a 100644 --- a/internal/commands/set_default_builder_test.go +++ b/internal/commands/set_default_builder_test.go @@ -17,9 +17,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -42,7 +41,7 @@ func testSetDefaultBuilderCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) var err error tempPackHome, err = ioutil.TempDir("", "pack-home") diff --git a/internal/commands/set_default_registry.go b/internal/commands/set_default_registry.go index 7e9ab77ae6..4a3c1fffc5 100644 --- a/internal/commands/set_default_registry.go +++ b/internal/commands/set_default_registry.go @@ -6,7 +6,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `pack config registries default` instead diff --git a/internal/commands/set_default_registry_test.go b/internal/commands/set_default_registry_test.go index 578ce0f340..74cb44f982 100644 --- a/internal/commands/set_default_registry_test.go +++ b/internal/commands/set_default_registry_test.go @@ -13,7 +13,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -28,7 +28,7 @@ func testSetDefaultRegistryCommand(t *testing.T, when spec.G, it spec.S) { when("#SetDefaultRegistry", func() { var ( outBuf bytes.Buffer - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tmpDir string configFile string assert = h.NewAssertionManager(t) diff --git a/internal/commands/set_run_image_mirrors.go b/internal/commands/set_run_image_mirrors.go index 79f09a5697..31d480a7b2 100644 --- a/internal/commands/set_run_image_mirrors.go +++ b/internal/commands/set_run_image_mirrors.go @@ -5,7 +5,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `pack config run-image-mirrors add` instead diff --git a/internal/commands/set_run_image_mirrors_test.go b/internal/commands/set_run_image_mirrors_test.go index 34b81b1294..da20ca042d 100644 --- a/internal/commands/set_run_image_mirrors_test.go +++ b/internal/commands/set_run_image_mirrors_test.go @@ -13,8 +13,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -33,7 +32,7 @@ func testSetRunImageMirrorsCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) cfg = config.Config{} var err error tempPackHome, err = ioutil.TempDir("", "pack-home") diff --git a/internal/commands/stack.go b/internal/commands/stack.go index 3890e29791..fcfdfda05e 100644 --- a/internal/commands/stack.go +++ b/internal/commands/stack.go @@ -3,7 +3,7 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func NewStackCommand(logger logging.Logger) *cobra.Command { diff --git a/internal/commands/stack_suggest.go b/internal/commands/stack_suggest.go index e90bf316c0..ad57580304 100644 --- a/internal/commands/stack_suggest.go +++ b/internal/commands/stack_suggest.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) type suggestedStack struct { diff --git a/internal/commands/stack_suggest_test.go b/internal/commands/stack_suggest_test.go index a2e4086500..5fd1f1acec 100644 --- a/internal/commands/stack_suggest_test.go +++ b/internal/commands/stack_suggest_test.go @@ -8,7 +8,7 @@ import ( "github.com/sclevine/spec/report" "github.com/spf13/cobra" - "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/suggest_builders.go b/internal/commands/suggest_builders.go index 077fd657cc..0d8772ed92 100644 --- a/internal/commands/suggest_builders.go +++ b/internal/commands/suggest_builders.go @@ -10,7 +10,7 @@ import ( bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `builder suggest` instead. diff --git a/internal/commands/suggest_builders_test.go b/internal/commands/suggest_builders_test.go index b54ed13e25..6759e21de1 100644 --- a/internal/commands/suggest_builders_test.go +++ b/internal/commands/suggest_builders_test.go @@ -13,9 +13,8 @@ import ( bldr "github.com/buildpacks/pack/internal/builder" "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/commands/testmocks" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testSuggestBuildersCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) }) when("#WriteSuggestedBuilder", func() { diff --git a/internal/commands/suggest_stacks.go b/internal/commands/suggest_stacks.go index d5c7831f82..a2c6d0b65c 100644 --- a/internal/commands/suggest_stacks.go +++ b/internal/commands/suggest_stacks.go @@ -3,7 +3,7 @@ package commands import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `stack suggest` instead diff --git a/internal/commands/suggest_stacks_test.go b/internal/commands/suggest_stacks_test.go index 8cd03c811e..7b4444b839 100644 --- a/internal/commands/suggest_stacks_test.go +++ b/internal/commands/suggest_stacks_test.go @@ -10,7 +10,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/commands" - "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/trust_builder.go b/internal/commands/trust_builder.go index 9f8bc86e4e..a948eeef2f 100644 --- a/internal/commands/trust_builder.go +++ b/internal/commands/trust_builder.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `config trusted-builders add` instead diff --git a/internal/commands/trust_builder_test.go b/internal/commands/trust_builder_test.go index ed3952bb3b..993bde831a 100644 --- a/internal/commands/trust_builder_test.go +++ b/internal/commands/trust_builder_test.go @@ -14,8 +14,7 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -37,7 +36,7 @@ func testTrustBuilderCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) configPath = filepath.Join(tempPackHome, "config.toml") diff --git a/internal/commands/untrust_builder.go b/internal/commands/untrust_builder.go index f67800dc0e..0b4b29da99 100644 --- a/internal/commands/untrust_builder.go +++ b/internal/commands/untrust_builder.go @@ -4,7 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use `config trusted-builders remove` instead diff --git a/internal/commands/untrust_builder_test.go b/internal/commands/untrust_builder_test.go index 3cf6aa4e3d..5a04c02390 100644 --- a/internal/commands/untrust_builder_test.go +++ b/internal/commands/untrust_builder_test.go @@ -14,9 +14,8 @@ import ( "github.com/buildpacks/pack/internal/commands" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -38,7 +37,7 @@ func testUntrustBuilderCommand(t *testing.T, when spec.G, it spec.S) { it.Before(func() { var err error - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tempPackHome, err = ioutil.TempDir("", "pack-home") h.AssertNil(t, err) diff --git a/internal/commands/version.go b/internal/commands/version.go index cf81789938..0d0c7d91b5 100644 --- a/internal/commands/version.go +++ b/internal/commands/version.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) // Version shows the current pack version diff --git a/internal/commands/version_test.go b/internal/commands/version_test.go index e16fcea0e8..01ed6b6f8a 100644 --- a/internal/commands/version_test.go +++ b/internal/commands/version_test.go @@ -9,7 +9,7 @@ import ( "github.com/spf13/cobra" "github.com/buildpacks/pack/internal/commands" - "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/commands/yank_buildpack.go b/internal/commands/yank_buildpack.go index c6f79f3584..3e0aec021e 100644 --- a/internal/commands/yank_buildpack.go +++ b/internal/commands/yank_buildpack.go @@ -5,8 +5,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" ) // Deprecated: Use yank instead diff --git a/internal/commands/yank_buildpack_test.go b/internal/commands/yank_buildpack_test.go index 703968705e..352b560b7f 100644 --- a/internal/commands/yank_buildpack_test.go +++ b/internal/commands/yank_buildpack_test.go @@ -16,8 +16,7 @@ import ( "github.com/buildpacks/pack/internal/commands/testmocks" "github.com/buildpacks/pack/internal/config" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -38,7 +37,7 @@ func testYankBuildpackCommand(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) mockController = gomock.NewController(t) mockClient = testmocks.NewMockPackClient(mockController) cfg = config.Config{} diff --git a/internal/fakes/fake_buildpack.go b/internal/fakes/fake_buildpack.go index 7857aa17ae..ce4ce28c80 100644 --- a/internal/fakes/fake_buildpack.go +++ b/internal/fakes/fake_buildpack.go @@ -8,8 +8,9 @@ import ( "github.com/BurntSushi/toml" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" ) type fakeBuildpack struct { @@ -52,7 +53,7 @@ func WithOpenError(err error) FakeBuildpackOption { // build-contents // \_ /cnbs/buildpacks/{ID}/{version}/bin/detect // detect-contents -func NewFakeBuildpack(descriptor dist.BuildpackDescriptor, chmod int64, options ...FakeBuildpackOption) (dist.Buildpack, error) { +func NewFakeBuildpack(descriptor dist.BuildpackDescriptor, chmod int64, options ...FakeBuildpackOption) (buildpack.Buildpack, error) { return &fakeBuildpack{ descriptor: descriptor, chmod: chmod, diff --git a/internal/fakes/fake_buildpack_blob.go b/internal/fakes/fake_buildpack_blob.go index 9f1901ea2e..b15c792b76 100644 --- a/internal/fakes/fake_buildpack_blob.go +++ b/internal/fakes/fake_buildpack_blob.go @@ -7,8 +7,9 @@ import ( "github.com/BurntSushi/toml" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/dist" ) type fakeBuildpackBlob struct { @@ -24,7 +25,7 @@ type fakeBuildpackBlob struct { // build-contents // \_ bin/detect // detect-contents -func NewFakeBuildpackBlob(descriptor dist.BuildpackDescriptor, chmod int64) (dist.Blob, error) { +func NewFakeBuildpackBlob(descriptor dist.BuildpackDescriptor, chmod int64) (blob.Blob, error) { return &fakeBuildpackBlob{ descriptor: descriptor, chmod: chmod, diff --git a/internal/fakes/fake_buildpack_tar.go b/internal/fakes/fake_buildpack_tar.go index d08a5c63d4..aa6b1bf2d6 100644 --- a/internal/fakes/fake_buildpack_tar.go +++ b/internal/fakes/fake_buildpack_tar.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "testing" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/fakes/fake_images.go b/internal/fakes/fake_images.go index 97ab28c04e..5057968c45 100644 --- a/internal/fakes/fake_images.go +++ b/internal/fakes/fake_images.go @@ -11,8 +11,8 @@ import ( "github.com/buildpacks/imgutil/fakes" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/fakes/fake_package.go b/internal/fakes/fake_package.go index 1b6e1702e3..88ced915d8 100644 --- a/internal/fakes/fake_package.go +++ b/internal/fakes/fake_package.go @@ -8,7 +8,8 @@ import ( "github.com/google/go-containerregistry/pkg/v1/tarball" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" ) type Package interface { @@ -25,9 +26,9 @@ type fakePackage struct { bpLayers dist.BuildpackLayers } -func NewPackage(tmpDir string, name string, buildpacks []dist.Buildpack) (Package, error) { - processBuildpack := func(bp dist.Buildpack) (tarFile string, diffID string, err error) { - tarFile, err = dist.BuildpackToLayerTar(tmpDir, bp) +func NewPackage(tmpDir string, name string, buildpacks []buildpack.Buildpack) (Package, error) { + processBuildpack := func(bp buildpack.Buildpack) (tarFile string, diffID string, err error) { + tarFile, err = buildpack.BuildpackToLayerTar(tmpDir, bp) if err != nil { return "", "", err } diff --git a/internal/inspectimage/bom_display.go b/internal/inspectimage/bom_display.go index b0c1efdc4d..9a438ae916 100644 --- a/internal/inspectimage/bom_display.go +++ b/internal/inspectimage/bom_display.go @@ -3,8 +3,8 @@ package inspectimage import ( "github.com/buildpacks/lifecycle/buildpack" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" ) type BOMDisplay struct { diff --git a/internal/inspectimage/info_display.go b/internal/inspectimage/info_display.go index 06a0e557d6..ca6fb15c77 100644 --- a/internal/inspectimage/info_display.go +++ b/internal/inspectimage/info_display.go @@ -6,8 +6,8 @@ import ( "github.com/buildpacks/lifecycle/platform" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" ) type GeneralInfo struct { diff --git a/internal/inspectimage/writer/bom_json_test.go b/internal/inspectimage/writer/bom_json_test.go index 3ec2d4291c..4a786b779a 100644 --- a/internal/inspectimage/writer/bom_json_test.go +++ b/internal/inspectimage/writer/bom_json_test.go @@ -11,8 +11,8 @@ import ( "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -131,7 +131,7 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { it("prints both local and remote image info in a JSON format", func() { jsonBOMWriter := writer.NewJSONBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonBOMWriter.Print(logger, inspectimage.GeneralInfo{}, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -144,7 +144,7 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { it("prints local image info in JSON format", func() { jsonBOMWriter := writer.NewJSONBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonBOMWriter.Print(logger, inspectimage.GeneralInfo{}, localInfo, nil, nil, nil) assert.Nil(err) @@ -159,7 +159,7 @@ func testJSONBOM(t *testing.T, when spec.G, it spec.S) { it("prints remote image info in JSON format", func() { jsonBOMWriter := writer.NewJSONBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonBOMWriter.Print(logger, inspectimage.GeneralInfo{}, nil, remoteInfo, nil, nil) assert.Nil(err) diff --git a/internal/inspectimage/writer/bom_yaml_test.go b/internal/inspectimage/writer/bom_yaml_test.go index 5c7478f02e..540c88b004 100644 --- a/internal/inspectimage/writer/bom_yaml_test.go +++ b/internal/inspectimage/writer/bom_yaml_test.go @@ -11,8 +11,8 @@ import ( "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -117,7 +117,7 @@ remote: it("prints both local and remote image info in a YAML format", func() { yamlBOMWriter := writer.NewYAMLBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlBOMWriter.Print(logger, inspectimage.GeneralInfo{}, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -130,7 +130,7 @@ remote: it("prints local image info in YAML format", func() { yamlBOMWriter := writer.NewYAMLBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlBOMWriter.Print(logger, inspectimage.GeneralInfo{}, localInfo, nil, nil, nil) assert.Nil(err) @@ -145,7 +145,7 @@ remote: it("prints remote image info in YAML format", func() { yamlBOMWriter := writer.NewYAMLBOM() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlBOMWriter.Print(logger, inspectimage.GeneralInfo{}, nil, remoteInfo, nil, nil) assert.Nil(err) diff --git a/internal/inspectimage/writer/factory.go b/internal/inspectimage/writer/factory.go index 79bc3219f4..279a54679d 100644 --- a/internal/inspectimage/writer/factory.go +++ b/internal/inspectimage/writer/factory.go @@ -6,7 +6,7 @@ import ( "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/pkg/client" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/internal/style" ) diff --git a/internal/inspectimage/writer/human_readable.go b/internal/inspectimage/writer/human_readable.go index e1f3024ee1..517330b10f 100644 --- a/internal/inspectimage/writer/human_readable.go +++ b/internal/inspectimage/writer/human_readable.go @@ -12,7 +12,7 @@ import ( strs "github.com/buildpacks/pack/internal/strings" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) type HumanReadable struct{} diff --git a/internal/inspectimage/writer/human_readable_test.go b/internal/inspectimage/writer/human_readable_test.go index 98b77153f2..1ed456b9bc 100644 --- a/internal/inspectimage/writer/human_readable_test.go +++ b/internal/inspectimage/writer/human_readable_test.go @@ -16,8 +16,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -224,7 +224,7 @@ Processes: } humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -255,7 +255,7 @@ Processes: } humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, localInfo, nil, nil, nil) assert.Nil(err) @@ -286,7 +286,7 @@ Processes: } humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) @@ -306,7 +306,7 @@ Processes: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) @@ -326,7 +326,7 @@ Processes: humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) @@ -362,7 +362,7 @@ Processes: } humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, nil, remoteErr) assert.Nil(err) @@ -397,7 +397,7 @@ Processes: } humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, localErr, nil) assert.Nil(err) @@ -411,7 +411,7 @@ Processes: it("displays a 'missing image' error message", func() { humanReadableWriter := writer.NewHumanReadable() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := humanReadableWriter.Print(logger, inspectimage.GeneralInfo{Name: "missing-image"}, nil, nil, nil, nil) assert.ErrorWithMessage(err, fmt.Sprintf("unable to find image '%s' locally or remotely", "missing-image")) }) diff --git a/internal/inspectimage/writer/json_test.go b/internal/inspectimage/writer/json_test.go index 73107791b8..1944d05f00 100644 --- a/internal/inspectimage/writer/json_test.go +++ b/internal/inspectimage/writer/json_test.go @@ -14,8 +14,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -291,7 +291,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { } jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -323,7 +323,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { } jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, sharedImageInfo, localInfo, nil, nil, nil) assert.Nil(err) @@ -357,7 +357,7 @@ func testJSON(t *testing.T, when spec.G, it spec.S) { } jsonWriter := writer.NewJSON() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := jsonWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) diff --git a/internal/inspectimage/writer/structured_bom_format.go b/internal/inspectimage/writer/structured_bom_format.go index e2d246ad26..a7069274dd 100644 --- a/internal/inspectimage/writer/structured_bom_format.go +++ b/internal/inspectimage/writer/structured_bom_format.go @@ -8,7 +8,7 @@ import ( "github.com/buildpacks/pack/internal/inspectimage" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) type StructuredBOMFormat struct { diff --git a/internal/inspectimage/writer/structured_bom_format_test.go b/internal/inspectimage/writer/structured_bom_format_test.go index a5732c0ed8..12837e4cab 100644 --- a/internal/inspectimage/writer/structured_bom_format_test.go +++ b/internal/inspectimage/writer/structured_bom_format_test.go @@ -12,11 +12,11 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -34,13 +34,13 @@ func testStructuredBOMFormat(t *testing.T, when spec.G, it spec.S) { remoteInfo *client.ImageInfo localInfo *client.ImageInfo generalInfo inspectimage.GeneralInfo - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters ) when("Print", func() { it.Before(func() { outBuf = bytes.NewBuffer(nil) - logger = ilogging.NewLogWithWriters(outBuf, outBuf) + logger = logging.NewLogWithWriters(outBuf, outBuf) remoteInfo = &client.ImageInfo{ BOM: []buildpack.BOMEntry{ { diff --git a/internal/inspectimage/writer/structured_format.go b/internal/inspectimage/writer/structured_format.go index 40526ea7d0..dd49d17d46 100644 --- a/internal/inspectimage/writer/structured_format.go +++ b/internal/inspectimage/writer/structured_format.go @@ -7,7 +7,7 @@ import ( "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) type StructuredFormat struct { diff --git a/internal/inspectimage/writer/structured_format_test.go b/internal/inspectimage/writer/structured_format_test.go index dfc68a1f1d..f6e64f7fb2 100644 --- a/internal/inspectimage/writer/structured_format_test.go +++ b/internal/inspectimage/writer/structured_format_test.go @@ -13,8 +13,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -53,7 +53,7 @@ func testStructuredFormat(t *testing.T, when spec.G, it spec.S) { MarshalFunc: testMarshalFunc, } - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := structuredWriter.Print(logger, sharedImageInfo, nil, nil, nil, nil) assert.ErrorWithMessage(err, fmt.Sprintf("unable to find image '%s' locally or remotely", "missing-image")) }) @@ -70,7 +70,7 @@ func testStructuredFormat(t *testing.T, when spec.G, it spec.S) { localErr := errors.New("a local error occurred") - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := structuredWriter.Print(logger, sharedImageInfo, nil, remoteInfo, localErr, nil) assert.ErrorWithMessage(err, "preparing output for 'localErr-image': a local error occurred") }) @@ -88,7 +88,7 @@ func testStructuredFormat(t *testing.T, when spec.G, it spec.S) { remoteErr := errors.New("a remote error occurred") - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := structuredWriter.Print(logger, sharedImageInfo, localInfo, nil, nil, remoteErr) assert.ErrorWithMessage(err, "preparing output for 'remoteErr-image': a remote error occurred") }) diff --git a/internal/inspectimage/writer/toml_test.go b/internal/inspectimage/writer/toml_test.go index 341436a56a..39cf213b4c 100644 --- a/internal/inspectimage/writer/toml_test.go +++ b/internal/inspectimage/writer/toml_test.go @@ -14,8 +14,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -277,7 +277,7 @@ args = [ } tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -309,7 +309,7 @@ args = [ } tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, sharedImageInfo, localInfo, nil, nil, nil) assert.Nil(err) @@ -341,7 +341,7 @@ args = [ } tomlWriter := writer.NewTOML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := tomlWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) diff --git a/internal/inspectimage/writer/yaml_test.go b/internal/inspectimage/writer/yaml_test.go index 814a1b674b..0ce95a08c3 100644 --- a/internal/inspectimage/writer/yaml_test.go +++ b/internal/inspectimage/writer/yaml_test.go @@ -14,8 +14,8 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/inspectimage" "github.com/buildpacks/pack/internal/inspectimage/writer" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -245,7 +245,7 @@ remote_info: } yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, sharedImageInfo, localInfo, remoteInfo, nil, nil) assert.Nil(err) @@ -277,7 +277,7 @@ remote_info: } yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, sharedImageInfo, localInfo, nil, nil, nil) assert.Nil(err) @@ -311,7 +311,7 @@ remote_info: } yamlWriter := writer.NewYAML() - logger := ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger := logging.NewLogWithWriters(&outBuf, &outBuf) err := yamlWriter.Print(logger, sharedImageInfo, nil, remoteInfo, nil, nil) assert.Nil(err) diff --git a/internal/logging/log_writer.go b/internal/logging/log_writer.go deleted file mode 100644 index e35f19abfe..0000000000 --- a/internal/logging/log_writer.go +++ /dev/null @@ -1,73 +0,0 @@ -package logging - -import ( - "fmt" - "io" - "regexp" - "sync" - "time" - - "github.com/heroku/color" -) - -// LogWriter is a writer used for logs -type LogWriter struct { - sync.Mutex - out io.Writer - clock func() time.Time - wantTime bool - wantNoColor bool -} - -var colorCodeMatcher = regexp.MustCompile(`\x1b\[[0-9;]*m`) - -// NewLogWriter creates a LogWriter -func NewLogWriter(writer io.Writer, clock func() time.Time, wantTime bool) *LogWriter { - wantNoColor := !color.Enabled() - return &LogWriter{ - out: writer, - clock: clock, - wantTime: wantTime, - wantNoColor: wantNoColor, - } -} - -// Write writes a message prepended by the time to the set io.Writer -func (tw *LogWriter) Write(buf []byte) (n int, err error) { - tw.Lock() - defer tw.Unlock() - - length := len(buf) - if tw.wantNoColor { - buf = stripColor(buf) - } - - prefix := "" - if tw.wantTime { - prefix = fmt.Sprintf("%s ", tw.clock().Format(timeFmt)) - } - - _, err = fmt.Fprintf(tw.out, "%s%s", prefix, buf) - return length, err -} - -// Fd returns the file descriptor of the writer. This is used to ensure it is a Console, and can therefore display streams of text -func (tw *LogWriter) Fd() uintptr { - tw.Lock() - defer tw.Unlock() - - if file, ok := tw.out.(hasDescriptor); ok { - return file.Fd() - } - - return InvalidFileDescriptor -} - -// Remove all ANSI color information. -func stripColor(b []byte) []byte { - return colorCodeMatcher.ReplaceAll(b, []byte("")) -} - -type hasDescriptor interface { - Fd() uintptr -} diff --git a/internal/logging/log_writer_test.go b/internal/logging/log_writer_test.go deleted file mode 100644 index fba0cedea4..0000000000 --- a/internal/logging/log_writer_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package logging_test - -import ( - "bytes" - "io/ioutil" - "testing" - "time" - - "github.com/heroku/color" - "github.com/sclevine/spec" - "github.com/sclevine/spec/report" - - ilogging "github.com/buildpacks/pack/internal/logging" - h "github.com/buildpacks/pack/testhelpers" -) - -const ( - timeFmt = "2006/01/02 15:04:05.000000" - testTime = "2019/05/15 01:01:01.000000" -) - -func TestLogWriter(t *testing.T) { - spec.Run(t, "LogWriter", testLogWriter, spec.Sequential(), spec.Report(report.Terminal{})) -} - -func testLogWriter(t *testing.T, when spec.G, it spec.S) { - var ( - writer *ilogging.LogWriter - outCons *color.Console - fOut func() string - - clockFunc = func() time.Time { - clock, _ := time.Parse(timeFmt, testTime) - return clock - } - ) - - it.Before(func() { - outCons, fOut = h.MockWriterAndOutput() - }) - - when("wantTime is true", func() { - it("has time", func() { - writer = ilogging.NewLogWriter(outCons, clockFunc, true) - writer.Write([]byte("test\n")) - h.AssertEq(t, fOut(), "2019/05/15 01:01:01.000000 test\n") - }) - }) - - when("wantTime is false", func() { - it("doesn't have time", func() { - writer = ilogging.NewLogWriter(outCons, clockFunc, false) - writer.Write([]byte("test\n")) - h.AssertEq(t, fOut(), "test\n") - }) - }) - - when("#Fd", func() { - when("out is a file", func() { - it("returns a Fd", func() { - file, err := ioutil.TempFile("", "testFile") - h.AssertNil(t, err) - writer = ilogging.NewLogWriter(file, clockFunc, false) - h.AssertNotEq(t, int(writer.Fd()), 0) - }) - }) - - when("out is just a Writer", func() { - it("returns the invalid file descriptor", func() { - var out *bytes.Buffer - writer = ilogging.NewLogWriter(out, clockFunc, true) - h.AssertEq(t, writer.Fd(), ilogging.InvalidFileDescriptor) - }) - }) - }) - - when("color is enabled", func() { - it("doesn't strip color", func() { - color.Disable(false) - - writer = ilogging.NewLogWriter(outCons, clockFunc, false) - writer.Write([]byte(color.HiBlueString(("test")))) - h.AssertEq(t, fOut(), "\x1b[94mtest\x1b[0m") - }) - }) - - when("color is disabled", func() { - it("strips color out", func() { - color.Disable(true) - defer color.Disable(false) - - writer = ilogging.NewLogWriter(outCons, clockFunc, false) - writer.Write([]byte(color.HiBlueString(("test")))) - - output := fOut() - h.AssertEq(t, output, "test") - h.AssertNotEq(t, output, "\x1b[94mtest\x1b[0m") - }) - - it("doesn't strip time out", func() { - color.Disable(true) - defer color.Disable(false) - - writer = ilogging.NewLogWriter(outCons, clockFunc, true) - writer.Write([]byte(color.HiBlueString(("test")))) - - output := fOut() - h.AssertEq(t, output, "2019/05/15 01:01:01.000000 test") - }) - }) -} diff --git a/internal/name/name.go b/internal/name/name.go index cdc36183e1..c840da5fe6 100644 --- a/internal/name/name.go +++ b/internal/name/name.go @@ -6,10 +6,13 @@ import ( gname "github.com/google/go-containerregistry/pkg/name" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" ) -func TranslateRegistry(name string, registryMirrors map[string]string, logger logging.Logger) (string, error) { +type Logger interface { + Infof(fmt string, v ...interface{}) +} + +func TranslateRegistry(name string, registryMirrors map[string]string, logger Logger) (string, error) { if registryMirrors == nil { return name, nil } diff --git a/internal/name/name_test.go b/internal/name/name_test.go index 57ecec480d..bbadb4120f 100644 --- a/internal/name/name_test.go +++ b/internal/name/name_test.go @@ -8,7 +8,7 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/name" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -19,7 +19,7 @@ func TestTranslateRegistry(t *testing.T) { func testTranslateRegistry(t *testing.T, when spec.G, it spec.S) { var ( assert = h.NewAssertionManager(t) - logger = logging.New(ioutil.Discard) + logger = logging.NewSimpleLogger(ioutil.Discard) ) when("#TranslateRegistry", func() { diff --git a/internal/registry/git_test.go b/internal/registry/git_test.go index 91dc57d6e4..63bb4645fd 100644 --- a/internal/registry/git_test.go +++ b/internal/registry/git_test.go @@ -11,9 +11,8 @@ import ( "github.com/sclevine/spec/report" "gopkg.in/src-d/go-git.v4" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -33,7 +32,7 @@ func testGit(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tmpDir, err = ioutil.TempDir("", "registry") h.AssertNil(t, err) diff --git a/internal/registry/registry_cache.go b/internal/registry/registry_cache.go index 86f5d232d8..95c9862c61 100644 --- a/internal/registry/registry_cache.go +++ b/internal/registry/registry_cache.go @@ -18,9 +18,9 @@ import ( "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing/object" - "github.com/buildpacks/pack/internal/buildpack" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/logging" ) const DefaultRegistryURL = "https://github.com/buildpacks/registry-index" diff --git a/internal/registry/registry_cache_test.go b/internal/registry/registry_cache_test.go index 8b13e8f8a2..3bb0e9cc4e 100644 --- a/internal/registry/registry_cache_test.go +++ b/internal/registry/registry_cache_test.go @@ -16,8 +16,7 @@ import ( "gopkg.in/src-d/go-git.v4" "gopkg.in/src-d/go-git.v4/plumbing/object" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testRegistryCache(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) tmpDir, err = ioutil.TempDir("", "registry") h.AssertNil(t, err) diff --git a/internal/stack/merge.go b/internal/stack/merge.go index 7eb9b4321f..854e96362f 100644 --- a/internal/stack/merge.go +++ b/internal/stack/merge.go @@ -3,8 +3,8 @@ package stack import ( "sort" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/stringset" + "github.com/buildpacks/pack/pkg/dist" ) // MergeCompatible determines the allowable set of stacks that a combination of buildpacks may run on, given each diff --git a/internal/stack/merge_test.go b/internal/stack/merge_test.go index 6a9eb875e3..17e185097d 100644 --- a/internal/stack/merge_test.go +++ b/internal/stack/merge_test.go @@ -6,8 +6,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/stack" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/term/term.go b/internal/term/term.go new file mode 100644 index 0000000000..04a246e783 --- /dev/null +++ b/internal/term/term.go @@ -0,0 +1,25 @@ +package term + +import ( + "io" + + "golang.org/x/term" +) + +// InvalidFileDescriptor based on https://golang.org/src/os/file_unix.go?s=2183:2210#L57 +const InvalidFileDescriptor = ^(uintptr(0)) + +// IsTerminal returns whether a writer is a terminal +func IsTerminal(w io.Writer) (uintptr, bool) { + if f, ok := w.(hasDescriptor); ok { + termFd := f.Fd() + isTerm := term.IsTerminal(int(termFd)) + return termFd, isTerm + } + + return InvalidFileDescriptor, false +} + +type hasDescriptor interface { + Fd() uintptr +} diff --git a/internal/term/term_test.go b/internal/term/term_test.go new file mode 100644 index 0000000000..e278f1206f --- /dev/null +++ b/internal/term/term_test.go @@ -0,0 +1,39 @@ +package term_test + +import ( + "bytes" + "os" + "testing" + + "github.com/sclevine/spec" + "github.com/sclevine/spec/report" + + "github.com/buildpacks/pack/internal/term" + h "github.com/buildpacks/pack/testhelpers" +) + +const ( + testTime = "2019/05/15 01:01:01.000000" +) + +func TestTerm(t *testing.T) { + spec.Run(t, "Term", testTerm, spec.Parallel(), spec.Report(report.Terminal{})) +} + +func testTerm(t *testing.T, when spec.G, it spec.S) { + + when("#IsTerminal", func() { + it("returns false for a pipe", func() { + r, _, _ := os.Pipe() + fd, isTerm := term.IsTerminal(r) + h.AssertFalse(t, isTerm) + h.AssertNotEq(t, fd, term.InvalidFileDescriptor) //The mock writer is a pipe, and therefore has a file descriptor + }) + + it("returns InvalidFileDescriptor if passed a normal Writer", func() { + fd, isTerm := term.IsTerminal(&bytes.Buffer{}) + h.AssertFalse(t, isTerm) + h.AssertEq(t, fd, term.InvalidFileDescriptor) + }) + }) +} diff --git a/pkg/blob/downloader.go b/pkg/blob/downloader.go index fe9b5ead37..1f5e9e5918 100644 --- a/pkg/blob/downloader.go +++ b/pkg/blob/downloader.go @@ -16,7 +16,6 @@ import ( "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" ) const ( @@ -24,19 +23,29 @@ const ( cacheVersion = "2" ) -type Downloader struct { - logger logging.Logger +type Logger interface { + Debugf(fmt string, v ...interface{}) + Infof(fmt string, v ...interface{}) + Writer() io.Writer +} + +type Downloader interface { + Download(ctx context.Context, pathOrURI string) (Blob, error) +} + +type downloader struct { + logger Logger baseCacheDir string } -func NewDownloader(logger logging.Logger, baseCacheDir string) *Downloader { //nolint:golint,gosimple - return &Downloader{ +func NewDownloader(logger Logger, baseCacheDir string) Downloader { + return &downloader{ logger: logger, baseCacheDir: baseCacheDir, } } -func (d *Downloader) Download(ctx context.Context, pathOrURI string) (Blob, error) { +func (d *downloader) Download(ctx context.Context, pathOrURI string) (Blob, error) { if paths.IsURI(pathOrURI) { parsedURL, err := url.Parse(pathOrURI) if err != nil { @@ -64,7 +73,7 @@ func (d *Downloader) Download(ctx context.Context, pathOrURI string) (Blob, erro return &blob{path: path}, nil } -func (d *Downloader) handleFile(path string) string { +func (d *downloader) handleFile(path string) string { path, err := filepath.Abs(path) if err != nil { return "" @@ -73,7 +82,7 @@ func (d *Downloader) handleFile(path string) string { return path } -func (d *Downloader) handleHTTP(ctx context.Context, uri string) (string, error) { +func (d *downloader) handleHTTP(ctx context.Context, uri string) (string, error) { cacheDir := d.versionedCacheDir() if err := os.MkdirAll(cacheDir, 0750); err != nil { @@ -123,7 +132,7 @@ func (d *Downloader) handleHTTP(ctx context.Context, uri string) (string, error) return cachePath, nil } -func (d *Downloader) downloadAsStream(ctx context.Context, uri string, etag string) (io.ReadCloser, string, error) { +func (d *downloader) downloadAsStream(ctx context.Context, uri string, etag string) (io.ReadCloser, string, error) { req, err := http.NewRequest("GET", uri, nil) if err != nil { return nil, "", err @@ -141,7 +150,7 @@ func (d *Downloader) downloadAsStream(ctx context.Context, uri string, etag stri if resp.StatusCode >= 200 && resp.StatusCode < 300 { d.logger.Infof("Downloading from %s", style.Symbol(uri)) - return withProgress(logging.GetWriterForLevel(d.logger, logging.InfoLevel), resp.Body, resp.ContentLength), resp.Header.Get("Etag"), nil + return withProgress(d.logger.Writer(), resp.Body, resp.ContentLength), resp.Header.Get("Etag"), nil } if resp.StatusCode == 304 { @@ -171,7 +180,7 @@ type progressReader struct { io.Closer } -func (d *Downloader) versionedCacheDir() string { +func (d *downloader) versionedCacheDir() string { return filepath.Join(d.baseCacheDir, cacheDirPrefix+cacheVersion) } diff --git a/pkg/blob/downloader_test.go b/pkg/blob/downloader_test.go index 2415d146b4..a2deccfa76 100644 --- a/pkg/blob/downloader_test.go +++ b/pkg/blob/downloader_test.go @@ -2,6 +2,8 @@ package blob_test import ( "context" + "fmt" + "io" "io/ioutil" "net/http" "os" @@ -14,7 +16,6 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/paths" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" h "github.com/buildpacks/pack/testhelpers" @@ -31,13 +32,13 @@ func testDownloader(t *testing.T, when spec.G, it spec.S) { var ( cacheDir string err error - subject *blob.Downloader + subject blob.Downloader ) it.Before(func() { cacheDir, err = ioutil.TempDir("", "cache") h.AssertNil(t, err) - subject = blob.NewDownloader(logging.New(ioutil.Discard), cacheDir) + subject = blob.NewDownloader(&logger{io.Discard}, cacheDir) }) it.After(func() { @@ -172,3 +173,19 @@ func assertBlob(t *testing.T, b blob.Blob) { h.AssertEq(t, string(bytes), "contents") } + +type logger struct { + writer io.Writer +} + +func (l *logger) Debugf(format string, v ...interface{}) { + fmt.Fprintln(l.writer, format, v) +} + +func (l *logger) Infof(format string, v ...interface{}) { + fmt.Fprintln(l.writer, format, v) +} + +func (l *logger) Writer() io.Writer { + return l.writer +} diff --git a/internal/buildpackage/builder.go b/pkg/buildpack/builder.go similarity index 93% rename from internal/buildpackage/builder.go rename to pkg/buildpack/builder.go index f893b52f98..0d9fa44a3f 100644 --- a/internal/buildpackage/builder.go +++ b/pkg/buildpack/builder.go @@ -1,4 +1,4 @@ -package buildpackage +package buildpack import ( "archive/tar" @@ -16,10 +16,10 @@ import ( "github.com/google/go-containerregistry/pkg/v1/tarball" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/stack" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/dist" ) type ImageFactory interface { @@ -62,22 +62,23 @@ func (i *layoutImage) AddLayerWithDiffID(path, _ string) error { } type PackageBuilder struct { - buildpack dist.Buildpack - dependencies []dist.Buildpack + buildpack Buildpack + dependencies []Buildpack imageFactory ImageFactory } +// TODO: Rename to PackageBuilder func NewBuilder(imageFactory ImageFactory) *PackageBuilder { return &PackageBuilder{ imageFactory: imageFactory, } } -func (b *PackageBuilder) SetBuildpack(buildpack dist.Buildpack) { +func (b *PackageBuilder) SetBuildpack(buildpack Buildpack) { b.buildpack = buildpack } -func (b *PackageBuilder) AddDependency(buildpack dist.Buildpack) { +func (b *PackageBuilder) AddDependency(buildpack Buildpack) { b.dependencies = append(b.dependencies, buildpack) } @@ -91,7 +92,7 @@ func (b *PackageBuilder) finalizeImage(image WorkableImage, tmpDir string) error bpLayers := dist.BuildpackLayers{} for _, bp := range append(b.dependencies, b.buildpack) { - bpLayerTar, err := dist.BuildpackToLayerTar(tmpDir, bp) + bpLayerTar, err := BuildpackToLayerTar(tmpDir, bp) if err != nil { return err } @@ -256,14 +257,14 @@ func (b *PackageBuilder) SaveAsImage(repoName string, publish bool, imageOS stri return image, nil } -func validateBuildpacks(mainBP dist.Buildpack, depBPs []dist.Buildpack) error { +func validateBuildpacks(mainBP Buildpack, depBPs []Buildpack) error { depsWithRefs := map[string][]dist.BuildpackInfo{} for _, bp := range depBPs { depsWithRefs[bp.Descriptor().Info.FullName()] = nil } - for _, bp := range append([]dist.Buildpack{mainBP}, depBPs...) { // List of everything + for _, bp := range append([]Buildpack{mainBP}, depBPs...) { // List of everything bpd := bp.Descriptor() for _, orderEntry := range bpd.Order { for _, groupEntry := range orderEntry.Group { diff --git a/internal/buildpackage/builder_test.go b/pkg/buildpack/builder_test.go similarity index 91% rename from internal/buildpackage/builder_test.go rename to pkg/buildpack/builder_test.go index bd930fc4a4..4064e98af1 100644 --- a/internal/buildpackage/builder_test.go +++ b/pkg/buildpack/builder_test.go @@ -1,4 +1,4 @@ -package buildpackage_test +package buildpack_test import ( "archive/tar" @@ -22,9 +22,9 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -70,20 +70,20 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { for _, _test := range []*struct { name string expectedImageOS string - fn func(*buildpackage.PackageBuilder) error + fn func(*buildpack.PackageBuilder) error }{ - {name: "SaveAsImage", expectedImageOS: "linux", fn: func(builder *buildpackage.PackageBuilder) error { + {name: "SaveAsImage", expectedImageOS: "linux", fn: func(builder *buildpack.PackageBuilder) error { _, err := builder.SaveAsImage("some/package", false, "linux") return err }}, - {name: "SaveAsImage", expectedImageOS: "windows", fn: func(builder *buildpackage.PackageBuilder) error { + {name: "SaveAsImage", expectedImageOS: "windows", fn: func(builder *buildpack.PackageBuilder) error { _, err := builder.SaveAsImage("some/package", false, "windows") return err }}, - {name: "SaveAsFile", expectedImageOS: "linux", fn: func(builder *buildpackage.PackageBuilder) error { + {name: "SaveAsFile", expectedImageOS: "linux", fn: func(builder *buildpack.PackageBuilder) error { return builder.SaveAsFile(path.Join(tmpDir, "package.cnb"), "linux") }}, - {name: "SaveAsFile", expectedImageOS: "windows", fn: func(builder *buildpackage.PackageBuilder) error { + {name: "SaveAsFile", expectedImageOS: "windows", fn: func(builder *buildpack.PackageBuilder) error { return builder.SaveAsFile(path.Join(tmpDir, "package.cnb"), "windows") }}, } { @@ -98,7 +98,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { when("validate buildpack", func() { when("buildpack not set", func() { it("returns error", func() { - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) err := testFn(builder) h.AssertError(t, err, "buildpack must be set") }) @@ -116,7 +116,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) builder.SetBuildpack(bp1) bp2, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ @@ -150,7 +150,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) builder.SetBuildpack(mainBP) presentBP, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ @@ -182,7 +182,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }}, }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) builder.SetBuildpack(mainBP) presentBP, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ @@ -206,7 +206,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { when("validate stacks", func() { when("buildpack is meta-buildpack", func() { it("should succeed", func() { - buildpack, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ + bp, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), Info: dist.BuildpackInfo{ ID: "bp.1.id", @@ -221,8 +221,8 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) - builder.SetBuildpack(buildpack) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) + builder.SetBuildpack(bp) dependency, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), @@ -246,7 +246,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { when("dependencies don't have a common stack", func() { it("should error", func() { - buildpack, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ + bp, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), Info: dist.BuildpackInfo{ ID: "bp.1.id", @@ -264,8 +264,8 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) - builder.SetBuildpack(buildpack) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) + builder.SetBuildpack(bp) dependency1, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), @@ -303,7 +303,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { when("dependency has stacks that aren't supported by buildpack", func() { it("should only support common stacks", func() { - buildpack, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ + bp, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), Info: dist.BuildpackInfo{ ID: "bp.1.id", @@ -321,8 +321,8 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) - builder.SetBuildpack(buildpack) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) + builder.SetBuildpack(bp) dependency1, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), @@ -356,7 +356,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { img, err := builder.SaveAsImage("some/package", false, expectedImageOS) h.AssertNil(t, err) - metadata := buildpackage.Metadata{} + metadata := buildpack.Metadata{} _, err = dist.GetLabel(img, "io.buildpacks.buildpackage.metadata", &metadata) h.AssertNil(t, err) @@ -366,7 +366,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { when("dependency is meta-buildpack", func() { it("should succeed and compute common stacks", func() { - buildpack, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ + bp, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), Info: dist.BuildpackInfo{ ID: "bp.1.id", @@ -381,8 +381,8 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory(expectedImageOS)) - builder.SetBuildpack(buildpack) + builder := buildpack.NewBuilder(mockImageFactory(expectedImageOS)) + builder.SetBuildpack(bp) dependencyOrder, err := ifakes.NewFakeBuildpack(dist.BuildpackDescriptor{ API: api.MustParse("0.2"), @@ -421,7 +421,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { img, err := builder.SaveAsImage("some/package", false, expectedImageOS) h.AssertNil(t, err) - metadata := buildpackage.Metadata{} + metadata := buildpack.Metadata{} _, err = dist.GetLabel(img, "io.buildpacks.buildpackage.metadata", &metadata) h.AssertNil(t, err) @@ -460,7 +460,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("linux")) + builder := buildpack.NewBuilder(mockImageFactory("linux")) builder.SetBuildpack(buildpack1) packageImage, err := builder.SaveAsImage("some/package", false, "linux") @@ -468,7 +468,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { labelData, err := packageImage.Label("io.buildpacks.buildpackage.metadata") h.AssertNil(t, err) - var md buildpackage.Metadata + var md buildpack.Metadata h.AssertNil(t, json.Unmarshal([]byte(labelData), &md)) h.AssertEq(t, md.ID, "bp.1.id") @@ -497,7 +497,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("linux")) + builder := buildpack.NewBuilder(mockImageFactory("linux")) builder.SetBuildpack(buildpack1) packageImage, err := builder.SaveAsImage("some/package", false, "linux") @@ -521,7 +521,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("linux")) + builder := buildpack.NewBuilder(mockImageFactory("linux")) builder.SetBuildpack(buildpack1) packageImage, err := builder.SaveAsImage("some/package", false, "linux") @@ -568,7 +568,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("windows")) + builder := buildpack.NewBuilder(mockImageFactory("windows")) builder.SetBuildpack(buildpack1) _, err = builder.SaveAsImage("some/package", false, "windows") @@ -586,7 +586,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("")) + builder := buildpack.NewBuilder(mockImageFactory("")) builder.SetBuildpack(buildpack1) outputFile := filepath.Join(tmpDir, fmt.Sprintf("package-%s.cnb", h.RandString(10))) @@ -643,7 +643,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("")) + builder := buildpack.NewBuilder(mockImageFactory("")) builder.SetBuildpack(buildpack1) outputFile := filepath.Join(tmpDir, fmt.Sprintf("package-%s.cnb", h.RandString(10))) @@ -693,7 +693,7 @@ func testPackageBuilder(t *testing.T, when spec.G, it spec.S) { }, 0644) h.AssertNil(t, err) - builder := buildpackage.NewBuilder(mockImageFactory("")) + builder := buildpack.NewBuilder(mockImageFactory("")) builder.SetBuildpack(buildpack1) outputFile := filepath.Join(tmpDir, fmt.Sprintf("package-%s.cnb", h.RandString(10))) diff --git a/internal/dist/buildpack.go b/pkg/buildpack/buildpack.go similarity index 69% rename from internal/dist/buildpack.go rename to pkg/buildpack/buildpack.go index a6f25b4cf6..eb7ba55eb0 100644 --- a/internal/dist/buildpack.go +++ b/pkg/buildpack/buildpack.go @@ -1,9 +1,12 @@ -package dist +package buildpack import ( "archive/tar" + "fmt" "io" + "os" "path" + "path/filepath" "github.com/BurntSushi/toml" "github.com/buildpacks/lifecycle/api" @@ -11,72 +14,36 @@ import ( "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/dist" ) -const AssumedBuildpackAPIVersion = "0.1" -const BuildpacksDir = "/cnb/buildpacks" - type Blob interface { // Open returns a io.ReadCloser for the contents of the Blob in tar format. Open() (io.ReadCloser, error) } -type buildpack struct { - descriptor BuildpackDescriptor - Blob `toml:"-"` -} - -func (b *buildpack) Descriptor() BuildpackDescriptor { - return b.descriptor -} +//go:generate mockgen -package testmocks -destination ../testmocks/mock_buildpack.go github.com/buildpacks/pack/pkg/buildpack Buildpack -//go:generate mockgen -package testmocks -destination testmocks/mock_buildpack.go github.com/buildpacks/pack/internal/dist Buildpack type Buildpack interface { // Open returns a reader to a tar with contents structured as per the distribution spec // (currently '/cnbs/buildpacks/{ID}/{version}/*', all entries with a zeroed-out // timestamp and root UID/GID). Open() (io.ReadCloser, error) - Descriptor() BuildpackDescriptor -} - -type BuildpackInfo struct { - ID string `toml:"id,omitempty" json:"id,omitempty" yaml:"id,omitempty"` - Name string `toml:"name,omitempty" json:"name,omitempty" yaml:"name,omitempty"` - Version string `toml:"version,omitempty" json:"version,omitempty" yaml:"version,omitempty"` - Description string `toml:"description,omitempty" json:"description,omitempty" yaml:"description,omitempty"` - Homepage string `toml:"homepage,omitempty" json:"homepage,omitempty" yaml:"homepage,omitempty"` - Keywords []string `toml:"keywords,omitempty" json:"keywords,omitempty" yaml:"keywords,omitempty"` - Licenses []License `toml:"licenses,omitempty" json:"licenses,omitempty" yaml:"licenses,omitempty"` -} - -type License struct { - Type string `toml:"type"` - URI string `toml:"uri"` -} - -func (b BuildpackInfo) FullName() string { - if b.Version != "" { - return b.ID + "@" + b.Version - } - return b.ID + Descriptor() dist.BuildpackDescriptor } -// Satisfy stringer -func (b BuildpackInfo) String() string { return b.FullName() } - -// Match compares two buildpacks by ID and Version -func (b BuildpackInfo) Match(o BuildpackInfo) bool { - return b.ID == o.ID && b.Version == o.Version +type buildpack struct { + descriptor dist.BuildpackDescriptor + Blob `toml:"-"` } -type Stack struct { - ID string `json:"id" toml:"id"` - Mixins []string `json:"mixins,omitempty" toml:"mixins,omitempty"` +func (b *buildpack) Descriptor() dist.BuildpackDescriptor { + return b.descriptor } // BuildpackFromBlob constructs a buildpack from a blob. It is assumed that the buildpack // contents are structured as per the distribution spec (currently '/cnbs/buildpacks/{ID}/{version}/*'). -func BuildpackFromBlob(bpd BuildpackDescriptor, blob Blob) Buildpack { +func BuildpackFromBlob(bpd dist.BuildpackDescriptor, blob Blob) Buildpack { return &buildpack{ Blob: blob, descriptor: bpd, @@ -87,7 +54,7 @@ func BuildpackFromBlob(bpd BuildpackDescriptor, blob Blob) Buildpack { // root of the blob. The constructed buildpack contents will be structured as per the distribution spec (currently // a tar with contents under '/cnbs/buildpacks/{ID}/{version}/*'). func BuildpackFromRootBlob(blob Blob, layerWriterFactory archive.TarWriterFactory) (Buildpack, error) { - bpd := BuildpackDescriptor{} + bpd := dist.BuildpackDescriptor{} rc, err := blob.Open() if err != nil { return nil, errors.Wrap(err, "open buildpack") @@ -99,7 +66,7 @@ func BuildpackFromRootBlob(blob Blob, layerWriterFactory archive.TarWriterFactor return nil, errors.Wrap(err, "reading buildpack.toml") } - bpd.API = api.MustParse(AssumedBuildpackAPIVersion) + bpd.API = api.MustParse(dist.AssumedBuildpackAPIVersion) _, err = toml.Decode(string(buf), &bpd) if err != nil { return nil, errors.Wrap(err, "decoding buildpack.toml") @@ -133,19 +100,19 @@ func (b *distBlob) Open() (io.ReadCloser, error) { return b.openFn(), nil } -func toDistTar(tw archive.TarWriter, bpd BuildpackDescriptor, blob Blob) error { +func toDistTar(tw archive.TarWriter, bpd dist.BuildpackDescriptor, blob Blob) error { ts := archive.NormalizedDateTime if err := tw.WriteHeader(&tar.Header{ Typeflag: tar.TypeDir, - Name: path.Join(BuildpacksDir, bpd.EscapedID()), + Name: path.Join(dist.BuildpacksDir, bpd.EscapedID()), Mode: 0755, ModTime: ts, }); err != nil { return errors.Wrapf(err, "writing buildpack id dir header") } - baseTarDir := path.Join(BuildpacksDir, bpd.EscapedID(), bpd.Info.Version) + baseTarDir := path.Join(dist.BuildpacksDir, bpd.EscapedID(), bpd.Info.Version) if err := tw.WriteHeader(&tar.Header{ Typeflag: tar.TypeDir, Name: baseTarDir, @@ -222,7 +189,7 @@ func anyExecBit(mode int64) bool { return mode&0111 != 0 } -func validateDescriptor(bpd BuildpackDescriptor) error { +func validateDescriptor(bpd dist.BuildpackDescriptor) error { if bpd.Info.ID == "" { return errors.Errorf("%s is required", style.Symbol("buildpack.id")) } @@ -251,3 +218,25 @@ func validateDescriptor(bpd BuildpackDescriptor) error { return nil } + +func BuildpackToLayerTar(dest string, bp Buildpack) (string, error) { + bpd := bp.Descriptor() + bpReader, err := bp.Open() + if err != nil { + return "", errors.Wrap(err, "opening buildpack blob") + } + defer bpReader.Close() + + layerTar := filepath.Join(dest, fmt.Sprintf("%s.%s.tar", bpd.EscapedID(), bpd.Info.Version)) + fh, err := os.Create(layerTar) + if err != nil { + return "", errors.Wrap(err, "create file for tar") + } + defer fh.Close() + + if _, err := io.Copy(fh, bpReader); err != nil { + return "", errors.Wrap(err, "writing buildpack blob to tar") + } + + return layerTar, nil +} diff --git a/internal/dist/buildpack_test.go b/pkg/buildpack/buildpack_test.go similarity index 93% rename from internal/dist/buildpack_test.go rename to pkg/buildpack/buildpack_test.go index 81e3fee821..fc93376c3b 100644 --- a/internal/dist/buildpack_test.go +++ b/pkg/buildpack/buildpack_test.go @@ -1,4 +1,4 @@ -package dist_test +package buildpack_test import ( "errors" @@ -13,8 +13,9 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) @@ -25,7 +26,7 @@ func TestBuildpack(t *testing.T) { } func testBuildpack(t *testing.T, when spec.G, it spec.S) { - var writeBlobToFile = func(bp dist.Buildpack) string { + var writeBlobToFile = func(bp buildpack.Buildpack) string { t.Helper() bpReader, err := bp.Open() @@ -49,7 +50,7 @@ func testBuildpack(t *testing.T, when spec.G, it spec.S) { when("#BuildpackFromRootBlob", func() { it("parses the descriptor file", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -79,7 +80,7 @@ id = "some.stack.id" }) it("translates blob to distribution format", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -161,7 +162,7 @@ id = "some.stack.id" }, } - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &errorBlob{ realBlob: realBlob, }, @@ -190,7 +191,7 @@ id = "some.stack.id" when("no exec bits set", func() { it("sets to 0755 if directory", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -215,7 +216,7 @@ id = "some.stack.id" when("no exec bits set", func() { it("sets to 0755 if 'bin/detect' or 'bin/build'", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -246,7 +247,7 @@ id = "some.stack.id" when("not directory, 'bin/detect', or 'bin/build'", func() { it("sets to 0755 if ANY exec bit is set", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -271,7 +272,7 @@ id = "some.stack.id" when("not directory, 'bin/detect', or 'bin/build'", func() { it("sets to 0644 if NO exec bits set", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -297,7 +298,7 @@ id = "some.stack.id" when("there is no descriptor file", func() { it("returns error", func() { - _, err := dist.BuildpackFromRootBlob( + _, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -312,7 +313,7 @@ id = "some.stack.id" when("there is no api field", func() { it("assumes an api version", func() { - bp, err := dist.BuildpackFromRootBlob( + bp, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -335,7 +336,7 @@ id = "some.stack.id"`)) when("there is no id", func() { it("returns error", func() { - _, err := dist.BuildpackFromRootBlob( + _, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -357,7 +358,7 @@ id = "some.stack.id"`)) when("there is no version", func() { it("returns error", func() { - _, err := dist.BuildpackFromRootBlob( + _, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -379,7 +380,7 @@ id = "some.stack.id"`)) when("both stacks and order are present", func() { it("returns error", func() { - _, err := dist.BuildpackFromRootBlob( + _, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -407,7 +408,7 @@ id = "some.stack.id" when("missing stacks and order", func() { it("returns error", func() { - _, err := dist.BuildpackFromRootBlob( + _, err := buildpack.BuildpackFromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -461,7 +462,7 @@ version = "1.2.3" type errorBlob struct { notFirst bool - realBlob dist.Blob + realBlob buildpack.Blob } func (e *errorBlob) Open() (io.ReadCloser, error) { diff --git a/internal/buildpackage/buildpackage.go b/pkg/buildpack/buildpackage.go similarity index 68% rename from internal/buildpackage/buildpackage.go rename to pkg/buildpack/buildpackage.go index 45f0a204b0..df40107355 100644 --- a/internal/buildpackage/buildpackage.go +++ b/pkg/buildpack/buildpackage.go @@ -1,9 +1,10 @@ -package buildpackage +package buildpack import ( - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" ) +// TODO: Move to dist const MetadataLabel = "io.buildpacks.buildpackage.metadata" type Metadata struct { diff --git a/pkg/buildpack/downloader.go b/pkg/buildpack/downloader.go index 1e19308be7..7cc1c215c0 100644 --- a/pkg/buildpack/downloader.go +++ b/pkg/buildpack/downloader.go @@ -7,17 +7,25 @@ import ( "github.com/pkg/errors" "github.com/buildpacks/imgutil" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) +type Logger interface { + Debug(msg string) + Debugf(fmt string, v ...interface{}) + Info(msg string) + Infof(fmt string, v ...interface{}) + Warn(msg string) + Warnf(fmt string, v ...interface{}) + Error(msg string) + Errorf(fmt string, v ...interface{}) +} + type ImageFetcher interface { Fetch(ctx context.Context, name string, options image.FetchOptions) (imgutil.Image, error) } @@ -26,20 +34,20 @@ type Downloader interface { Download(ctx context.Context, pathOrURI string) (blob.Blob, error) } -//go:generate mockgen -package testmocks -destination ../../testmocks/mock_registry_resolver.go github.com/buildpacks/pack/pkg/buildpack RegistryResolver +//go:generate mockgen -package testmocks -destination ../testmocks/mock_registry_resolver.go github.com/buildpacks/pack/pkg/buildpack RegistryResolver type RegistryResolver interface { Resolve(registryName, bpURI string) (string, error) } type buildpackDownloader struct { - logger logging.Logger + logger Logger imageFetcher ImageFetcher downloader Downloader registryResolver RegistryResolver } -func NewDownloader(logger logging.Logger, imageFetcher ImageFetcher, downloader Downloader, registryResolver RegistryResolver) *buildpackDownloader { //nolint:golint,gosimple +func NewDownloader(logger Logger, imageFetcher ImageFetcher, downloader Downloader, registryResolver RegistryResolver) *buildpackDownloader { //nolint:golint,gosimple return &buildpackDownloader{ logger: logger, imageFetcher: imageFetcher, @@ -66,31 +74,31 @@ type DownloadOptions struct { PullPolicy image.PullPolicy } -func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, opts DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { +func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, opts DownloadOptions) (Buildpack, []Buildpack, error) { var err error - var locatorType buildpack.LocatorType + var locatorType LocatorType if buildpackURI == "" && opts.ImageName != "" { c.logger.Warn("The 'image' key is deprecated. Use 'uri=\"docker://...\"' instead.") buildpackURI = opts.ImageName - locatorType = buildpack.PackageLocator + locatorType = PackageLocator } else { - locatorType, err = buildpack.GetLocatorType(buildpackURI, opts.RelativeBaseDir, []dist.BuildpackInfo{}) + locatorType, err = GetLocatorType(buildpackURI, opts.RelativeBaseDir, []dist.BuildpackInfo{}) if err != nil { return nil, nil, err } } - var mainBP dist.Buildpack - var depBPs []dist.Buildpack + var mainBP Buildpack + var depBPs []Buildpack switch locatorType { - case buildpack.PackageLocator: - imageName := buildpack.ParsePackageLocator(buildpackURI) + case PackageLocator: + imageName := ParsePackageLocator(buildpackURI) c.logger.Debugf("Downloading buildpack from image: %s", style.Symbol(imageName)) mainBP, depBPs, err = extractPackagedBuildpacks(ctx, imageName, c.imageFetcher, image.FetchOptions{Daemon: opts.Daemon, PullPolicy: opts.PullPolicy}) if err != nil { return nil, nil, errors.Wrapf(err, "extracting from registry %s", style.Symbol(buildpackURI)) } - case buildpack.RegistryLocator: + case RegistryLocator: c.logger.Debugf("Downloading buildpack from registry: %s", style.Symbol(buildpackURI)) address, err := c.registryResolver.Resolve(opts.RegistryName, buildpackURI) if err != nil { @@ -101,7 +109,7 @@ func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, if err != nil { return nil, nil, errors.Wrapf(err, "extracting from registry %s", style.Symbol(buildpackURI)) } - case buildpack.URILocator: + case URILocator: buildpackURI, err = paths.FilePathToURI(buildpackURI, opts.RelativeBaseDir) if err != nil { return nil, nil, errors.Wrapf(err, "making absolute: %s", style.Symbol(buildpackURI)) @@ -125,14 +133,14 @@ func (c *buildpackDownloader) Download(ctx context.Context, buildpackURI string, } // decomposeBuildpack decomposes a buildpack blob into the main builder (order buildpack) and it's dependencies buildpacks. -func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { - isOCILayout, err := buildpackage.IsOCILayoutBlob(blob) +func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP Buildpack, depBPs []Buildpack, err error) { + isOCILayout, err := IsOCILayoutBlob(blob) if err != nil { return mainBP, depBPs, errors.Wrap(err, "inspecting buildpack blob") } if isOCILayout { - mainBP, depBPs, err = buildpackage.BuildpacksFromOCILayoutBlob(blob) + mainBP, depBPs, err = BuildpacksFromOCILayoutBlob(blob) if err != nil { return mainBP, depBPs, errors.Wrap(err, "extracting buildpacks") } @@ -142,7 +150,7 @@ func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP dist.Buildpack, return mainBP, depBPs, errors.Wrapf(err, "get tar writer factory for OS %s", style.Symbol(imageOS)) } - mainBP, err = dist.BuildpackFromRootBlob(blob, layerWriterFactory) + mainBP, err = BuildpackFromRootBlob(blob, layerWriterFactory) if err != nil { return mainBP, depBPs, errors.Wrap(err, "reading buildpack") } @@ -151,13 +159,13 @@ func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP dist.Buildpack, return mainBP, depBPs, nil } -func extractPackagedBuildpacks(ctx context.Context, pkgImageRef string, fetcher ImageFetcher, fetchOptions image.FetchOptions) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { +func extractPackagedBuildpacks(ctx context.Context, pkgImageRef string, fetcher ImageFetcher, fetchOptions image.FetchOptions) (mainBP Buildpack, depBPs []Buildpack, err error) { pkgImage, err := fetcher.Fetch(ctx, pkgImageRef, fetchOptions) if err != nil { return nil, nil, errors.Wrapf(err, "fetching image") } - mainBP, depBPs, err = buildpackage.ExtractBuildpacks(pkgImage) + mainBP, depBPs, err = ExtractBuildpacks(pkgImage) if err != nil { return nil, nil, errors.Wrapf(err, "extracting buildpacks from %s", style.Symbol(pkgImageRef)) } diff --git a/pkg/buildpack/downloader_test.go b/pkg/buildpack/downloader_test.go index 21c36ba74c..8672d00449 100644 --- a/pkg/buildpack/downloader_test.go +++ b/pkg/buildpack/downloader_test.go @@ -19,15 +19,14 @@ import ( "github.com/sclevine/spec/report" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -90,7 +89,7 @@ func testBuildpackDownloader(t *testing.T, when spec.G, it spec.S) { } it.Before(func() { - logger = ilogging.NewLogWithWriters(&out, &out, ilogging.WithVerbose()) + logger = logging.NewLogWithWriters(&out, &out, logging.WithVerbose()) mockController = gomock.NewController(t) mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockRegistryResolver = testmocks.NewMockRegistryResolver(mockController) diff --git a/internal/buildpack/locator_type.go b/pkg/buildpack/locator_type.go similarity index 98% rename from internal/buildpack/locator_type.go rename to pkg/buildpack/locator_type.go index 0443402a74..2f1a74bb5b 100644 --- a/internal/buildpack/locator_type.go +++ b/pkg/buildpack/locator_type.go @@ -9,9 +9,9 @@ import ( "github.com/google/go-containerregistry/pkg/name" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/dist" ) type LocatorType int diff --git a/internal/buildpack/locator_type_test.go b/pkg/buildpack/locator_type_test.go similarity index 96% rename from internal/buildpack/locator_type_test.go rename to pkg/buildpack/locator_type_test.go index abb464655d..c38c247f7d 100644 --- a/internal/buildpack/locator_type_test.go +++ b/pkg/buildpack/locator_type_test.go @@ -9,8 +9,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) @@ -71,8 +71,8 @@ func testGetLocatorType(t *testing.T, when spec.G, it spec.S) { expectedType: buildpack.IDLocator, }, { - locator: localPath("some-bp"), - builderBPs: []dist.BuildpackInfo{{ID: localPath("some-bp"), Version: "some-version"}}, + locator: localPath("buildpack"), + builderBPs: []dist.BuildpackInfo{{ID: "bp.one", Version: "1.2.3"}}, expectedType: buildpack.URILocator, }, { diff --git a/internal/buildpackage/oci_layout_package.go b/pkg/buildpack/oci_layout_package.go similarity index 90% rename from internal/buildpackage/oci_layout_package.go rename to pkg/buildpack/oci_layout_package.go index 2919f0ac05..4be4ac6882 100644 --- a/internal/buildpackage/oci_layout_package.go +++ b/pkg/buildpack/oci_layout_package.go @@ -1,4 +1,4 @@ -package buildpackage +package buildpack import ( "archive/tar" @@ -12,10 +12,10 @@ import ( v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" blob2 "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/dist" ) // IsOCILayoutBlob checks whether a blob is in OCI layout format. @@ -39,7 +39,7 @@ func IsOCILayoutBlob(blob blob2.Blob) (bool, error) { } // BuildpackFromOCILayoutBlob constructs buildpacks from a blob in OCI layout format. -func BuildpacksFromOCILayoutBlob(blob dist.Blob) (mainBP dist.Buildpack, dependencies []dist.Buildpack, err error) { +func BuildpacksFromOCILayoutBlob(blob Blob) (mainBP Buildpack, dependencies []Buildpack, err error) { layoutPackage, err := newOCILayoutPackage(blob) if err != nil { return nil, nil, err @@ -48,7 +48,7 @@ func BuildpacksFromOCILayoutBlob(blob dist.Blob) (mainBP dist.Buildpack, depende return ExtractBuildpacks(layoutPackage) } -func ConfigFromOCILayoutBlob(blob dist.Blob) (config v1.ImageConfig, err error) { +func ConfigFromOCILayoutBlob(blob Blob) (config v1.ImageConfig, err error) { layoutPackage, err := newOCILayoutPackage(blob) if err != nil { return v1.ImageConfig{}, err @@ -59,10 +59,10 @@ func ConfigFromOCILayoutBlob(blob dist.Blob) (config v1.ImageConfig, err error) type ociLayoutPackage struct { imageInfo v1.Image manifest v1.Manifest - blob dist.Blob + blob Blob } -func newOCILayoutPackage(blob dist.Blob) (*ociLayoutPackage, error) { +func newOCILayoutPackage(blob Blob) (*ociLayoutPackage, error) { index := &v1.Index{} if err := unmarshalJSONFromBlob(blob, "/index.json", index); err != nil { @@ -173,7 +173,7 @@ func pathFromDescriptor(descriptor v1.Descriptor) string { return path.Join("/blobs", descriptor.Digest.Algorithm().String(), descriptor.Digest.Encoded()) } -func unmarshalJSONFromBlob(blob dist.Blob, path string, obj interface{}) error { +func unmarshalJSONFromBlob(blob Blob, path string, obj interface{}) error { reader, err := blob.Open() if err != nil { return err diff --git a/internal/buildpackage/oci_layout_package_test.go b/pkg/buildpack/oci_layout_package_test.go similarity index 75% rename from internal/buildpackage/oci_layout_package_test.go rename to pkg/buildpack/oci_layout_package_test.go index 9aadd49b70..528d470eb7 100644 --- a/internal/buildpackage/oci_layout_package_test.go +++ b/pkg/buildpack/oci_layout_package_test.go @@ -1,21 +1,20 @@ -package buildpackage_test +package buildpack_test import ( "fmt" "path/filepath" "testing" + "github.com/buildpacks/lifecycle/api" "github.com/heroku/color" "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/lifecycle/api" - - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/fakes" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) @@ -28,7 +27,7 @@ func TestOCILayoutPackage(t *testing.T) { func testOCILayoutPackage(t *testing.T, when spec.G, it spec.S) { when("#BuildpacksFromOCILayoutBlob", func() { it("extracts buildpacks", func() { - mainBP, depBPs, err := buildpackage.BuildpacksFromOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) + mainBP, depBPs, err := buildpack.BuildpacksFromOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) h.AssertNil(t, err) h.AssertEq(t, mainBP.Descriptor().Info.ID, "io.buildpacks.samples.hello-universe") @@ -37,10 +36,10 @@ func testOCILayoutPackage(t *testing.T, when spec.G, it spec.S) { }) it("provides readable blobs", func() { - mainBP, depBPs, err := buildpackage.BuildpacksFromOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) + mainBP, depBPs, err := buildpack.BuildpacksFromOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) h.AssertNil(t, err) - for _, bp := range append([]dist.Buildpack{mainBP}, depBPs...) { + for _, bp := range append([]buildpack.Buildpack{mainBP}, depBPs...) { reader, err := bp.Open() h.AssertNil(t, err) @@ -61,7 +60,7 @@ func testOCILayoutPackage(t *testing.T, when spec.G, it spec.S) { when("#IsOCILayoutBlob", func() { when("is an OCI layout blob", func() { it("returns true", func() { - isOCILayoutBlob, err := buildpackage.IsOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) + isOCILayoutBlob, err := buildpack.IsOCILayoutBlob(blob.NewBlob(filepath.Join("testdata", "hello-universe.cnb"))) h.AssertNil(t, err) h.AssertEq(t, isOCILayoutBlob, true) }) @@ -80,7 +79,7 @@ func testOCILayoutPackage(t *testing.T, when spec.G, it spec.S) { }, 0755) h.AssertNil(t, err) - isOCILayoutBlob, err := buildpackage.IsOCILayoutBlob(buildpackBlob) + isOCILayoutBlob, err := buildpack.IsOCILayoutBlob(buildpackBlob) h.AssertNil(t, err) h.AssertEq(t, isOCILayoutBlob, false) }) diff --git a/internal/buildpackage/package.go b/pkg/buildpack/package.go similarity index 86% rename from internal/buildpackage/package.go rename to pkg/buildpack/package.go index ee7ab5d553..d580376325 100644 --- a/internal/buildpackage/package.go +++ b/pkg/buildpack/package.go @@ -1,12 +1,12 @@ -package buildpackage +package buildpack import ( "io" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/dist" ) type Package interface { @@ -14,7 +14,7 @@ type Package interface { GetLayer(diffID string) (io.ReadCloser, error) } -func ExtractBuildpacks(pkg Package) (mainBP dist.Buildpack, depBPs []dist.Buildpack, err error) { +func ExtractBuildpacks(pkg Package) (mainBP Buildpack, depBPs []Buildpack, err error) { md := &Metadata{} if found, err := dist.GetLabel(pkg, MetadataLabel, md); err != nil { return nil, nil, err @@ -68,9 +68,9 @@ func ExtractBuildpacks(pkg Package) (mainBP dist.Buildpack, depBPs []dist.Buildp } if desc.Info.Match(md.BuildpackInfo) { // This is the order buildpack of the package - mainBP = dist.BuildpackFromBlob(desc, b) + mainBP = BuildpackFromBlob(desc, b) } else { - depBPs = append(depBPs, dist.BuildpackFromBlob(desc, b)) + depBPs = append(depBPs, BuildpackFromBlob(desc, b)) } } } diff --git a/internal/buildpack/parse_name.go b/pkg/buildpack/parse_name.go similarity index 100% rename from internal/buildpack/parse_name.go rename to pkg/buildpack/parse_name.go diff --git a/internal/buildpack/parse_name_test.go b/pkg/buildpack/parse_name_test.go similarity index 98% rename from internal/buildpack/parse_name_test.go rename to pkg/buildpack/parse_name_test.go index 08df16c0cf..0ce32cd8a5 100644 --- a/internal/buildpack/parse_name_test.go +++ b/pkg/buildpack/parse_name_test.go @@ -7,7 +7,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/buildpack" + "github.com/buildpacks/pack/pkg/buildpack" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/buildpackage/testdata/hello-universe.cnb b/pkg/buildpack/testdata/hello-universe.cnb similarity index 100% rename from internal/buildpackage/testdata/hello-universe.cnb rename to pkg/buildpack/testdata/hello-universe.cnb diff --git a/internal/buildpackage/testdata/package.toml b/pkg/buildpack/testdata/package.toml similarity index 100% rename from internal/buildpackage/testdata/package.toml rename to pkg/buildpack/testdata/package.toml diff --git a/pkg/client/build.go b/pkg/client/build.go index 604a9d26b7..3c47865589 100644 --- a/pkg/client/build.go +++ b/pkg/client/build.go @@ -23,18 +23,17 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" - ibuildpack "github.com/buildpacks/pack/internal/buildpack" internalConfig "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" pname "github.com/buildpacks/pack/internal/name" "github.com/buildpacks/pack/internal/stack" "github.com/buildpacks/pack/internal/stringset" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/internal/termui" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" projectTypes "github.com/buildpacks/pack/pkg/project/types" ) @@ -487,7 +486,7 @@ func (c *Client) validateRunImage(context context.Context, name string, pullPoli return img, nil } -func (c *Client) validateMixins(additionalBuildpacks []dist.Buildpack, bldr *builder.Builder, runImageName string, runMixins []string) error { +func (c *Client) validateMixins(additionalBuildpacks []buildpack.Buildpack, bldr *builder.Builder, runImageName string, runMixins []string) error { if err := stack.ValidateMixins(bldr.Image().Name(), bldr.Mixins(), runImageName, runMixins); err != nil { return err } @@ -537,7 +536,7 @@ func assembleAvailableMixins(buildMixins, runMixins []string) []string { // allBuildpacks aggregates all buildpacks declared on the image with additional buildpacks passed in. They are sorted // by ID then Version. -func allBuildpacks(builderImage imgutil.Image, additionalBuildpacks []dist.Buildpack) ([]dist.BuildpackDescriptor, error) { +func allBuildpacks(builderImage imgutil.Image, additionalBuildpacks []buildpack.Buildpack) ([]dist.BuildpackDescriptor, error) { var all []dist.BuildpackDescriptor var bpLayers dist.BuildpackLayers if _, err := dist.GetLabel(builderImage, dist.BuildpackLayersLabel, &bpLayers); err != nil { @@ -677,7 +676,7 @@ func (c *Client) processProxyConfig(config *ProxyConfig) ProxyConfig { // ---------- // - group: // - A -func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Image, builderBPs []dist.BuildpackInfo, builderOrder dist.Order, stackID string, opts BuildOptions) (fetchedBPs []dist.Buildpack, order dist.Order, err error) { +func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Image, builderBPs []dist.BuildpackInfo, builderOrder dist.Order, stackID string, opts BuildOptions) (fetchedBPs []buildpack.Buildpack, order dist.Order, err error) { pullPolicy := opts.PullPolicy publish := opts.Publish registry := opts.Registry @@ -712,13 +711,13 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima order = dist.Order{{Group: []dist.BuildpackRef{}}} for _, bp := range declaredBPs { - locatorType, err := ibuildpack.GetLocatorType(bp, relativeBaseDir, builderBPs) + locatorType, err := buildpack.GetLocatorType(bp, relativeBaseDir, builderBPs) if err != nil { return nil, nil, err } switch locatorType { - case ibuildpack.FromBuilderLocator: + case buildpack.FromBuilderLocator: switch { case len(order) == 0 || len(order[0].Group) == 0: order = builderOrder @@ -735,8 +734,8 @@ func (c *Client) processBuildpacks(ctx context.Context, builderImage imgutil.Ima order = newOrder } - case ibuildpack.IDLocator: - id, version := ibuildpack.ParseIDLocator(bp) + case buildpack.IDLocator: + id, version := buildpack.ParseIDLocator(bp) order = appendBuildpackToOrder(order, dist.BuildpackInfo{ ID: id, Version: version, @@ -777,7 +776,7 @@ func appendBuildpackToOrder(order dist.Order, bpInfo dist.BuildpackInfo) (newOrd return newOrder } -func (c *Client) createEphemeralBuilder(rawBuilderImage imgutil.Image, env map[string]string, order dist.Order, buildpacks []dist.Buildpack) (*builder.Builder, error) { +func (c *Client) createEphemeralBuilder(rawBuilderImage imgutil.Image, env map[string]string, order dist.Order, buildpacks []buildpack.Buildpack) (*builder.Builder, error) { origBuilderName := rawBuilderImage.Name() bldr, err := builder.New(rawBuilderImage, fmt.Sprintf("pack.local/builder/%x:latest", randString(10))) if err != nil { diff --git a/pkg/client/build_test.go b/pkg/client/build_test.go index a595a2158f..dad91ac245 100644 --- a/pkg/client/build_test.go +++ b/pkg/client/build_test.go @@ -34,16 +34,15 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/buildpackage" cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" rg "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" projectTypes "github.com/buildpacks/pack/pkg/project/types" h "github.com/buildpacks/pack/testhelpers" ) @@ -74,7 +73,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { fakeMirror2 *fakes.Image tmpDir string outBuf bytes.Buffer - logger *ilogging.LogWithWriters + logger *logging.LogWithWriters fakeLifecycleImage *fakes.Image ) it.Before(func() { @@ -120,7 +119,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { docker, err := dockerclient.NewClientWithOpts(dockerclient.FromEnv, dockerclient.WithVersion("1.38")) h.AssertNil(t, err) - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) dlCacheDir, err := ioutil.TempDir(tmpDir, "dl-cache") h.AssertNil(t, err) @@ -1043,7 +1042,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { }, } - md := buildpackage.Metadata{ + md := buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "meta.buildpack.id", Version: "meta.buildpack.version", @@ -1474,7 +1473,7 @@ func testBuild(t *testing.T, when spec.G, it spec.S) { }, } - md := buildpackage.Metadata{ + md := buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "example/foo", Version: "1.0.0", diff --git a/pkg/client/client.go b/pkg/client/client.go index 25f77dbc80..4010e39d65 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -29,12 +29,11 @@ import ( "github.com/buildpacks/pack/internal/build" iconfig "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" ) //go:generate mockgen -package testmocks -destination ../testmocks/mock_docker_client.go github.com/docker/docker/client CommonAPIClient @@ -78,7 +77,7 @@ type ImageFactory interface { // BuildpackDownloader is an interface for downloading and extracting buildpacks from various sources type BuildpackDownloader interface { // Download parses a buildpack URI and downloads the buildpack and any dependencies buildpacks from the appropriate source - Download(ctx context.Context, buildpackURI string, opts buildpack.DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) + Download(ctx context.Context, buildpackURI string, opts buildpack.DownloadOptions) (buildpack.Buildpack, []buildpack.Buildpack, error) } // Client is an orchestration object, it contains all parameters needed to @@ -193,7 +192,7 @@ func NewClient(opts ...ClientOption) (*Client, error) { } if client.logger == nil { - client.logger = logging.New(os.Stderr) + client.logger = logging.NewSimpleLogger(os.Stderr) } if client.docker == nil { diff --git a/pkg/client/client_test.go b/pkg/client/client_test.go index d020987bdf..0b40ec0a8f 100644 --- a/pkg/client/client_test.go +++ b/pkg/client/client_test.go @@ -10,7 +10,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -48,7 +48,7 @@ func testClient(t *testing.T, when spec.G, it spec.S) { when("#WithLogger", func() { it("uses logger provided", func() { var w bytes.Buffer - logger := logging.New(&w) + logger := logging.NewSimpleLogger(&w) cl, err := NewClient(WithLogger(logger)) h.AssertNil(t, err) h.AssertSameInstance(t, cl.logger, logger) diff --git a/pkg/client/common.go b/pkg/client/common.go index bf02ea329b..b67916729a 100644 --- a/pkg/client/common.go +++ b/pkg/client/common.go @@ -10,7 +10,7 @@ import ( "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" ) func (c *Client) parseTagReference(imageName string) (name.Reference, error) { diff --git a/pkg/client/common_test.go b/pkg/client/common_test.go index 2d9507b4e6..732c324b73 100644 --- a/pkg/client/common_test.go +++ b/pkg/client/common_test.go @@ -9,8 +9,7 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/builder" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -36,7 +35,7 @@ func testCommon(t *testing.T, when spec.G, it spec.S) { ) it.Before(func() { - logger = ilogging.NewLogWithWriters(&outBuf, &outBuf) + logger = logging.NewLogWithWriters(&outBuf, &outBuf) var err error subject, err = NewClient(WithLogger(logger)) @@ -73,7 +72,7 @@ func testCommon(t *testing.T, when spec.G, it spec.S) { it("prefers config defined run image mirror to stack defined run image mirror", func() { configMirrors := map[string][]string{ - runImageName: []string{defaultRegistry + "/unique-run-img"}, + runImageName: {defaultRegistry + "/unique-run-img"}, } runImageName := subject.resolveRunImage("", defaultRegistry, "", stackInfo, configMirrors, true) assert.NotEqual(runImageName, defaultMirror) @@ -82,7 +81,7 @@ func testCommon(t *testing.T, when spec.G, it spec.S) { it("returns a config mirror if no match to target registry", func() { configMirrors := map[string][]string{ - runImageName: []string{defaultRegistry + "/unique-run-img"}, + runImageName: {defaultRegistry + "/unique-run-img"}, } runImageName := subject.resolveRunImage("", "test.registry.io", "", stackInfo, configMirrors, true) assert.NotEqual(runImageName, defaultMirror) @@ -100,7 +99,7 @@ func testCommon(t *testing.T, when spec.G, it spec.S) { it("prefers config defined run image mirror to stack defined run image mirror", func() { configMirrors := map[string][]string{ - runImageName: []string{defaultRegistry + "/unique-run-img"}, + runImageName: {defaultRegistry + "/unique-run-img"}, } runImageName := subject.resolveRunImage("", gcrRegistry, defaultRegistry, stackInfo, configMirrors, false) assert.NotEqual(runImageName, defaultMirror) @@ -109,7 +108,7 @@ func testCommon(t *testing.T, when spec.G, it spec.S) { it("returns a config mirror if no match to target registry", func() { configMirrors := map[string][]string{ - runImageName: []string{defaultRegistry + "/unique-run-img"}, + runImageName: {defaultRegistry + "/unique-run-img"}, } runImageName := subject.resolveRunImage("", defaultRegistry, "test.registry.io", stackInfo, configMirrors, false) assert.NotEqual(runImageName, defaultMirror) diff --git a/pkg/client/create_builder.go b/pkg/client/create_builder.go index bcdc2e5074..34bca4b5ee 100644 --- a/pkg/client/create_builder.go +++ b/pkg/client/create_builder.go @@ -10,7 +10,6 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/buildpack" @@ -234,7 +233,7 @@ func (c *Client) addBuildpacksToBuilder(ctx context.Context, opts CreateBuilderO } } - for _, bp := range append([]dist.Buildpack{mainBP}, depBPs...) { + for _, bp := range append([]buildpack.Buildpack{mainBP}, depBPs...) { bldr.AddBuildpack(bp) } } @@ -242,7 +241,7 @@ func (c *Client) addBuildpacksToBuilder(ctx context.Context, opts CreateBuilderO return nil } -func validateBuildpack(bp dist.Buildpack, source, expectedID, expectedBPVersion string) error { +func validateBuildpack(bp buildpack.Buildpack, source, expectedID, expectedBPVersion string) error { if expectedID != "" && bp.Descriptor().Info.ID != expectedID { return fmt.Errorf( "buildpack from URI %s has ID %s which does not match ID %s from builder config", diff --git a/pkg/client/create_builder_test.go b/pkg/client/create_builder_test.go index b63bde836f..399973fb1c 100644 --- a/pkg/client/create_builder_test.go +++ b/pkg/client/create_builder_test.go @@ -21,18 +21,16 @@ import ( pubbldr "github.com/buildpacks/pack/builder" pubbldpkg "github.com/buildpacks/pack/buildpackage" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - ilogging "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -70,7 +68,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { mockImageFetcher.EXPECT().Fetch(gomock.Any(), "some/build-image", gomock.Any()).Return(fakeBuildImage, nil) } - var createBuildpack = func(descriptor dist.BuildpackDescriptor) dist.Buildpack { + var createBuildpack = func(descriptor dist.BuildpackDescriptor) buildpack.Buildpack { buildpack, err := ifakes.NewFakeBuildpack(descriptor, 0644) h.AssertNil(t, err) return buildpack @@ -85,7 +83,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { } it.Before(func() { - logger = ilogging.NewLogWithWriters(&out, &out, ilogging.WithVerbose()) + logger = logging.NewLogWithWriters(&out, &out, logging.WithVerbose()) mockController = gomock.NewController(t) mockDownloader = testmocks.NewMockBlobDownloader(mockController) mockImageFetcher = testmocks.NewMockImageFetcher(mockController) @@ -111,11 +109,9 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), "file:///some-lifecycle").Return(blob.NewBlob(filepath.Join("testdata", "lifecycle", "platform-0.4")), nil).AnyTimes() mockDownloader.EXPECT().Download(gomock.Any(), "file:///some-lifecycle-platform-0-1").Return(blob.NewBlob(filepath.Join("testdata", "lifecycle-platform-0.1")), nil).AnyTimes() - var buildpack dist.Buildpack - var err error - buildpack, err = dist.BuildpackFromRootBlob(exampleBuildpackBlob, archive.DefaultTarWriterFactory()) + bp, err := buildpack.BuildpackFromRootBlob(exampleBuildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) - mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz", gomock.Any()).Return(buildpack, nil, nil).AnyTimes() + mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz", gomock.Any()).Return(bp, nil, nil).AnyTimes() subject, err = client.NewClient( client.WithLogger(logger), @@ -626,7 +622,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { opts.Config.Buildpacks[0].URI = "https://example.fake/bp-one-with-api-4.tgz" buildpackBlob := blob.NewBlob(filepath.Join("testdata", "buildpack-api-0.4")) - buildpack, err := dist.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) + buildpack, err := buildpack.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one-with-api-4.tgz", gomock.Any()).Return(buildpack, nil, nil) @@ -645,7 +641,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { opts.Config.Buildpacks[0].URI = directoryPath buildpackBlob := blob.NewBlob(directoryPath) - buildpack, err := dist.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) + buildpack, err := buildpack.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), directoryPath, gomock.Any()).Return(buildpack, nil, nil) @@ -674,7 +670,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { Format: "file", })) - buildpack, _, err := buildpackage.BuildpacksFromOCILayoutBlob(blob.NewBlob(cnbFile)) + buildpack, _, err := buildpack.BuildpacksFromOCILayoutBlob(blob.NewBlob(cnbFile)) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), cnbFile, gomock.Any()).Return(buildpack, nil, nil).AnyTimes() opts.Config.Buildpacks = []pubbldr.BuildpackConfig{{ diff --git a/pkg/client/example_buildpack_downloader_test.go b/pkg/client/example_buildpack_downloader_test.go new file mode 100644 index 0000000000..155263d362 --- /dev/null +++ b/pkg/client/example_buildpack_downloader_test.go @@ -0,0 +1,51 @@ +package client_test + +import ( + "context" + "errors" + "fmt" + "path/filepath" + + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/client" +) + +// This example shows how to replace the buildpack downloader component +func Example_buildpack_downloader() { + // create a context object + context := context.Background() + + // initialize a pack client + pack, err := client.NewClient(client.WithBuildpackDownloader(&bpDownloader{})) + if err != nil { + panic(err) + } + + // replace this with the location of a sample application + // For a list of prepared samples see the 'apps' folder at + // https://github.com/buildpacks/samples. + appPath := filepath.Join("testdata", "some-app") + + // initialize our options + buildOpts := client.BuildOptions{ + Image: "pack-lib-test-image:0.0.1", + Builder: "cnbs/sample-builder:bionic", + AppPath: appPath, + Buildpacks: []string{"some-buildpack:1.2.3"}, + TrustBuilder: func(string) bool { return true }, + } + + // build an image + _ = pack.Build(context, buildOpts) + + // Output: custom buildpack downloader called +} + +var _ client.BuildpackDownloader = (*bpDownloader)(nil) + +type bpDownloader struct{} + +func (f *bpDownloader) Download(ctx context.Context, buildpackURI string, opts buildpack.DownloadOptions) (buildpack.Buildpack, []buildpack.Buildpack, error) { + fmt.Println("custom buildpack downloader called") + return nil, nil, errors.New("not implemented") +} diff --git a/pkg/client/inspect_builder.go b/pkg/client/inspect_builder.go index 9305c1792b..8a22249f3d 100644 --- a/pkg/client/inspect_builder.go +++ b/pkg/client/inspect_builder.go @@ -6,7 +6,7 @@ import ( pubbldr "github.com/buildpacks/pack/builder" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) diff --git a/pkg/client/inspect_builder_test.go b/pkg/client/inspect_builder_test.go index 8e141a7b7d..abb2629827 100644 --- a/pkg/client/inspect_builder_test.go +++ b/pkg/client/inspect_builder_test.go @@ -17,9 +17,9 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/inspect_buildpack.go b/pkg/client/inspect_buildpack.go index 727d3493fa..84f89ce813 100644 --- a/pkg/client/inspect_buildpack.go +++ b/pkg/client/inspect_buildpack.go @@ -7,15 +7,14 @@ import ( v1 "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) type BuildpackInfo struct { - BuildpackMetadata buildpackage.Metadata + BuildpackMetadata buildpack.Metadata Buildpacks []dist.BuildpackInfo Order dist.Order BuildpackLayers dist.BuildpackLayers @@ -42,7 +41,7 @@ func (c *Client) InspectBuildpack(opts InspectBuildpackOptions) (*BuildpackInfo, return nil, err } var layersMd dist.BuildpackLayers - var buildpackMd buildpackage.Metadata + var buildpackMd buildpack.Metadata switch locatorType { case buildpack.RegistryLocator: @@ -67,62 +66,62 @@ func (c *Client) InspectBuildpack(opts InspectBuildpackOptions) (*BuildpackInfo, }, nil } -func metadataFromRegistry(client *Client, name, registry string) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { +func metadataFromRegistry(client *Client, name, registry string) (buildpackMd buildpack.Metadata, layersMd dist.BuildpackLayers, err error) { registryCache, err := getRegistry(client.logger, registry) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("invalid registry %s: %q", registry, err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("invalid registry %s: %q", registry, err) } registryBp, err := registryCache.LocateBuildpack(name) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to find %s in registry: %q", style.Symbol(name), err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to find %s in registry: %q", style.Symbol(name), err) } buildpackMd, layersMd, err = metadataFromImage(client, registryBp.Address, false) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("error pulling registry specified image: %s", err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("error pulling registry specified image: %s", err) } return buildpackMd, layersMd, nil } -func metadataFromArchive(downloader BlobDownloader, path string) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { +func metadataFromArchive(downloader BlobDownloader, path string) (buildpackMd buildpack.Metadata, layersMd dist.BuildpackLayers, err error) { imgBlob, err := downloader.Download(context.Background(), path) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to download archive: %q", err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to download archive: %q", err) } - config, err := buildpackage.ConfigFromOCILayoutBlob(imgBlob) + config, err := buildpack.ConfigFromOCILayoutBlob(imgBlob) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to fetch config from buildpack blob: %q", err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to fetch config from buildpack blob: %q", err) } wrapper := ImgWrapper{config} if _, err := dist.GetLabel(wrapper, dist.BuildpackLayersLabel, &layersMd); err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, err + return buildpack.Metadata{}, dist.BuildpackLayers{}, err } - if _, err := dist.GetLabel(wrapper, buildpackage.MetadataLabel, &buildpackMd); err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, err + if _, err := dist.GetLabel(wrapper, buildpack.MetadataLabel, &buildpackMd); err != nil { + return buildpack.Metadata{}, dist.BuildpackLayers{}, err } return buildpackMd, layersMd, nil } -func metadataFromImage(client *Client, name string, daemon bool) (buildpackMd buildpackage.Metadata, layersMd dist.BuildpackLayers, err error) { +func metadataFromImage(client *Client, name string, daemon bool) (buildpackMd buildpack.Metadata, layersMd dist.BuildpackLayers, err error) { imageName := buildpack.ParsePackageLocator(name) img, err := client.imageFetcher.Fetch(context.Background(), imageName, image.FetchOptions{Daemon: daemon, PullPolicy: image.PullNever}) if err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, err + return buildpack.Metadata{}, dist.BuildpackLayers{}, err } if _, err := dist.GetLabel(img, dist.BuildpackLayersLabel, &layersMd); err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to get image label %s: %q", dist.BuildpackLayersLabel, err) + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to get image label %s: %q", dist.BuildpackLayersLabel, err) } - if _, err := dist.GetLabel(img, buildpackage.MetadataLabel, &buildpackMd); err != nil { - return buildpackage.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to get image label %s: %q", buildpackage.MetadataLabel, err) + if _, err := dist.GetLabel(img, buildpack.MetadataLabel, &buildpackMd); err != nil { + return buildpack.Metadata{}, dist.BuildpackLayers{}, fmt.Errorf("unable to get image label %s: %q", buildpack.MetadataLabel, err) } return buildpackMd, layersMd, nil } -func extractOrder(buildpackMd buildpackage.Metadata) dist.Order { +func extractOrder(buildpackMd buildpack.Metadata) dist.Order { return dist.Order{ { Group: []dist.BuildpackRef{ diff --git a/pkg/client/inspect_buildpack_test.go b/pkg/client/inspect_buildpack_test.go index ac6a9cb31a..07e2cafcae 100644 --- a/pkg/client/inspect_buildpack_test.go +++ b/pkg/client/inspect_buildpack_test.go @@ -20,15 +20,14 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/buildpackage" cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/archive" "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -178,7 +177,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { client.WithDownloader(mockDownloader)(subject) buildpackImage = fakes.NewImage("some/buildpack", "", nil) - h.AssertNil(t, buildpackImage.SetLabel(buildpackage.MetadataLabel, buildpackageMetadataTag)) + h.AssertNil(t, buildpackImage.SetLabel(buildpack.MetadataLabel, buildpackageMetadataTag)) h.AssertNil(t, buildpackImage.SetLabel(dist.BuildpackLayersLabel, buildpackLayersTag)) var err error @@ -191,7 +190,7 @@ func testInspectBuildpack(t *testing.T, when spec.G, it spec.S) { buildpackPath = filepath.Join(tmpDir, "buildpackTarFile.tar") expectedInfo = &client.BuildpackInfo{ - BuildpackMetadata: buildpackage.Metadata{ + BuildpackMetadata: buildpack.Metadata{ BuildpackInfo: dist.BuildpackInfo{ ID: "some/top-buildpack", Version: "0.0.1", @@ -627,7 +626,7 @@ func writeBuildpackArchive(buildpackPath, tmpDir string, assert h.AssertionManag assert.Nil(err) c.Config.Labels = map[string]string{} - c.Config.Labels[buildpackage.MetadataLabel] = buildpackageMetadataTag + c.Config.Labels[buildpack.MetadataLabel] = buildpackageMetadataTag c.Config.Labels[dist.BuildpackLayersLabel] = buildpackLayersTag img, err = mutate.Config(img, c.Config) assert.Nil(err) diff --git a/pkg/client/inspect_image.go b/pkg/client/inspect_image.go index 7566dc265d..c881dc20a3 100644 --- a/pkg/client/inspect_image.go +++ b/pkg/client/inspect_image.go @@ -10,7 +10,7 @@ import ( "github.com/buildpacks/lifecycle/platform" "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) diff --git a/pkg/client/inspect_image_test.go b/pkg/client/inspect_image_test.go index e2e723c1f9..b6184495ba 100644 --- a/pkg/client/inspect_image_test.go +++ b/pkg/client/inspect_image_test.go @@ -15,8 +15,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/new_buildpack.go b/pkg/client/new_buildpack.go index 95e130b2e6..df85eb0168 100644 --- a/pkg/client/new_buildpack.go +++ b/pkg/client/new_buildpack.go @@ -10,8 +10,8 @@ import ( "github.com/buildpacks/lifecycle/api" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/dist" ) var ( diff --git a/pkg/client/new_buildpack_test.go b/pkg/client/new_buildpack_test.go index a8352119e7..084e904814 100644 --- a/pkg/client/new_buildpack_test.go +++ b/pkg/client/new_buildpack_test.go @@ -14,8 +14,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/package_buildpack.go b/pkg/client/package_buildpack.go index b57ddc1fc9..c3bc8fab83 100644 --- a/pkg/client/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -6,8 +6,6 @@ import ( "github.com/pkg/errors" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" @@ -74,7 +72,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti return errors.Wrap(err, "creating layer writer factory") } - packageBuilder := buildpackage.NewBuilder(c.imageFactory) + packageBuilder := buildpack.NewBuilder(c.imageFactory) bpURI := opts.Config.Buildpack.URI if bpURI == "" { @@ -86,7 +84,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti return err } - bp, err := dist.BuildpackFromRootBlob(mainBlob, writerFactory) + bp, err := buildpack.BuildpackFromRootBlob(mainBlob, writerFactory) if err != nil { return errors.Wrapf(err, "creating buildpack from %s", style.Symbol(bpURI)) } @@ -94,7 +92,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti packageBuilder.SetBuildpack(bp) for _, dep := range opts.Config.Dependencies { - var depBPs []dist.Buildpack + var depBPs []buildpack.Buildpack mainBP, deps, err := c.buildpackDownloader.Download(ctx, dep.URI, buildpack.DownloadOptions{ RegistryName: opts.Registry, RelativeBaseDir: opts.RelativeBaseDir, @@ -108,7 +106,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti return errors.Wrapf(err, "packaging dependencies (uri=%s,image=%s)", style.Symbol(dep.URI), style.Symbol(dep.ImageName)) } - depBPs = append([]dist.Buildpack{mainBP}, deps...) + depBPs = append([]buildpack.Buildpack{mainBP}, deps...) for _, depBP := range depBPs { packageBuilder.AddDependency(depBP) } diff --git a/pkg/client/package_buildpack_test.go b/pkg/client/package_buildpack_test.go index 7744854682..cd47a61180 100644 --- a/pkg/client/package_buildpack_test.go +++ b/pkg/client/package_buildpack_test.go @@ -19,15 +19,15 @@ import ( "github.com/sclevine/spec/report" pubbldpkg "github.com/buildpacks/pack/buildpackage" - "github.com/buildpacks/pack/internal/buildpackage" cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/dist" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/buildpack" "github.com/buildpacks/pack/pkg/client" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) @@ -799,7 +799,7 @@ func testPackageBuildpack(t *testing.T, when spec.G, it spec.S) { func assertPackageBPFileHasBuildpacks(t *testing.T, path string, descriptors []dist.BuildpackDescriptor) { packageBlob := blob.NewBlob(path) - mainBP, depBPs, err := buildpackage.BuildpacksFromOCILayoutBlob(packageBlob) + mainBP, depBPs, err := buildpack.BuildpacksFromOCILayoutBlob(packageBlob) h.AssertNil(t, err) - h.AssertBuildpacksHaveDescriptors(t, append([]dist.Buildpack{mainBP}, depBPs...), descriptors) + h.AssertBuildpacksHaveDescriptors(t, append([]buildpack.Buildpack{mainBP}, depBPs...), descriptors) } diff --git a/pkg/client/pull_buildpack.go b/pkg/client/pull_buildpack.go index 868ab16d27..d3942fbcfb 100644 --- a/pkg/client/pull_buildpack.go +++ b/pkg/client/pull_buildpack.go @@ -6,9 +6,9 @@ import ( "github.com/pkg/errors" - "github.com/buildpacks/pack/internal/buildpack" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) diff --git a/pkg/client/pull_buildpack_test.go b/pkg/client/pull_buildpack_test.go index a62707ecee..f1d1e023ff 100644 --- a/pkg/client/pull_buildpack_test.go +++ b/pkg/client/pull_buildpack_test.go @@ -15,10 +15,10 @@ import ( "github.com/sclevine/spec/report" cfg "github.com/buildpacks/pack/internal/config" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" "github.com/buildpacks/pack/pkg/testmocks" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/rebase.go b/pkg/client/rebase.go index 3eb0b3680a..a244c9fc67 100644 --- a/pkg/client/rebase.go +++ b/pkg/client/rebase.go @@ -9,8 +9,8 @@ import ( "github.com/buildpacks/pack/internal/build" "github.com/buildpacks/pack/internal/builder" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/style" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) diff --git a/pkg/client/rebase_test.go b/pkg/client/rebase_test.go index 103242e1b4..286d6dc0e5 100644 --- a/pkg/client/rebase_test.go +++ b/pkg/client/rebase_test.go @@ -11,8 +11,8 @@ import ( "github.com/sclevine/spec/report" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/register_buildpack.go b/pkg/client/register_buildpack.go index 9df1e0c08d..1bae8e5d96 100644 --- a/pkg/client/register_buildpack.go +++ b/pkg/client/register_buildpack.go @@ -7,9 +7,9 @@ import ( "runtime" "strings" - "github.com/buildpacks/pack/internal/buildpackage" - "github.com/buildpacks/pack/internal/dist" "github.com/buildpacks/pack/internal/registry" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" "github.com/buildpacks/pack/pkg/image" ) @@ -31,7 +31,7 @@ func (c *Client) RegisterBuildpack(ctx context.Context, opts RegisterBuildpackOp } var buildpackInfo dist.BuildpackInfo - if _, err := dist.GetLabel(appImage, buildpackage.MetadataLabel, &buildpackInfo); err != nil { + if _, err := dist.GetLabel(appImage, buildpack.MetadataLabel, &buildpackInfo); err != nil { return err } diff --git a/pkg/client/register_buildpack_test.go b/pkg/client/register_buildpack_test.go index db7cc84cd2..1a2e883047 100644 --- a/pkg/client/register_buildpack_test.go +++ b/pkg/client/register_buildpack_test.go @@ -11,8 +11,8 @@ import ( "github.com/sclevine/spec/report" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/internal/registry" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/client/yank_buildpack_test.go b/pkg/client/yank_buildpack_test.go index 314d3259b0..c080754694 100644 --- a/pkg/client/yank_buildpack_test.go +++ b/pkg/client/yank_buildpack_test.go @@ -10,7 +10,7 @@ import ( "github.com/sclevine/spec/report" ifakes "github.com/buildpacks/pack/internal/fakes" - "github.com/buildpacks/pack/internal/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/dist/buildpack.go b/pkg/dist/buildpack.go new file mode 100644 index 0000000000..4042c717d7 --- /dev/null +++ b/pkg/dist/buildpack.go @@ -0,0 +1,39 @@ +package dist + +const AssumedBuildpackAPIVersion = "0.1" +const BuildpacksDir = "/cnb/buildpacks" + +type BuildpackInfo struct { + ID string `toml:"id,omitempty" json:"id,omitempty" yaml:"id,omitempty"` + Name string `toml:"name,omitempty" json:"name,omitempty" yaml:"name,omitempty"` + Version string `toml:"version,omitempty" json:"version,omitempty" yaml:"version,omitempty"` + Description string `toml:"description,omitempty" json:"description,omitempty" yaml:"description,omitempty"` + Homepage string `toml:"homepage,omitempty" json:"homepage,omitempty" yaml:"homepage,omitempty"` + Keywords []string `toml:"keywords,omitempty" json:"keywords,omitempty" yaml:"keywords,omitempty"` + Licenses []License `toml:"licenses,omitempty" json:"licenses,omitempty" yaml:"licenses,omitempty"` +} + +func (b BuildpackInfo) FullName() string { + if b.Version != "" { + return b.ID + "@" + b.Version + } + return b.ID +} + +// Satisfy stringer +func (b BuildpackInfo) String() string { return b.FullName() } + +// Match compares two buildpacks by ID and Version +func (b BuildpackInfo) Match(o BuildpackInfo) bool { + return b.ID == o.ID && b.Version == o.Version +} + +type License struct { + Type string `toml:"type"` + URI string `toml:"uri"` +} + +type Stack struct { + ID string `json:"id" toml:"id"` + Mixins []string `json:"mixins,omitempty" toml:"mixins,omitempty"` +} diff --git a/internal/dist/buildpack_descriptor.go b/pkg/dist/buildpack_descriptor.go similarity index 100% rename from internal/dist/buildpack_descriptor.go rename to pkg/dist/buildpack_descriptor.go diff --git a/internal/dist/buildpack_descriptor_test.go b/pkg/dist/buildpack_descriptor_test.go similarity index 98% rename from internal/dist/buildpack_descriptor_test.go rename to pkg/dist/buildpack_descriptor_test.go index ef28ac216a..c45898c2b6 100644 --- a/internal/dist/buildpack_descriptor_test.go +++ b/pkg/dist/buildpack_descriptor_test.go @@ -7,7 +7,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/dist/dist.go b/pkg/dist/dist.go similarity index 76% rename from internal/dist/dist.go rename to pkg/dist/dist.go index 4a09277a27..6ccee5bcc9 100644 --- a/internal/dist/dist.go +++ b/pkg/dist/dist.go @@ -67,18 +67,3 @@ func (b BuildpackLayers) Get(id, version string) (BuildpackLayerInfo, bool) { result, ok := buildpackLayerEntries[version] return result, ok } - -func AddBuildpackToLayersMD(layerMD BuildpackLayers, descriptor BuildpackDescriptor, diffID string) { - bpInfo := descriptor.Info - if _, ok := layerMD[bpInfo.ID]; !ok { - layerMD[bpInfo.ID] = map[string]BuildpackLayerInfo{} - } - layerMD[bpInfo.ID][bpInfo.Version] = BuildpackLayerInfo{ - API: descriptor.API, - Stacks: descriptor.Stacks, - Order: descriptor.Order, - LayerDiffID: diffID, - Homepage: bpInfo.Homepage, - Name: bpInfo.Name, - } -} diff --git a/internal/dist/dist_test.go b/pkg/dist/dist_test.go similarity index 98% rename from internal/dist/dist_test.go rename to pkg/dist/dist_test.go index 1283f5e956..e8cb94fdf4 100644 --- a/internal/dist/dist_test.go +++ b/pkg/dist/dist_test.go @@ -8,7 +8,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/dist" + "github.com/buildpacks/pack/pkg/dist" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/pkg/dist/distribution.go b/pkg/dist/distribution.go new file mode 100644 index 0000000000..b9232771b8 --- /dev/null +++ b/pkg/dist/distribution.go @@ -0,0 +1,3 @@ +// Package dist is responsible for cataloging all data types in relation +// to distributing Cloud Native Buildpack components. +package dist diff --git a/internal/dist/image.go b/pkg/dist/image.go similarity index 100% rename from internal/dist/image.go rename to pkg/dist/image.go diff --git a/internal/dist/layers.go b/pkg/dist/layers.go similarity index 52% rename from internal/dist/layers.go rename to pkg/dist/layers.go index 3609ef36b5..873f86ca4f 100644 --- a/internal/dist/layers.go +++ b/pkg/dist/layers.go @@ -1,8 +1,6 @@ package dist import ( - "fmt" - "io" "os" "path/filepath" @@ -11,28 +9,6 @@ import ( "github.com/pkg/errors" ) -func BuildpackToLayerTar(dest string, bp Buildpack) (string, error) { - bpd := bp.Descriptor() - bpReader, err := bp.Open() - if err != nil { - return "", errors.Wrap(err, "opening buildpack blob") - } - defer bpReader.Close() - - layerTar := filepath.Join(dest, fmt.Sprintf("%s.%s.tar", bpd.EscapedID(), bpd.Info.Version)) - fh, err := os.Create(layerTar) - if err != nil { - return "", errors.Wrap(err, "create file for tar") - } - defer fh.Close() - - if _, err := io.Copy(fh, bpReader); err != nil { - return "", errors.Wrap(err, "writing buildpack blob to tar") - } - - return layerTar, nil -} - func LayerDiffID(layerTarPath string) (v1.Hash, error) { fh, err := os.Open(filepath.Clean(layerTarPath)) if err != nil { @@ -52,3 +28,18 @@ func LayerDiffID(layerTarPath string) (v1.Hash, error) { return hash, nil } + +func AddBuildpackToLayersMD(layerMD BuildpackLayers, descriptor BuildpackDescriptor, diffID string) { + bpInfo := descriptor.Info + if _, ok := layerMD[bpInfo.ID]; !ok { + layerMD[bpInfo.ID] = map[string]BuildpackLayerInfo{} + } + layerMD[bpInfo.ID][bpInfo.Version] = BuildpackLayerInfo{ + API: descriptor.API, + Stacks: descriptor.Stacks, + Order: descriptor.Order, + LayerDiffID: diffID, + Homepage: bpInfo.Homepage, + Name: bpInfo.Name, + } +} diff --git a/pkg/image/fetcher.go b/pkg/image/fetcher.go index 14f4e71238..09990517af 100644 --- a/pkg/image/fetcher.go +++ b/pkg/image/fetcher.go @@ -17,10 +17,10 @@ import ( "github.com/google/go-containerregistry/pkg/authn" "github.com/pkg/errors" - ilogging "github.com/buildpacks/pack/internal/logging" pname "github.com/buildpacks/pack/internal/name" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/internal/term" + "github.com/buildpacks/pack/pkg/logging" ) // FetcherOption is a type of function that mutate settings on the client. @@ -133,7 +133,7 @@ func (f *Fetcher) pullImage(ctx context.Context, imageID string, platform string } writer := logging.GetWriterForLevel(f.logger, logging.InfoLevel) - termFd, isTerm := ilogging.IsTerminal(writer) + termFd, isTerm := term.IsTerminal(writer) err = jsonmessage.DisplayJSONMessagesStream(rc, &colorizedWriter{writer}, termFd, isTerm, nil) if err != nil { diff --git a/pkg/image/fetcher_test.go b/pkg/image/fetcher_test.go index c7e7b7206b..4d4d4c0a34 100644 --- a/pkg/image/fetcher_test.go +++ b/pkg/image/fetcher_test.go @@ -17,8 +17,8 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/internal/logging" "github.com/buildpacks/pack/pkg/image" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/logging/default_logger.go b/pkg/logging/logger_simple.go similarity index 51% rename from logging/default_logger.go rename to pkg/logging/logger_simple.go index 02684eebaa..beb18e72e6 100644 --- a/logging/default_logger.go +++ b/pkg/logging/logger_simple.go @@ -6,14 +6,14 @@ import ( "log" ) -// New creates a default logger for the pack library. Note that the pack CLI has it's own logger. -func New(w io.Writer) Logger { - return &defaultLogger{ +// NewSimpleLogger creates a simple logger for the pack library. +func NewSimpleLogger(w io.Writer) Logger { + return &simpleLogger{ out: log.New(w, "", log.LstdFlags|log.Lmicroseconds), } } -type defaultLogger struct { +type simpleLogger struct { out *log.Logger } @@ -25,42 +25,42 @@ const ( prefixFmt = "%-7s %s" ) -func (l *defaultLogger) Debug(msg string) { +func (l *simpleLogger) Debug(msg string) { l.out.Printf(prefixFmt, debugPrefix, msg) } -func (l *defaultLogger) Debugf(format string, v ...interface{}) { +func (l *simpleLogger) Debugf(format string, v ...interface{}) { l.out.Printf(prefixFmt, debugPrefix, fmt.Sprintf(format, v...)) } -func (l *defaultLogger) Info(msg string) { +func (l *simpleLogger) Info(msg string) { l.out.Printf(prefixFmt, infoPrefix, msg) } -func (l *defaultLogger) Infof(format string, v ...interface{}) { +func (l *simpleLogger) Infof(format string, v ...interface{}) { l.out.Printf(prefixFmt, infoPrefix, fmt.Sprintf(format, v...)) } -func (l *defaultLogger) Warn(msg string) { +func (l *simpleLogger) Warn(msg string) { l.out.Printf(prefixFmt, warnPrefix, msg) } -func (l *defaultLogger) Warnf(format string, v ...interface{}) { +func (l *simpleLogger) Warnf(format string, v ...interface{}) { l.out.Printf(prefixFmt, warnPrefix, fmt.Sprintf(format, v...)) } -func (l *defaultLogger) Error(msg string) { +func (l *simpleLogger) Error(msg string) { l.out.Printf(prefixFmt, errorPrefix, msg) } -func (l *defaultLogger) Errorf(format string, v ...interface{}) { +func (l *simpleLogger) Errorf(format string, v ...interface{}) { l.out.Printf(prefixFmt, errorPrefix, fmt.Sprintf(format, v...)) } -func (l *defaultLogger) Writer() io.Writer { +func (l *simpleLogger) Writer() io.Writer { return l.out.Writer() } -func (l *defaultLogger) IsVerbose() bool { +func (l *simpleLogger) IsVerbose() bool { return false } diff --git a/logging/default_logger_test.go b/pkg/logging/logger_simple_test.go similarity index 88% rename from logging/default_logger_test.go rename to pkg/logging/logger_simple_test.go index dcdb0ea7a6..48fdcaddbd 100644 --- a/logging/default_logger_test.go +++ b/pkg/logging/logger_simple_test.go @@ -1,4 +1,4 @@ -package logging +package logging_test import ( "bytes" @@ -6,6 +6,7 @@ import ( "github.com/sclevine/spec" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -16,13 +17,13 @@ const ( errorMatcher = `^\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}:\d{2}\.\d{6} ERROR: \w*\n$` ) -func TestDefaultLogger(t *testing.T) { - spec.Run(t, "DefaultLogger", func(t *testing.T, when spec.G, it spec.S) { +func TestSimpleLogger(t *testing.T) { + spec.Run(t, "SimpleLogger", func(t *testing.T, when spec.G, it spec.S) { var w bytes.Buffer - var logger Logger + var logger logging.Logger it.Before(func() { - logger = New(&w) + logger = logging.NewSimpleLogger(&w) }) it.After(func() { diff --git a/internal/logging/logging.go b/pkg/logging/logger_writers.go similarity index 63% rename from internal/logging/logging.go rename to pkg/logging/logger_writers.go index 6a0f64526f..dceb66c462 100644 --- a/internal/logging/logging.go +++ b/pkg/logging/logger_writers.go @@ -5,14 +5,14 @@ import ( "fmt" "io" "io/ioutil" + "regexp" "sync" "time" "github.com/apex/log" - "golang.org/x/term" + "github.com/heroku/color" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" ) const ( @@ -29,6 +29,10 @@ const ( InvalidFileDescriptor = ^(uintptr(0)) ) +var colorCodeMatcher = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +var _ Logger = (*LogWithWriters)(nil) + // LogWithWriters is a logger used with the pack CLI, allowing users to print logs for various levels, including Info, Debug and Error type LogWithWriters struct { sync.Mutex @@ -78,23 +82,23 @@ func (lw *LogWithWriters) HandleLog(e *log.Entry) error { lw.Lock() defer lw.Unlock() - writer := lw.WriterForLevel(logging.Level(e.Level)) + writer := lw.WriterForLevel(Level(e.Level)) _, err := fmt.Fprint(writer, appendMissingLineFeed(fmt.Sprintf("%s%s", formatLevel(e.Level), e.Message))) return err } -// WriterForLevel returns a Writer for the given logging.Level -func (lw *LogWithWriters) WriterForLevel(level logging.Level) io.Writer { +// WriterForLevel returns a Writer for the given Level +func (lw *LogWithWriters) WriterForLevel(level Level) io.Writer { if lw.Level > log.Level(level) { return ioutil.Discard } - if level == logging.ErrorLevel { - return NewLogWriter(lw.errOut, lw.clock, lw.wantTime) + if level == ErrorLevel { + return newLogWriter(lw.errOut, lw.clock, lw.wantTime) } - return NewLogWriter(lw.out, lw.clock, lw.wantTime) + return newLogWriter(lw.out, lw.clock, lw.wantTime) } // Writer returns the base Writer for the LogWithWriters @@ -126,17 +130,6 @@ func (lw *LogWithWriters) IsVerbose() bool { return lw.Level == log.DebugLevel } -// IsTerminal returns whether a writer is a terminal -func IsTerminal(w io.Writer) (uintptr, bool) { - if f, ok := w.(hasDescriptor); ok { - termFd := f.Fd() - isTerm := term.IsTerminal(int(termFd)) - return termFd, isTerm - } - - return InvalidFileDescriptor, false -} - func formatLevel(ll log.Level) string { switch ll { case log.ErrorLevel: @@ -156,3 +149,67 @@ func appendMissingLineFeed(msg string) string { } return string(buff) } + +// logWriter is a writer used for logs +type logWriter struct { + sync.Mutex + out io.Writer + clock func() time.Time + wantTime bool + wantNoColor bool +} + +func newLogWriter(writer io.Writer, clock func() time.Time, wantTime bool) *logWriter { + wantNoColor := !color.Enabled() + return &logWriter{ + out: writer, + clock: clock, + wantTime: wantTime, + wantNoColor: wantNoColor, + } +} + +// Write writes a message prepended by the time to the set io.Writer +func (lw *logWriter) Write(buf []byte) (n int, err error) { + lw.Lock() + defer lw.Unlock() + + length := len(buf) + if lw.wantNoColor { + buf = stripColor(buf) + } + + prefix := "" + if lw.wantTime { + prefix = fmt.Sprintf("%s ", lw.clock().Format(timeFmt)) + } + + _, err = fmt.Fprintf(lw.out, "%s%s", prefix, buf) + return length, err +} + +// Writer returns the base Writer for the logWriter +func (lw *logWriter) Writer() io.Writer { + return lw.out +} + +// Fd returns the file descriptor of the writer. This is used to ensure it is a Console, and can therefore display streams of text +func (lw *logWriter) Fd() uintptr { + lw.Lock() + defer lw.Unlock() + + if file, ok := lw.out.(hasDescriptor); ok { + return file.Fd() + } + + return InvalidFileDescriptor +} + +// Remove all ANSI color information. +func stripColor(b []byte) []byte { + return colorCodeMatcher.ReplaceAll(b, []byte("")) +} + +type hasDescriptor interface { + Fd() uintptr +} diff --git a/internal/logging/logging_test.go b/pkg/logging/logger_writers_test.go similarity index 83% rename from internal/logging/logging_test.go rename to pkg/logging/logger_writers_test.go index 881aa28f1a..42a6a63b5d 100644 --- a/internal/logging/logging_test.go +++ b/pkg/logging/logger_writers_test.go @@ -1,7 +1,6 @@ -package logging +package logging_test import ( - "bytes" "fmt" "io" "io/ioutil" @@ -14,29 +13,27 @@ import ( "github.com/sclevine/spec/report" "github.com/buildpacks/pack/internal/style" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) -const ( - testTime = "2019/05/15 01:01:01.000000" -) - func TestLogWithWriters(t *testing.T) { spec.Run(t, "LogWithWriters", testLogWithWriters, spec.Parallel(), spec.Report(report.Terminal{})) } func testLogWithWriters(t *testing.T, when spec.G, it spec.S) { var ( - logger *LogWithWriters + logger *logging.LogWithWriters outCons, errCons *color.Console fOut, fErr func() string + timeFmt = "2006/01/02 15:04:05.000000" + testTime = "2019/05/15 01:01:01.000000" ) it.Before(func() { outCons, fOut = h.MockWriterAndOutput() errCons, fErr = h.MockWriterAndOutput() - logger = NewLogWithWriters(outCons, errCons, WithClock(func() time.Time { + logger = logging.NewLogWithWriters(outCons, errCons, logging.WithClock(func() time.Time { clock, _ := time.Parse(timeFmt, testTime) return clock })) @@ -82,8 +79,6 @@ func testLogWithWriters(t *testing.T, when spec.G, it spec.S) { it("will return correct writers", func() { h.AssertSameInstance(t, logger.Writer(), outCons) h.AssertSameInstance(t, logger.WriterForLevel(logging.DebugLevel), ioutil.Discard) - assertLogWriterHasOut(t, logger.WriterForLevel(logging.InfoLevel), outCons) - assertLogWriterHasOut(t, logger.WriterForLevel(logging.ErrorLevel), errCons) }) it("is only verbose for debug level", func() { @@ -173,8 +168,6 @@ func testLogWithWriters(t *testing.T, when spec.G, it spec.S) { h.AssertSameInstance(t, logger.Writer(), outCons) h.AssertSameInstance(t, logger.WriterForLevel(logging.DebugLevel), ioutil.Discard) h.AssertSameInstance(t, logger.WriterForLevel(logging.InfoLevel), ioutil.Discard) - assertLogWriterHasOut(t, logger.WriterForLevel(logging.WarnLevel), outCons) - assertLogWriterHasOut(t, logger.WriterForLevel(logging.ErrorLevel), errCons) }) }) @@ -223,24 +216,14 @@ func testLogWithWriters(t *testing.T, when spec.G, it spec.S) { expected := "\n" h.AssertEq(t, fOut(), expected) }) - - when("IsTerminal", func() { - it("returns false for a pipe", func() { - fd, isTerm := IsTerminal(logger.WriterForLevel(logging.InfoLevel)) - h.AssertFalse(t, isTerm) - h.AssertNotEq(t, fd, InvalidFileDescriptor) //The mock writer is a pipe, and therefore has a file descriptor - }) - - it("returns InvalidFileDescriptor if passed a normal Writer", func() { - fd, isTerm := IsTerminal(&bytes.Buffer{}) - h.AssertFalse(t, isTerm) - h.AssertEq(t, fd, InvalidFileDescriptor) - }) - }) } func assertLogWriterHasOut(t *testing.T, writer io.Writer, out io.Writer) { - logWriter, ok := writer.(*LogWriter) + logWriter, ok := writer.(hasWriter) h.AssertTrue(t, ok) - h.AssertSameInstance(t, logWriter.out, out) + h.AssertSameInstance(t, logWriter.Writer(), out) +} + +type hasWriter interface { + Writer() io.Writer } diff --git a/logging/logging.go b/pkg/logging/logging.go similarity index 81% rename from logging/logging.go rename to pkg/logging/logging.go index bcf63be8c7..6d9a026950 100644 --- a/logging/logging.go +++ b/pkg/logging/logging.go @@ -36,17 +36,16 @@ type Logger interface { IsVerbose() bool } -// WithSelectableWriter is an optional interface for loggers that want to support a separate writer per log level. -type WithSelectableWriter interface { +type isSelectableWriter interface { WriterForLevel(level Level) io.Writer } // GetWriterForLevel retrieves the appropriate Writer for the log level provided. // -// See WithSelectableWriter +// See isSelectableWriter func GetWriterForLevel(logger Logger, level Level) io.Writer { - if er, ok := logger.(WithSelectableWriter); ok { - return er.WriterForLevel(level) + if w, ok := logger.(isSelectableWriter); ok { + return w.WriterForLevel(level) } return logger.Writer() diff --git a/logging/logging_test.go b/pkg/logging/logging_test.go similarity index 79% rename from logging/logging_test.go rename to pkg/logging/logging_test.go index 675fde4274..46b861a473 100644 --- a/logging/logging_test.go +++ b/pkg/logging/logging_test.go @@ -8,8 +8,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - ilogging "github.com/buildpacks/pack/internal/logging" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) @@ -21,11 +20,11 @@ func TestLogging(t *testing.T) { func testLogging(t *testing.T, when spec.G, it spec.S) { when("#GetWriterForLevel", func() { - when("implements WithSelectableWriter", func() { + when("isSelectableWriter", func() { it("returns Logger for appropriate level", func() { outCons, output := h.MockWriterAndOutput() errCons, errOutput := h.MockWriterAndOutput() - logger := ilogging.NewLogWithWriters(outCons, errCons) + logger := logging.NewLogWithWriters(outCons, errCons) infoLogger := logging.GetWriterForLevel(logger, logging.InfoLevel) _, _ = infoLogger.Write([]byte("info test")) @@ -37,10 +36,10 @@ func testLogging(t *testing.T, when spec.G, it spec.S) { }) }) - when("doesn't implement WithSelectableWriter", func() { + when("doesn't implement isSelectableWriter", func() { it("returns one Writer for all levels", func() { var w bytes.Buffer - logger := logging.New(&w) + logger := logging.NewSimpleLogger(&w) writer := logging.GetWriterForLevel(logger, logging.InfoLevel) _, _ = writer.Write([]byte("info test\n")) h.AssertEq(t, w.String(), "info test\n") @@ -53,10 +52,10 @@ func testLogging(t *testing.T, when spec.G, it spec.S) { }) when("IsQuiet", func() { - when("implements WithSelectableWriter", func() { + when("implements isSelectableWriter", func() { it("return true for quiet mode", func() { var w bytes.Buffer - logger := ilogging.NewLogWithWriters(&w, &w) + logger := logging.NewLogWithWriters(&w, &w) h.AssertEq(t, logging.IsQuiet(logger), false) logger.WantQuiet(true) @@ -64,10 +63,10 @@ func testLogging(t *testing.T, when spec.G, it spec.S) { }) }) - when("doesn't implement WithSelectableWriter", func() { + when("doesn't implement isSelectableWriter", func() { it("always returns false", func() { var w bytes.Buffer - logger := logging.New(&w) + logger := logging.NewSimpleLogger(&w) h.AssertEq(t, logging.IsQuiet(logger), false) }) }) @@ -76,7 +75,7 @@ func testLogging(t *testing.T, when spec.G, it spec.S) { when("#Tip", func() { it("prepends `Tip:` to string", func() { var w bytes.Buffer - logger := logging.New(&w) + logger := logging.NewSimpleLogger(&w) logging.Tip(logger, "test") h.AssertContains(t, w.String(), "Tip: "+"test") }) diff --git a/logging/prefix_writer.go b/pkg/logging/prefix_writer.go similarity index 100% rename from logging/prefix_writer.go rename to pkg/logging/prefix_writer.go diff --git a/logging/prefix_writer_test.go b/pkg/logging/prefix_writer_test.go similarity index 98% rename from logging/prefix_writer_test.go rename to pkg/logging/prefix_writer_test.go index a7dc9a8efb..34badea8ac 100644 --- a/logging/prefix_writer_test.go +++ b/pkg/logging/prefix_writer_test.go @@ -10,7 +10,7 @@ import ( "github.com/sclevine/spec" "github.com/sclevine/spec/report" - "github.com/buildpacks/pack/logging" + "github.com/buildpacks/pack/pkg/logging" h "github.com/buildpacks/pack/testhelpers" ) diff --git a/internal/dist/testmocks/mock_buildpack.go b/pkg/testmocks/mock_buildpack.go similarity index 94% rename from internal/dist/testmocks/mock_buildpack.go rename to pkg/testmocks/mock_buildpack.go index efa16e5841..8480199e5e 100644 --- a/internal/dist/testmocks/mock_buildpack.go +++ b/pkg/testmocks/mock_buildpack.go @@ -1,11 +1,11 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/buildpacks/pack/internal/dist (interfaces: Buildpack) +// Source: github.com/buildpacks/pack/pkg/buildpack (interfaces: Buildpack) // Package testmocks is a generated GoMock package. package testmocks import ( - dist "github.com/buildpacks/pack/internal/dist" + dist "github.com/buildpacks/pack/pkg/dist" gomock "github.com/golang/mock/gomock" io "io" reflect "reflect" diff --git a/pkg/testmocks/mock_buildpack_downloader.go b/pkg/testmocks/mock_buildpack_downloader.go index 11d8f834d4..1e4ddde4f0 100644 --- a/pkg/testmocks/mock_buildpack_downloader.go +++ b/pkg/testmocks/mock_buildpack_downloader.go @@ -6,7 +6,6 @@ package testmocks import ( context "context" - dist "github.com/buildpacks/pack/internal/dist" buildpack "github.com/buildpacks/pack/pkg/buildpack" gomock "github.com/golang/mock/gomock" reflect "reflect" @@ -36,11 +35,11 @@ func (m *MockBuildpackDownloader) EXPECT() *MockBuildpackDownloaderMockRecorder } // Download mocks base method -func (m *MockBuildpackDownloader) Download(arg0 context.Context, arg1 string, arg2 buildpack.DownloadOptions) (dist.Buildpack, []dist.Buildpack, error) { +func (m *MockBuildpackDownloader) Download(arg0 context.Context, arg1 string, arg2 buildpack.DownloadOptions) (buildpack.Buildpack, []buildpack.Buildpack, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Download", arg0, arg1, arg2) - ret0, _ := ret[0].(dist.Buildpack) - ret1, _ := ret[1].([]dist.Buildpack) + ret0, _ := ret[0].(buildpack.Buildpack) + ret1, _ := ret[1].([]buildpack.Buildpack) ret2, _ := ret[2].(error) return ret0, ret1, ret2 } diff --git a/pkg/testmocks/mock_registry_resolver.go b/pkg/testmocks/mock_registry_resolver.go index 9cc98219fb..3697c9de0d 100644 --- a/pkg/testmocks/mock_registry_resolver.go +++ b/pkg/testmocks/mock_registry_resolver.go @@ -1,5 +1,5 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/buildpacks/pack/pkg/buildpack/downloader (interfaces: RegistryResolver) +// Source: github.com/buildpacks/pack/pkg/buildpack (interfaces: RegistryResolver) // Package testmocks is a generated GoMock package. package testmocks diff --git a/testhelpers/testhelpers.go b/testhelpers/testhelpers.go index d574b0ca66..f87cefd2a9 100644 --- a/testhelpers/testhelpers.go +++ b/testhelpers/testhelpers.go @@ -32,11 +32,11 @@ import ( "github.com/pkg/errors" "gopkg.in/src-d/go-git.v4" - "github.com/buildpacks/pack/internal/dist" - "github.com/buildpacks/pack/internal/stringset" "github.com/buildpacks/pack/internal/style" "github.com/buildpacks/pack/pkg/archive" + "github.com/buildpacks/pack/pkg/buildpack" + "github.com/buildpacks/pack/pkg/dist" ) func RandString(n int) string { @@ -786,7 +786,7 @@ func tarHasFile(t *testing.T, tarFile, path string) (exist bool) { return false } -func AssertBuildpacksHaveDescriptors(t *testing.T, bps []dist.Buildpack, descriptors []dist.BuildpackDescriptor) { +func AssertBuildpacksHaveDescriptors(t *testing.T, bps []buildpack.Buildpack, descriptors []dist.BuildpackDescriptor) { AssertEq(t, len(bps), len(descriptors)) for _, bp := range bps { found := false diff --git a/testmocks/mock_registry_resolver.go b/testmocks/mock_registry_resolver.go deleted file mode 100644 index 3697c9de0d..0000000000 --- a/testmocks/mock_registry_resolver.go +++ /dev/null @@ -1,48 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/buildpacks/pack/pkg/buildpack (interfaces: RegistryResolver) - -// Package testmocks is a generated GoMock package. -package testmocks - -import ( - gomock "github.com/golang/mock/gomock" - reflect "reflect" -) - -// MockRegistryResolver is a mock of RegistryResolver interface -type MockRegistryResolver struct { - ctrl *gomock.Controller - recorder *MockRegistryResolverMockRecorder -} - -// MockRegistryResolverMockRecorder is the mock recorder for MockRegistryResolver -type MockRegistryResolverMockRecorder struct { - mock *MockRegistryResolver -} - -// NewMockRegistryResolver creates a new mock instance -func NewMockRegistryResolver(ctrl *gomock.Controller) *MockRegistryResolver { - mock := &MockRegistryResolver{ctrl: ctrl} - mock.recorder = &MockRegistryResolverMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use -func (m *MockRegistryResolver) EXPECT() *MockRegistryResolverMockRecorder { - return m.recorder -} - -// Resolve mocks base method -func (m *MockRegistryResolver) Resolve(arg0, arg1 string) (string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Resolve", arg0, arg1) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Resolve indicates an expected call of Resolve -func (mr *MockRegistryResolverMockRecorder) Resolve(arg0, arg1 interface{}) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Resolve", reflect.TypeOf((*MockRegistryResolver)(nil).Resolve), arg0, arg1) -} From 533c4e19ea07cf2d507206a9e0c652125074606d Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Mon, 1 Nov 2021 13:47:44 -0500 Subject: [PATCH 08/15] Adjust acceptance tests to new package restructure Signed-off-by: Javier Romero --- acceptance/config/github_asset_fetcher.go | 6 ++-- internal/builder/builder.go | 2 +- internal/builder/testmocks/mock_lifecycle.go | 6 ++-- .../mock_inspect_image_writer_factory.go | 6 ++-- .../commands/testmocks/mock_pack_client.go | 6 ++-- internal/fakes/fake_package.go | 2 +- internal/term/term_test.go | 5 ---- pkg/buildpack/builder.go | 2 +- pkg/buildpack/buildpack.go | 10 +++---- pkg/buildpack/buildpack_test.go | 26 ++++++++--------- pkg/buildpack/downloader.go | 3 +- pkg/buildpack/package.go | 4 +-- pkg/client/client.go | 28 +++++++++---------- pkg/client/create_builder_test.go | 6 ++-- pkg/client/example_fetcher_test.go | 1 + pkg/client/package_buildpack.go | 2 +- pkg/testmocks/mock_blob_downloader.go | 6 ++-- pkg/testmocks/mock_buildpack.go | 6 ++-- pkg/testmocks/mock_buildpack_downloader.go | 6 ++-- pkg/testmocks/mock_docker_client.go | 11 ++++---- pkg/testmocks/mock_image_factory.go | 3 +- pkg/testmocks/mock_image_fetcher.go | 6 ++-- pkg/testmocks/mock_registry_resolver.go | 3 +- 23 files changed, 85 insertions(+), 71 deletions(-) diff --git a/acceptance/config/github_asset_fetcher.go b/acceptance/config/github_asset_fetcher.go index 0cb67f7f46..7d4182d1c1 100644 --- a/acceptance/config/github_asset_fetcher.go +++ b/acceptance/config/github_asset_fetcher.go @@ -26,8 +26,8 @@ import ( "github.com/pkg/errors" "golang.org/x/oauth2" - "github.com/buildpacks/pack/logging" "github.com/buildpacks/pack/pkg/blob" + "github.com/buildpacks/pack/pkg/logging" ) const ( @@ -376,7 +376,7 @@ func (f *GithubAssetFetcher) writeCacheManifest(owner, repo string, op func(cach func (f *GithubAssetFetcher) downloadAndSave(assetURI, destPath string) error { f.testObject.Helper() - downloader := blob.NewDownloader(logging.New(&testWriter{t: f.testObject}), f.cacheDir) + downloader := blob.NewDownloader(logging.NewSimpleLogger(&testWriter{t: f.testObject}), f.cacheDir) assetBlob, err := downloader.Download(f.ctx, assetURI) if err != nil { @@ -405,7 +405,7 @@ func (f *GithubAssetFetcher) downloadAndSave(assetURI, destPath string) error { func (f *GithubAssetFetcher) downloadAndExtractTgz(assetURI, destDir string) error { f.testObject.Helper() - downloader := blob.NewDownloader(logging.New(&testWriter{t: f.testObject}), f.cacheDir) + downloader := blob.NewDownloader(logging.NewSimpleLogger(&testWriter{t: f.testObject}), f.cacheDir) assetBlob, err := downloader.Download(f.ctx, assetURI) if err != nil { diff --git a/internal/builder/builder.go b/internal/builder/builder.go index 7ce61cef9c..e32d70f7a1 100644 --- a/internal/builder/builder.go +++ b/internal/builder/builder.go @@ -392,7 +392,7 @@ func addBuildpacks(logger logging.Logger, tmpDir string, image imgutil.Image, ad } // create tar file - bpLayerTar, err := buildpack.BuildpackToLayerTar(bpTmpDir, bp) + bpLayerTar, err := buildpack.ToLayerTar(bpTmpDir, bp) if err != nil { return err } diff --git a/internal/builder/testmocks/mock_lifecycle.go b/internal/builder/testmocks/mock_lifecycle.go index 258909b72e..c0753bd846 100644 --- a/internal/builder/testmocks/mock_lifecycle.go +++ b/internal/builder/testmocks/mock_lifecycle.go @@ -5,10 +5,12 @@ package testmocks import ( - builder "github.com/buildpacks/pack/internal/builder" - gomock "github.com/golang/mock/gomock" io "io" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + builder "github.com/buildpacks/pack/internal/builder" ) // MockLifecycle is a mock of Lifecycle interface diff --git a/internal/commands/testmocks/mock_inspect_image_writer_factory.go b/internal/commands/testmocks/mock_inspect_image_writer_factory.go index 6f887e2e87..2b931aa84c 100644 --- a/internal/commands/testmocks/mock_inspect_image_writer_factory.go +++ b/internal/commands/testmocks/mock_inspect_image_writer_factory.go @@ -5,9 +5,11 @@ package testmocks import ( - writer "github.com/buildpacks/pack/internal/inspectimage/writer" - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + writer "github.com/buildpacks/pack/internal/inspectimage/writer" ) // MockInspectImageWriterFactory is a mock of InspectImageWriterFactory interface diff --git a/internal/commands/testmocks/mock_pack_client.go b/internal/commands/testmocks/mock_pack_client.go index 49bd187940..522616dc8f 100644 --- a/internal/commands/testmocks/mock_pack_client.go +++ b/internal/commands/testmocks/mock_pack_client.go @@ -6,9 +6,11 @@ package testmocks import ( context "context" - client "github.com/buildpacks/pack/pkg/client" - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + client "github.com/buildpacks/pack/pkg/client" ) // MockPackClient is a mock of PackClient interface diff --git a/internal/fakes/fake_package.go b/internal/fakes/fake_package.go index 88ced915d8..0a139098ad 100644 --- a/internal/fakes/fake_package.go +++ b/internal/fakes/fake_package.go @@ -28,7 +28,7 @@ type fakePackage struct { func NewPackage(tmpDir string, name string, buildpacks []buildpack.Buildpack) (Package, error) { processBuildpack := func(bp buildpack.Buildpack) (tarFile string, diffID string, err error) { - tarFile, err = buildpack.BuildpackToLayerTar(tmpDir, bp) + tarFile, err = buildpack.ToLayerTar(tmpDir, bp) if err != nil { return "", "", err } diff --git a/internal/term/term_test.go b/internal/term/term_test.go index e278f1206f..e8e6430adf 100644 --- a/internal/term/term_test.go +++ b/internal/term/term_test.go @@ -12,16 +12,11 @@ import ( h "github.com/buildpacks/pack/testhelpers" ) -const ( - testTime = "2019/05/15 01:01:01.000000" -) - func TestTerm(t *testing.T) { spec.Run(t, "Term", testTerm, spec.Parallel(), spec.Report(report.Terminal{})) } func testTerm(t *testing.T, when spec.G, it spec.S) { - when("#IsTerminal", func() { it("returns false for a pipe", func() { r, _, _ := os.Pipe() diff --git a/pkg/buildpack/builder.go b/pkg/buildpack/builder.go index 0d9fa44a3f..da0f8226c5 100644 --- a/pkg/buildpack/builder.go +++ b/pkg/buildpack/builder.go @@ -92,7 +92,7 @@ func (b *PackageBuilder) finalizeImage(image WorkableImage, tmpDir string) error bpLayers := dist.BuildpackLayers{} for _, bp := range append(b.dependencies, b.buildpack) { - bpLayerTar, err := BuildpackToLayerTar(tmpDir, bp) + bpLayerTar, err := ToLayerTar(tmpDir, bp) if err != nil { return err } diff --git a/pkg/buildpack/buildpack.go b/pkg/buildpack/buildpack.go index eb7ba55eb0..d3713b6cf8 100644 --- a/pkg/buildpack/buildpack.go +++ b/pkg/buildpack/buildpack.go @@ -41,19 +41,19 @@ func (b *buildpack) Descriptor() dist.BuildpackDescriptor { return b.descriptor } -// BuildpackFromBlob constructs a buildpack from a blob. It is assumed that the buildpack +// FromBlob constructs a buildpack from a blob. It is assumed that the buildpack // contents are structured as per the distribution spec (currently '/cnbs/buildpacks/{ID}/{version}/*'). -func BuildpackFromBlob(bpd dist.BuildpackDescriptor, blob Blob) Buildpack { +func FromBlob(bpd dist.BuildpackDescriptor, blob Blob) Buildpack { return &buildpack{ Blob: blob, descriptor: bpd, } } -// BuildpackFromRootBlob constructs a buildpack from a blob. It is assumed that the buildpack contents reside at the +// FromRootBlob constructs a buildpack from a blob. It is assumed that the buildpack contents reside at the // root of the blob. The constructed buildpack contents will be structured as per the distribution spec (currently // a tar with contents under '/cnbs/buildpacks/{ID}/{version}/*'). -func BuildpackFromRootBlob(blob Blob, layerWriterFactory archive.TarWriterFactory) (Buildpack, error) { +func FromRootBlob(blob Blob, layerWriterFactory archive.TarWriterFactory) (Buildpack, error) { bpd := dist.BuildpackDescriptor{} rc, err := blob.Open() if err != nil { @@ -219,7 +219,7 @@ func validateDescriptor(bpd dist.BuildpackDescriptor) error { return nil } -func BuildpackToLayerTar(dest string, bp Buildpack) (string, error) { +func ToLayerTar(dest string, bp Buildpack) (string, error) { bpd := bp.Descriptor() bpReader, err := bp.Open() if err != nil { diff --git a/pkg/buildpack/buildpack_test.go b/pkg/buildpack/buildpack_test.go index fc93376c3b..b2ead856e6 100644 --- a/pkg/buildpack/buildpack_test.go +++ b/pkg/buildpack/buildpack_test.go @@ -50,7 +50,7 @@ func testBuildpack(t *testing.T, when spec.G, it spec.S) { when("#BuildpackFromRootBlob", func() { it("parses the descriptor file", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -80,7 +80,7 @@ id = "some.stack.id" }) it("translates blob to distribution format", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -162,7 +162,7 @@ id = "some.stack.id" }, } - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &errorBlob{ realBlob: realBlob, }, @@ -191,7 +191,7 @@ id = "some.stack.id" when("no exec bits set", func() { it("sets to 0755 if directory", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -216,7 +216,7 @@ id = "some.stack.id" when("no exec bits set", func() { it("sets to 0755 if 'bin/detect' or 'bin/build'", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -247,7 +247,7 @@ id = "some.stack.id" when("not directory, 'bin/detect', or 'bin/build'", func() { it("sets to 0755 if ANY exec bit is set", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -272,7 +272,7 @@ id = "some.stack.id" when("not directory, 'bin/detect', or 'bin/build'", func() { it("sets to 0644 if NO exec bits set", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -298,7 +298,7 @@ id = "some.stack.id" when("there is no descriptor file", func() { it("returns error", func() { - _, err := buildpack.BuildpackFromRootBlob( + _, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -313,7 +313,7 @@ id = "some.stack.id" when("there is no api field", func() { it("assumes an api version", func() { - bp, err := buildpack.BuildpackFromRootBlob( + bp, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -336,7 +336,7 @@ id = "some.stack.id"`)) when("there is no id", func() { it("returns error", func() { - _, err := buildpack.BuildpackFromRootBlob( + _, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -358,7 +358,7 @@ id = "some.stack.id"`)) when("there is no version", func() { it("returns error", func() { - _, err := buildpack.BuildpackFromRootBlob( + _, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -380,7 +380,7 @@ id = "some.stack.id"`)) when("both stacks and order are present", func() { it("returns error", func() { - _, err := buildpack.BuildpackFromRootBlob( + _, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} @@ -408,7 +408,7 @@ id = "some.stack.id" when("missing stacks and order", func() { it("returns error", func() { - _, err := buildpack.BuildpackFromRootBlob( + _, err := buildpack.FromRootBlob( &readerBlob{ openFn: func() io.ReadCloser { tarBuilder := archive.TarBuilder{} diff --git a/pkg/buildpack/downloader.go b/pkg/buildpack/downloader.go index 7cc1c215c0..bb3545f701 100644 --- a/pkg/buildpack/downloader.go +++ b/pkg/buildpack/downloader.go @@ -7,6 +7,7 @@ import ( "github.com/pkg/errors" "github.com/buildpacks/imgutil" + "github.com/buildpacks/pack/internal/layer" "github.com/buildpacks/pack/internal/paths" "github.com/buildpacks/pack/internal/style" @@ -150,7 +151,7 @@ func decomposeBuildpack(blob blob.Blob, imageOS string) (mainBP Buildpack, depBP return mainBP, depBPs, errors.Wrapf(err, "get tar writer factory for OS %s", style.Symbol(imageOS)) } - mainBP, err = BuildpackFromRootBlob(blob, layerWriterFactory) + mainBP, err = FromRootBlob(blob, layerWriterFactory) if err != nil { return mainBP, depBPs, errors.Wrap(err, "reading buildpack") } diff --git a/pkg/buildpack/package.go b/pkg/buildpack/package.go index d580376325..c8ae73fb8c 100644 --- a/pkg/buildpack/package.go +++ b/pkg/buildpack/package.go @@ -68,9 +68,9 @@ func ExtractBuildpacks(pkg Package) (mainBP Buildpack, depBPs []Buildpack, err e } if desc.Info.Match(md.BuildpackInfo) { // This is the order buildpack of the package - mainBP = BuildpackFromBlob(desc, b) + mainBP = FromBlob(desc, b) } else { - depBPs = append(depBPs, BuildpackFromBlob(desc, b)) + depBPs = append(depBPs, FromBlob(desc, b)) } } } diff --git a/pkg/client/client.go b/pkg/client/client.go index 4010e39d65..0dc7b311f5 100644 --- a/pkg/client/client.go +++ b/pkg/client/client.go @@ -22,11 +22,11 @@ import ( "github.com/buildpacks/imgutil" "github.com/buildpacks/imgutil/local" "github.com/buildpacks/imgutil/remote" - "github.com/buildpacks/pack" dockerClient "github.com/docker/docker/client" "github.com/google/go-containerregistry/pkg/authn" "github.com/pkg/errors" + "github.com/buildpacks/pack" "github.com/buildpacks/pack/internal/build" iconfig "github.com/buildpacks/pack/internal/config" "github.com/buildpacks/pack/internal/style" @@ -99,19 +99,19 @@ type Client struct { version string } -// ClientOption is a type of function that mutate settings on the client. +// Option is a type of function that mutate settings on the client. // Values in these functions are set through currying. -type ClientOption func(c *Client) +type Option func(c *Client) // WithLogger supply your own logger. -func WithLogger(l logging.Logger) ClientOption { +func WithLogger(l logging.Logger) Option { return func(c *Client) { c.logger = l } } // WithImageFactory supply your own image factory. -func WithImageFactory(f ImageFactory) ClientOption { +func WithImageFactory(f ImageFactory) Option { return func(c *Client) { c.imageFactory = f } @@ -119,7 +119,7 @@ func WithImageFactory(f ImageFactory) ClientOption { // WithFetcher supply your own Fetcher. // A Fetcher retrieves both local and remote images to make them available. -func WithFetcher(f ImageFetcher) ClientOption { +func WithFetcher(f ImageFetcher) Option { return func(c *Client) { c.imageFetcher = f } @@ -127,7 +127,7 @@ func WithFetcher(f ImageFetcher) ClientOption { // WithDownloader supply your own downloader. // A Downloader is used to gather buildpacks from both remote urls, or local sources. -func WithDownloader(d BlobDownloader) ClientOption { +func WithDownloader(d BlobDownloader) Option { return func(c *Client) { c.downloader = d } @@ -135,7 +135,7 @@ func WithDownloader(d BlobDownloader) ClientOption { // WithBuildpackDownloader supply your own BuildpackDownloader. // A BuildpackDownloader is used to gather buildpacks from both remote urls, or local sources. -func WithBuildpackDownloader(d BuildpackDownloader) ClientOption { +func WithBuildpackDownloader(d BuildpackDownloader) Option { return func(c *Client) { c.buildpackDownloader = d } @@ -144,35 +144,35 @@ func WithBuildpackDownloader(d BuildpackDownloader) ClientOption { // Deprecated: use WithDownloader instead. // // WithCacheDir supply your own cache directory. -func WithCacheDir(path string) ClientOption { +func WithCacheDir(path string) Option { return func(c *Client) { c.downloader = blob.NewDownloader(c.logger, path) } } // WithDockerClient supply your own docker client. -func WithDockerClient(docker dockerClient.CommonAPIClient) ClientOption { +func WithDockerClient(docker dockerClient.CommonAPIClient) Option { return func(c *Client) { c.docker = docker } } // WithExperimental sets whether experimental features should be enabled. -func WithExperimental(experimental bool) ClientOption { +func WithExperimental(experimental bool) Option { return func(c *Client) { c.experimental = experimental } } // WithRegistryMirrors sets mirrors to pull images from. -func WithRegistryMirrors(registryMirrors map[string]string) ClientOption { +func WithRegistryMirrors(registryMirrors map[string]string) Option { return func(c *Client) { c.registryMirrors = registryMirrors } } // WithKeychain sets keychain of credentials to image registries -func WithKeychain(keychain authn.Keychain) ClientOption { +func WithKeychain(keychain authn.Keychain) Option { return func(c *Client) { c.keychain = keychain } @@ -181,7 +181,7 @@ func WithKeychain(keychain authn.Keychain) ClientOption { const DockerAPIVersion = "1.38" // NewClient allocates and returns a Client configured with the specified options. -func NewClient(opts ...ClientOption) (*Client, error) { +func NewClient(opts ...Option) (*Client, error) { client := &Client{ version: pack.Version, keychain: authn.DefaultKeychain, diff --git a/pkg/client/create_builder_test.go b/pkg/client/create_builder_test.go index 399973fb1c..45a16b9437 100644 --- a/pkg/client/create_builder_test.go +++ b/pkg/client/create_builder_test.go @@ -109,7 +109,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { mockDownloader.EXPECT().Download(gomock.Any(), "file:///some-lifecycle").Return(blob.NewBlob(filepath.Join("testdata", "lifecycle", "platform-0.4")), nil).AnyTimes() mockDownloader.EXPECT().Download(gomock.Any(), "file:///some-lifecycle-platform-0-1").Return(blob.NewBlob(filepath.Join("testdata", "lifecycle-platform-0.1")), nil).AnyTimes() - bp, err := buildpack.BuildpackFromRootBlob(exampleBuildpackBlob, archive.DefaultTarWriterFactory()) + bp, err := buildpack.FromRootBlob(exampleBuildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one.tgz", gomock.Any()).Return(bp, nil, nil).AnyTimes() @@ -622,7 +622,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { opts.Config.Buildpacks[0].URI = "https://example.fake/bp-one-with-api-4.tgz" buildpackBlob := blob.NewBlob(filepath.Join("testdata", "buildpack-api-0.4")) - buildpack, err := buildpack.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) + buildpack, err := buildpack.FromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), "https://example.fake/bp-one-with-api-4.tgz", gomock.Any()).Return(buildpack, nil, nil) @@ -641,7 +641,7 @@ func testCreateBuilder(t *testing.T, when spec.G, it spec.S) { opts.Config.Buildpacks[0].URI = directoryPath buildpackBlob := blob.NewBlob(directoryPath) - buildpack, err := buildpack.BuildpackFromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) + buildpack, err := buildpack.FromRootBlob(buildpackBlob, archive.DefaultTarWriterFactory()) h.AssertNil(t, err) mockBuildpackDownloader.EXPECT().Download(gomock.Any(), directoryPath, gomock.Any()).Return(buildpack, nil, nil) diff --git a/pkg/client/example_fetcher_test.go b/pkg/client/example_fetcher_test.go index 26adb6fa5e..6d22d9673d 100644 --- a/pkg/client/example_fetcher_test.go +++ b/pkg/client/example_fetcher_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "github.com/buildpacks/imgutil" + "github.com/buildpacks/pack/pkg/client" "github.com/buildpacks/pack/pkg/image" ) diff --git a/pkg/client/package_buildpack.go b/pkg/client/package_buildpack.go index c3bc8fab83..c17ee00936 100644 --- a/pkg/client/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -84,7 +84,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti return err } - bp, err := buildpack.BuildpackFromRootBlob(mainBlob, writerFactory) + bp, err := buildpack.FromRootBlob(mainBlob, writerFactory) if err != nil { return errors.Wrapf(err, "creating buildpack from %s", style.Symbol(bpURI)) } diff --git a/pkg/testmocks/mock_blob_downloader.go b/pkg/testmocks/mock_blob_downloader.go index 71e148a25d..9596b0f0d8 100644 --- a/pkg/testmocks/mock_blob_downloader.go +++ b/pkg/testmocks/mock_blob_downloader.go @@ -6,9 +6,11 @@ package testmocks import ( context "context" - blob "github.com/buildpacks/pack/pkg/blob" - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + blob "github.com/buildpacks/pack/pkg/blob" ) // MockBlobDownloader is a mock of BlobDownloader interface diff --git a/pkg/testmocks/mock_buildpack.go b/pkg/testmocks/mock_buildpack.go index 8480199e5e..a96441d925 100644 --- a/pkg/testmocks/mock_buildpack.go +++ b/pkg/testmocks/mock_buildpack.go @@ -5,10 +5,12 @@ package testmocks import ( - dist "github.com/buildpacks/pack/pkg/dist" - gomock "github.com/golang/mock/gomock" io "io" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + dist "github.com/buildpacks/pack/pkg/dist" ) // MockBuildpack is a mock of Buildpack interface diff --git a/pkg/testmocks/mock_buildpack_downloader.go b/pkg/testmocks/mock_buildpack_downloader.go index 1e4ddde4f0..9d46b10518 100644 --- a/pkg/testmocks/mock_buildpack_downloader.go +++ b/pkg/testmocks/mock_buildpack_downloader.go @@ -6,9 +6,11 @@ package testmocks import ( context "context" - buildpack "github.com/buildpacks/pack/pkg/buildpack" - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" + + buildpack "github.com/buildpacks/pack/pkg/buildpack" ) // MockBuildpackDownloader is a mock of BuildpackDownloader interface diff --git a/pkg/testmocks/mock_docker_client.go b/pkg/testmocks/mock_docker_client.go index 504c8d8355..72b57b0887 100644 --- a/pkg/testmocks/mock_docker_client.go +++ b/pkg/testmocks/mock_docker_client.go @@ -6,6 +6,12 @@ package testmocks import ( context "context" + io "io" + net "net" + http "net/http" + reflect "reflect" + time "time" + types "github.com/docker/docker/api/types" container "github.com/docker/docker/api/types/container" events "github.com/docker/docker/api/types/events" @@ -17,11 +23,6 @@ import ( volume "github.com/docker/docker/api/types/volume" gomock "github.com/golang/mock/gomock" v1 "github.com/opencontainers/image-spec/specs-go/v1" - io "io" - net "net" - http "net/http" - reflect "reflect" - time "time" ) // MockCommonAPIClient is a mock of CommonAPIClient interface diff --git a/pkg/testmocks/mock_image_factory.go b/pkg/testmocks/mock_image_factory.go index 783831fb00..c8fa2a9ae6 100644 --- a/pkg/testmocks/mock_image_factory.go +++ b/pkg/testmocks/mock_image_factory.go @@ -5,9 +5,10 @@ package testmocks import ( + reflect "reflect" + imgutil "github.com/buildpacks/imgutil" gomock "github.com/golang/mock/gomock" - reflect "reflect" ) // MockImageFactory is a mock of ImageFactory interface diff --git a/pkg/testmocks/mock_image_fetcher.go b/pkg/testmocks/mock_image_fetcher.go index ca4b89d2ad..5d1c3ce338 100644 --- a/pkg/testmocks/mock_image_fetcher.go +++ b/pkg/testmocks/mock_image_fetcher.go @@ -6,10 +6,12 @@ package testmocks import ( context "context" + reflect "reflect" + imgutil "github.com/buildpacks/imgutil" - image "github.com/buildpacks/pack/pkg/image" gomock "github.com/golang/mock/gomock" - reflect "reflect" + + image "github.com/buildpacks/pack/pkg/image" ) // MockImageFetcher is a mock of ImageFetcher interface diff --git a/pkg/testmocks/mock_registry_resolver.go b/pkg/testmocks/mock_registry_resolver.go index 3697c9de0d..5ef77e6a10 100644 --- a/pkg/testmocks/mock_registry_resolver.go +++ b/pkg/testmocks/mock_registry_resolver.go @@ -5,8 +5,9 @@ package testmocks import ( - gomock "github.com/golang/mock/gomock" reflect "reflect" + + gomock "github.com/golang/mock/gomock" ) // MockRegistryResolver is a mock of RegistryResolver interface From fb8830240f63c1589920e9bf94bca01349ec186d Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Mon, 1 Nov 2021 14:52:21 -0500 Subject: [PATCH 09/15] Use ioutil.Discard instead of io.Discard We are still using go1.14, io.Discard is available as of go1.16 Signed-off-by: Javier Romero --- pkg/blob/downloader_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/blob/downloader_test.go b/pkg/blob/downloader_test.go index a2deccfa76..791473312a 100644 --- a/pkg/blob/downloader_test.go +++ b/pkg/blob/downloader_test.go @@ -38,7 +38,7 @@ func testDownloader(t *testing.T, when spec.G, it spec.S) { it.Before(func() { cacheDir, err = ioutil.TempDir("", "cache") h.AssertNil(t, err) - subject = blob.NewDownloader(&logger{io.Discard}, cacheDir) + subject = blob.NewDownloader(&logger{ioutil.Discard}, cacheDir) }) it.After(func() { From 68a93d493ce230283287e28f5934903a2a641525 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Mon, 1 Nov 2021 15:03:28 -0500 Subject: [PATCH 10/15] Skip examples in certain scenarios Signed-off-by: Javier Romero --- pkg/client/example_build_test.go | 8 ++++++++ pkg/client/example_buildpack_downloader_test.go | 8 ++++++++ pkg/client/example_fetcher_test.go | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/pkg/client/example_build_test.go b/pkg/client/example_build_test.go index b10c877a06..30c4b25447 100644 --- a/pkg/client/example_build_test.go +++ b/pkg/client/example_build_test.go @@ -1,8 +1,11 @@ +//+build !windows + package client_test import ( "context" "fmt" + "os" "path/filepath" "github.com/buildpacks/pack/pkg/client" @@ -11,6 +14,11 @@ import ( // This example shows the basic usage of the package: Create a client, // call a configuration object, call the client's Build function. func Example_build() { + // extra: skip when docker is not available + if os.Getenv("NO_DOCKER") == "true" { + return + } + // create a context object context := context.Background() diff --git a/pkg/client/example_buildpack_downloader_test.go b/pkg/client/example_buildpack_downloader_test.go index 155263d362..eb37c901c8 100644 --- a/pkg/client/example_buildpack_downloader_test.go +++ b/pkg/client/example_buildpack_downloader_test.go @@ -1,9 +1,12 @@ +//+build !windows + package client_test import ( "context" "errors" "fmt" + "os" "path/filepath" "github.com/buildpacks/pack/pkg/buildpack" @@ -12,6 +15,11 @@ import ( // This example shows how to replace the buildpack downloader component func Example_buildpack_downloader() { + // extra: skip when docker is not available + if os.Getenv("NO_DOCKER") == "true" { + return + } + // create a context object context := context.Background() diff --git a/pkg/client/example_fetcher_test.go b/pkg/client/example_fetcher_test.go index 6d22d9673d..6854d0f4e1 100644 --- a/pkg/client/example_fetcher_test.go +++ b/pkg/client/example_fetcher_test.go @@ -1,9 +1,12 @@ +//+build !windows + package client_test import ( "context" "errors" "fmt" + "os" "path/filepath" "github.com/buildpacks/imgutil" @@ -14,6 +17,11 @@ import ( // This example shows how to replace the image fetcher component func Example_fetcher() { + // extra: skip when docker is not available + if os.Getenv("NO_DOCKER") == "true" { + return + } + // create a context object context := context.Background() From 4ef6cb4f7e3895164251ccff27a580169fe05cae Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Mon, 1 Nov 2021 22:11:06 -0500 Subject: [PATCH 11/15] Exclude examples when no docker is present via build flags Signed-off-by: Javier Romero --- Makefile | 4 ++++ pkg/client/example_build_test.go | 8 +------- pkg/client/example_buildpack_downloader_test.go | 8 +------- pkg/client/example_fetcher_test.go | 8 +------- pkg/client/inspect_builder_test.go | 2 ++ 5 files changed, 9 insertions(+), 21 deletions(-) diff --git a/Makefile b/Makefile index 9e2f2bef0b..707a27e633 100644 --- a/Makefile +++ b/Makefile @@ -31,6 +31,7 @@ PACK_GITSHA1=$(shell git rev-parse --short=7 HEAD) PACK_VERSION?=0.0.0 TEST_TIMEOUT?=1200s UNIT_TIMEOUT?=$(TEST_TIMEOUT) +NO_DOCKER?= clean_build := $(strip ${PACK_BUILD}) clean_sha := $(strip ${PACK_GITSHA1}) @@ -99,6 +100,9 @@ test: unit acceptance ifeq ($(TEST_COVERAGE), 1) unit: GOTESTFLAGS:=$(GOTESTFLAGS) -coverprofile=./out/tests/coverage-unit.txt -covermode=atomic endif +ifeq ($(NO_DOCKER),) +unit: GOTESTFLAGS:=$(GOTESTFLAGS) --tags=example +endif unit: out @echo "> Running unit/integration tests..." $(GOCMD) test $(GOTESTFLAGS) -timeout=$(UNIT_TIMEOUT) ./... diff --git a/pkg/client/example_build_test.go b/pkg/client/example_build_test.go index 30c4b25447..967a2fca9d 100644 --- a/pkg/client/example_build_test.go +++ b/pkg/client/example_build_test.go @@ -1,11 +1,10 @@ -//+build !windows +//+build !windows, example package client_test import ( "context" "fmt" - "os" "path/filepath" "github.com/buildpacks/pack/pkg/client" @@ -14,11 +13,6 @@ import ( // This example shows the basic usage of the package: Create a client, // call a configuration object, call the client's Build function. func Example_build() { - // extra: skip when docker is not available - if os.Getenv("NO_DOCKER") == "true" { - return - } - // create a context object context := context.Background() diff --git a/pkg/client/example_buildpack_downloader_test.go b/pkg/client/example_buildpack_downloader_test.go index eb37c901c8..c39bb70f10 100644 --- a/pkg/client/example_buildpack_downloader_test.go +++ b/pkg/client/example_buildpack_downloader_test.go @@ -1,4 +1,4 @@ -//+build !windows +//+build !windows, example package client_test @@ -6,7 +6,6 @@ import ( "context" "errors" "fmt" - "os" "path/filepath" "github.com/buildpacks/pack/pkg/buildpack" @@ -15,11 +14,6 @@ import ( // This example shows how to replace the buildpack downloader component func Example_buildpack_downloader() { - // extra: skip when docker is not available - if os.Getenv("NO_DOCKER") == "true" { - return - } - // create a context object context := context.Background() diff --git a/pkg/client/example_fetcher_test.go b/pkg/client/example_fetcher_test.go index 6854d0f4e1..94d154ce75 100644 --- a/pkg/client/example_fetcher_test.go +++ b/pkg/client/example_fetcher_test.go @@ -1,4 +1,4 @@ -//+build !windows +//+build !windows, example package client_test @@ -6,7 +6,6 @@ import ( "context" "errors" "fmt" - "os" "path/filepath" "github.com/buildpacks/imgutil" @@ -17,11 +16,6 @@ import ( // This example shows how to replace the image fetcher component func Example_fetcher() { - // extra: skip when docker is not available - if os.Getenv("NO_DOCKER") == "true" { - return - } - // create a context object context := context.Background() diff --git a/pkg/client/inspect_builder_test.go b/pkg/client/inspect_builder_test.go index abb2629827..e0c96e72d8 100644 --- a/pkg/client/inspect_builder_test.go +++ b/pkg/client/inspect_builder_test.go @@ -1,3 +1,5 @@ +//+build !windows, example + package client import ( From cd3cb10057214161f45d0d1a65e1ec6c784f4aca Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Tue, 2 Nov 2021 09:16:02 -0500 Subject: [PATCH 12/15] Fix: Set propose OS when packaging Signed-off-by: Javier Romero --- pkg/client/package_buildpack.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/client/package_buildpack.go b/pkg/client/package_buildpack.go index c17ee00936..c26d27623c 100644 --- a/pkg/client/package_buildpack.go +++ b/pkg/client/package_buildpack.go @@ -96,7 +96,7 @@ func (c *Client) PackageBuildpack(ctx context.Context, opts PackageBuildpackOpti mainBP, deps, err := c.buildpackDownloader.Download(ctx, dep.URI, buildpack.DownloadOptions{ RegistryName: opts.Registry, RelativeBaseDir: opts.RelativeBaseDir, - ImageOS: "linux", + ImageOS: opts.Config.Platform.OS, ImageName: dep.ImageName, Daemon: !opts.Publish, PullPolicy: opts.PullPolicy, From 3471fc162fee338bfd810eb4e41f38821c8c26c2 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Tue, 2 Nov 2021 11:31:34 -0500 Subject: [PATCH 13/15] Bind test ssh port on non-privileged ports Signed-off-by: Javier Romero --- internal/sshdialer/ssh_dialer_test.go | 515 +++++++++++------- internal/sshdialer/testdata/Dockerfile | 1 - .../sshdialer/testdata/etc/ssh/sshd_config | 1 - 3 files changed, 313 insertions(+), 204 deletions(-) diff --git a/internal/sshdialer/ssh_dialer_test.go b/internal/sshdialer/ssh_dialer_test.go index 3e569953cd..a37d6a7ec4 100644 --- a/internal/sshdialer/ssh_dialer_test.go +++ b/internal/sshdialer/ssh_dialer_test.go @@ -2,7 +2,6 @@ package sshdialer_test import ( "context" - "errors" "fmt" "io/ioutil" "net" @@ -12,42 +11,49 @@ import ( "os/exec" "path/filepath" "runtime" + "strconv" "strings" "sync" "testing" "text/template" "time" - "github.com/buildpacks/pack/internal/sshdialer" - th "github.com/buildpacks/pack/testhelpers" - "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/docker/pkg/homedir" "github.com/docker/go-connections/nat" + "github.com/pkg/errors" "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" + + "github.com/buildpacks/pack/internal/sshdialer" + th "github.com/buildpacks/pack/testhelpers" ) const ( imageName = "buildpacks/sshdialer-test-img" containerName = "sshdialer-test-ctr" + sshPort = "22/tcp" ) -var containerIP4 = "" -var containerIP6 = "" +type ConnectionConfig struct { + containerIPv4 string + containerIPv6 string + port int +} // We need to set up the test container running sshd against which we will run tests. // This will return IPv4 and IPv6 of the container, // cleanUp procedure to remove the test container and possibly error. -func prepareSSHServer(t *testing.T) (cleanUp func(), err error) { - t.Helper() - +func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func(), err error) { th.RequireDocker(t) - containerIP4 = "127.0.0.1" - containerIP6 = "::1" + connConfig = &ConnectionConfig{ + containerIPv4: "127.0.0.1", + containerIPv6: "::1", + port: 0, + } var cleanUps []func() cleanUp = func() { @@ -84,8 +90,7 @@ func prepareSSHServer(t *testing.T) (cleanUp func(), err error) { if runtime.GOOS != "linux" { hostConfig = &container.HostConfig{ PortBindings: map[nat.Port][]nat.PortBinding{ - "22/tcp": {nat.PortBinding{HostIP: "localhost", HostPort: "22"}}, - "2222/tcp": {nat.PortBinding{HostIP: "localhost", HostPort: "2222"}}, + sshPort: {nat.PortBinding{HostIP: "localhost"}}, }, } } @@ -123,27 +128,38 @@ func prepareSSHServer(t *testing.T) (cleanUp func(), err error) { }() var ctrJSON types.ContainerJSON + ctrJSON, err = cli.ContainerInspect(ctx, ctr.ID) + if err != nil { + return + } + if runtime.GOOS == "linux" { - ctrJSON, err = cli.ContainerInspect(ctx, ctr.ID) - if err != nil { - return - } + connConfig.containerIPv4 = ctrJSON.NetworkSettings.IPAddress + connConfig.containerIPv6 = ctrJSON.NetworkSettings.GlobalIPv6Address + } + + sshPortBinds := ctrJSON.NetworkSettings.Ports[sshPort] + if len(sshPortBinds) == 0 { + err = errors.New("SSH port was not bound to host") + return + } - containerIP4 = ctrJSON.NetworkSettings.IPAddress - containerIP6 = ctrJSON.NetworkSettings.GlobalIPv6Address + connConfig.port, err = strconv.Atoi(sshPortBinds[0].HostPort) + if err != nil { + return } // wait for ssh container to start serving ssh - timeoutChan := time.After(time.Second * 10) for { select { - case <-timeoutChan: + case <-time.After(time.Second * 20): err = fmt.Errorf("test container failed to start serving ssh") return - case <-time.After(time.Millisecond * 500): + case <-time.After(time.Second * 2): } - conn, err := net.Dial("tcp", net.JoinHostPort(containerIP4, "2222")) + t.Logf("connecting to ssh: %s:%d", connConfig.containerIPv4, connConfig.port) + conn, err := net.Dial("tcp", net.JoinHostPort(connConfig.containerIPv4, strconv.Itoa(connConfig.port))) if err != nil { continue } @@ -152,7 +168,7 @@ func prepareSSHServer(t *testing.T) (cleanUp func(), err error) { break } - return cleanUp, err + return connConfig, cleanUp, err } // function that prepares testing environment and returns clean up function @@ -188,7 +204,7 @@ func TestCreateDialer(t *testing.T) { defer withoutSSHAgent(t)() defer withCleanHome(t)() - cleanUp, err := prepareSSHServer(t) + connConfig, cleanUp, err := prepareSSHServer(t) if err != nil { t.Fatal(err) } @@ -210,39 +226,49 @@ func TestCreateDialer(t *testing.T) { { name: "read password from input", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{PasswordCallback: func() (string, error) { return "idkfa", nil }}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { - name: "password in url", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + name: "password in url", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { - name: "password in url standard ssh port", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), - }, - { - name: "server key is not in known_hosts (the file doesn't exists)", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, + name: "server key is not in known_hosts (the file doesn't exists)", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, setUpEnv: all(withoutSSHAgent, withCleanHome), CreateError: sshdialer.ErrKeyUnknownMsg, }, { - name: "server key is not in known_hosts (the file exists)", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, + name: "server key is not in known_hosts (the file exists)", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withEmptyKnownHosts), CreateError: sshdialer.ErrKeyUnknownMsg, }, { name: "server key is not in known_hosts (the filed doesn't exists) - user force trust", args: args{ - connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{HostKeyCallback: func(hostPort string, pubKey ssh.PublicKey) error { return nil }}, @@ -252,7 +278,10 @@ func TestCreateDialer(t *testing.T) { { name: "server key is not in known_hosts (the file exists) - user force trust", args: args{ - connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{HostKeyCallback: func(hostPort string, pubKey ssh.PublicKey) error { return nil }}, @@ -260,66 +289,93 @@ func TestCreateDialer(t *testing.T) { setUpEnv: all(withoutSSHAgent, withCleanHome, withEmptyKnownHosts), }, { - name: "server key does not match the respective key in known_host", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withBadKnownHosts), + name: "server key does not match the respective key in known_host", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withBadKnownHosts(connConfig)), CreateError: sshdialer.ErrKeyMismatchMsg, }, { name: "key from identity parameter", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { name: "key at standard location with need to read passphrase", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{PassPhraseCallback: func() (string, error) { return "idfa", nil }}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts(connConfig)), }, { name: "key at standard location with explicitly set passphrase", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{PassPhrase: "idfa"}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts(connConfig)), }, { - name: "key at standard location with no passphrase", - args: args{connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_ed25519"), withKnowHosts), + name: "key at standard location with no passphrase", + args: args{connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_ed25519"), withKnowHosts(connConfig)), }, { - name: "key from ssh-agent", - args: args{connStr: fmt.Sprintf("ssh://testuser@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withGoodSSHAgent, withCleanHome, withKnowHosts), + name: "key from ssh-agent", + args: args{connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withGoodSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { - name: "password in url with IPv6", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]:2222/home/testuser/test.sock", containerIP6)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + name: "password in url with IPv6", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]:%d/home/testuser/test.sock", + connConfig.containerIPv6, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { name: "password in url with IPv6 standard port", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]/home/testuser/test.sock", containerIP6)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]/home/testuser/test.sock", connConfig.containerIPv6)}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { - name: "broken known host", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, + name: "broken known host", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withBrokenKnownHosts), CreateError: "missing host pattern", }, { - name: "inaccessible known host", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, + name: "inaccessible known host", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withInaccessibleKnownHosts), skipOnWin: true, CreateError: "permission denied", @@ -327,126 +383,168 @@ func TestCreateDialer(t *testing.T) { { name: "failing pass phrase cbk", args: args{ - connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{PassPhraseCallback: func() (string, error) { return "", errors.New("test_error_msg") }}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_rsa"), withKnowHosts(connConfig)), CreateError: "test_error_msg", }, { - name: "with broken key at default location", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_dsa"), withKnowHosts), + name: "with broken key at default location", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_dsa"), withKnowHosts(connConfig)), CreateError: "failed to parse private key", }, { name: "with broken key explicit", args: args{ - connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_dsa")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), CreateError: "failed to parse private key", }, { - name: "with inaccessible key", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:2222/home/testuser/test.sock", containerIP4)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withInaccessibleKey("id_rsa"), withKnowHosts), + name: "with inaccessible key", + args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", + connConfig.containerIPv4, + connConfig.port, + )}, + setUpEnv: all(withoutSSHAgent, withCleanHome, withInaccessibleKey("id_rsa"), withKnowHosts(connConfig)), skipOnWin: true, CreateError: "failed to read key file", }, { name: "socket doesn't exist in remote", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/does/not/exist/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{PasswordCallback: func() (string, error) { return "idkfa", nil }}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), DialError: "failed to dial unix socket in the remote", }, { name: "ssh agent non-existent socket", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/does/not/exist/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), }, - setUpEnv: all(withBadSSHAgentSocket, withCleanHome, withKnowHosts), + setUpEnv: all(withBadSSHAgentSocket, withCleanHome, withKnowHosts(connConfig)), CreateError: "failed to connect to ssh-agent's socket", }, { name: "bad ssh agent", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222/does/not/exist/test.sock", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", + connConfig.containerIPv4, + connConfig.port, + ), }, - setUpEnv: all(withBadSSHAgent, withCleanHome, withKnowHosts), + setUpEnv: all(withBadSSHAgent, withCleanHome, withKnowHosts(connConfig)), CreateError: "failed to get signers from ssh-agent", }, { name: "use docker host from remote unix", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, - withRemoteDockerHost("unix:///home/testuser/test.sock")), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), + withRemoteDockerHost("unix:///home/testuser/test.sock", connConfig)), }, { name: "use docker host from remote tcp", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, - withRemoteDockerHost("tcp://localhost:1234")), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), + withRemoteDockerHost("tcp://localhost:1234", connConfig)), }, { name: "use docker host from remote fd", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, - withRemoteDockerHost("fd://localhost:1234")), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), + withRemoteDockerHost("fd://localhost:1234", connConfig)), }, { name: "use docker host from remote npipe", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, - withRemoteDockerHost("npipe:////./pipe/docker_engine")), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), + withRemoteDockerHost("npipe:////./pipe/docker_engine", connConfig)), CreateError: "not supported", }, { name: "use emulated windows with default docker host", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, - withEmulatingWindows), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), + withEmulatingWindows(connConfig)), CreateError: "not supported", }, { name: "use emulated windows with tcp docker host", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, withEmulatingWindows, - withRemoteDockerHost("tcp://localhost:1234")), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), withEmulatingWindows(connConfig), + withRemoteDockerHost("tcp://localhost:1234", connConfig)), }, { name: "use docker system dial-stdio", args: args{ - connStr: fmt.Sprintf("ssh://testuser@%s:2222", containerIP4), + connStr: fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts, withEmulatedDockerSystemDialStdio, withFixedUpSSHCLI), + setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig), withEmulatedDockerSystemDialStdio(connConfig), withFixedUpSSHCLI), }, } @@ -464,7 +562,7 @@ func TestCreateDialer(t *testing.T) { t.Skip("skipping test against standard port (22) on non-linux platform") } - if net.ParseIP(u.Hostname()).To4() == nil && containerIP6 == "" { + if net.ParseIP(u.Hostname()).To4() == nil && connConfig.containerIPv6 == "" { t.Skip("skipping ipv6 test since test environment doesn't support ipv6 connection") } @@ -541,7 +639,7 @@ func cp(src, dest string) error { // puts key from ./testdata/{keyName} to $HOME/.ssh/{keyName} // those keys are authorized by the testing ssh server -func withKey(t *testing.T, keyName string) func(t *testing.T) func() { +func withKey(t *testing.T, keyName string) setUpEnvFn { t.Helper() return func(t *testing.T) func() { @@ -572,7 +670,7 @@ func withKey(t *testing.T, keyName string) func(t *testing.T) func() { } // withInaccessibleKey creates inaccessible key of give type (specified by keyName) -func withInaccessibleKey(keyName string) func(t *testing.T) func() { +func withInaccessibleKey(keyName string) setUpEnvFn { return func(t *testing.T) func() { t.Helper() var err error @@ -625,96 +723,101 @@ func withCleanHome(t *testing.T) func() { } // withKnowHosts creates $HOME/.ssh/known_hosts with correct entries -func withKnowHosts(t *testing.T) func() { - t.Helper() - knownHosts := filepath.Join(homedir.Get(), ".ssh", "known_hosts") +func withKnowHosts(connConfig *ConnectionConfig) setUpEnvFn { + return func(t *testing.T) func() { + t.Helper() - err := os.MkdirAll(filepath.Join(homedir.Get(), ".ssh"), 0700) - if err != nil { - t.Fatal(err) - } + knownHosts := filepath.Join(homedir.Get(), ".ssh", "known_hosts") - _, err = os.Stat(knownHosts) - if err == nil || !errors.Is(err, os.ErrNotExist) { - t.Fatal("known_hosts already exists") - } + err := os.MkdirAll(filepath.Join(homedir.Get(), ".ssh"), 0700) + if err != nil { + t.Fatal(err) + } - f, err := os.OpenFile(knownHosts, os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - t.Fatal(err) - } - defer f.Close() + _, err = os.Stat(knownHosts) + if err == nil || !errors.Is(err, os.ErrNotExist) { + t.Fatal("known_hosts already exists") + } - // generate known_hosts - serverKeysDir := filepath.Join("testdata", "etc", "ssh") - for _, k := range []string{"ecdsa"} { - keyPath := filepath.Join(serverKeysDir, fmt.Sprintf("ssh_host_%s_key.pub", k)) - key, err := ioutil.ReadFile(keyPath) + f, err := os.OpenFile(knownHosts, os.O_CREATE|os.O_WRONLY, 0600) if err != nil { - t.Fatal(t) + t.Fatal(err) } + defer f.Close() - fmt.Fprintf(f, "%s %s", containerIP4, string(key)) - fmt.Fprintf(f, "[%s]:2222 %s", containerIP4, string(key)) + // generate known_hosts + serverKeysDir := filepath.Join("testdata", "etc", "ssh") + for _, k := range []string{"ecdsa"} { + keyPath := filepath.Join(serverKeysDir, fmt.Sprintf("ssh_host_%s_key.pub", k)) + key, err := ioutil.ReadFile(keyPath) + if err != nil { + t.Fatal(t) + } - if containerIP6 != "" { - fmt.Fprintf(f, "%s %s", containerIP6, string(key)) - fmt.Fprintf(f, "[%s]:2222 %s", containerIP6, string(key)) + fmt.Fprintf(f, "%s %s", connConfig.containerIPv4, string(key)) + fmt.Fprintf(f, "[%s]:%d %s", connConfig.containerIPv4, connConfig.port, string(key)) + + if connConfig.containerIPv6 != "" { + fmt.Fprintf(f, "%s %s", connConfig.containerIPv6, string(key)) + fmt.Fprintf(f, "[%s]:%d %s", connConfig.containerIPv6, connConfig.port, string(key)) + } } - } - return func() { - os.Remove(knownHosts) + return func() { + os.Remove(knownHosts) + } } } // withBadKnownHosts creates $HOME/.ssh/known_hosts with incorrect entries -func withBadKnownHosts(t *testing.T) func() { - t.Helper() +func withBadKnownHosts(connConfig *ConnectionConfig) setUpEnvFn { + return func(t *testing.T) func() { + t.Helper() - knownHosts := filepath.Join(homedir.Get(), ".ssh", "known_hosts") + knownHosts := filepath.Join(homedir.Get(), ".ssh", "known_hosts") - err := os.MkdirAll(filepath.Join(homedir.Get(), ".ssh"), 0700) - if err != nil { - t.Fatal(err) - } + err := os.MkdirAll(filepath.Join(homedir.Get(), ".ssh"), 0700) + if err != nil { + t.Fatal(err) + } - _, err = os.Stat(knownHosts) - if err == nil || !errors.Is(err, os.ErrNotExist) { - t.Fatal("known_hosts already exists") - } + _, err = os.Stat(knownHosts) + if err == nil || !errors.Is(err, os.ErrNotExist) { + t.Fatal("known_hosts already exists") + } - f, err := os.OpenFile(knownHosts, os.O_CREATE|os.O_WRONLY, 0600) - if err != nil { - t.Fatal(err) - } - defer f.Close() + f, err := os.OpenFile(knownHosts, os.O_CREATE|os.O_WRONLY, 0600) + if err != nil { + t.Fatal(err) + } + defer f.Close() - knownHostTemplate := `{{range $host := .}}{{$host}} ssh-dss AAAAB3NzaC1kc3MAAACBAKH4ufS3ABVb780oTgEL1eu+pI1p6YOq/1KJn5s3zm+L3cXXq76r5OM/roGEYrXWUDGRtfVpzYTAKoMWuqcVc0AZ2zOdYkoy1fSjJ3MqDGF53QEO3TXIUt3gUzmLOewwmZWle0RgMa9GHccv7XVVIZB36RR68ZEUswLaTnlVhXQ1AAAAFQCl4t/LnY7kuUI+tL2qT2XmxmiyqwAAAIB72XaO+LfyIiqBOaTkQf+5rvH1i6y6LDO1QD9pzGWUYw3y03AEveHJMjW0EjnYBKJjK39wcZNTieRyU54lhH/HWeWABn9NcQ3duEf1WSO/s7SPsFO2R6quqVSsStkqf2Yfdy4fl24mH41olwtNA6ft5nkVfkqrIa51si4jU8fBVAAAAIB8SSvyYBcyMGLUlQjzQqhhhAHer9x/1YbknVz+y5PHJLLjHjMC4ZRfLgNEojvMKQW46Te9Pwnudcwv19ho4F+kkCOfss7xjyH70gQm6Sj76DxClmnnPoSRq3qEAOMy5Oh+7vyzxm68KHqd/aOmUaiT1LgqgViS9+kNdCoVMGAMOg== mvasek@bellatrix + knownHostTemplate := `{{range $host := .}}{{$host}} ssh-dss AAAAB3NzaC1kc3MAAACBAKH4ufS3ABVb780oTgEL1eu+pI1p6YOq/1KJn5s3zm+L3cXXq76r5OM/roGEYrXWUDGRtfVpzYTAKoMWuqcVc0AZ2zOdYkoy1fSjJ3MqDGF53QEO3TXIUt3gUzmLOewwmZWle0RgMa9GHccv7XVVIZB36RR68ZEUswLaTnlVhXQ1AAAAFQCl4t/LnY7kuUI+tL2qT2XmxmiyqwAAAIB72XaO+LfyIiqBOaTkQf+5rvH1i6y6LDO1QD9pzGWUYw3y03AEveHJMjW0EjnYBKJjK39wcZNTieRyU54lhH/HWeWABn9NcQ3duEf1WSO/s7SPsFO2R6quqVSsStkqf2Yfdy4fl24mH41olwtNA6ft5nkVfkqrIa51si4jU8fBVAAAAIB8SSvyYBcyMGLUlQjzQqhhhAHer9x/1YbknVz+y5PHJLLjHjMC4ZRfLgNEojvMKQW46Te9Pwnudcwv19ho4F+kkCOfss7xjyH70gQm6Sj76DxClmnnPoSRq3qEAOMy5Oh+7vyzxm68KHqd/aOmUaiT1LgqgViS9+kNdCoVMGAMOg== mvasek@bellatrix {{$host}} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLTxVVaQ93ReqHNlbjg5/nBRpuRuG6JIgNeJXWT1V4Dl+dMMrnad3uJBfyrNpvn8rv2qnn6gMTZVtTbLdo96pG0= mvasek@bellatrix {{$host}} ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOKymJNQszrxetVffPZRfZGKWK786r0mNcg/Wah4+2wn mvasek@bellatrix {{$host}} ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC/1/OCwec2Gyv5goNYYvos4iOA+a0NolOGsZA/93jmSArPY1zZS1UWeJ6dDTmxGoL/e7jm9lM6NJY7a/zM0C/GqCNRGR/aCUHBJTIgGtH+79FDKO/LWY6ClGY7Lw8qNgZpugbBw3N3HqTtyb2lELhFLT0FEb+le4WUbryooLK2zsz6DnqV4JvTYyyHcanS0h68iSXC7XbkZchvL99l5LT0gD1oDteBPKKFdNOwIjpMkk/IrbFM24xoNkaTDXN87EpQPQzYDfsoGymprc5OZZ8kzrtErQR+yfuunHfzzqDHWi7ga5pbgkuxNt10djWgCfBRsy07FTEgV0JirS0TCfwTBbqRzdjf3dgi8AP+WtkW3mcv4a1XYeqoBo2o9TbfyiA9kERs79UBN0mCe3KNX3Ns0PvutsRLaHmdJ49eaKWkJ6GgL37aqSlIwTixz2xY3eoDSkqHoZpx6Q1MdpSIl5gGVzlaobM/PNM1jqVdyUj+xpjHyiXwHQMKc3eJna7s8Jc= mvasek@bellatrix {{end}}` - tmpl := template.New(knownHostTemplate) - tmpl, err = tmpl.Parse(knownHostTemplate) - if err != nil { - t.Fatal(err) - } + tmpl := template.New(knownHostTemplate) + tmpl, err = tmpl.Parse(knownHostTemplate) + if err != nil { + t.Fatal(err) + } - hosts := make([]string, 0, 4) - hosts = append(hosts, containerIP4, fmt.Sprintf("[%s]:2222", containerIP4)) - if containerIP6 != "" { - hosts = append(hosts, containerIP6, fmt.Sprintf("[%s]:2222", containerIP6)) - } + hosts := make([]string, 0, 4) + hosts = append(hosts, connConfig.containerIPv4, fmt.Sprintf("[%s]:%d", connConfig.containerIPv4, connConfig.port)) + if connConfig.containerIPv6 != "" { + hosts = append(hosts, connConfig.containerIPv6, fmt.Sprintf("[%s]:%d", connConfig.containerIPv6, connConfig.port)) + } - err = tmpl.Execute(f, hosts) - if err != nil { - t.Fatal(err) - } + err = tmpl.Execute(f, hosts) + if err != nil { + t.Fatal(err) + } - return func() { - os.Remove(knownHosts) + return func() { + os.Remove(knownHosts) + } } } @@ -1059,65 +1162,73 @@ SSH_BIN -o PasswordAuthentication=no -o ConnectTimeout=3 -o UserKnownHostsFile=% // withEmulatedDockerSystemDialStdio makes `docker system dial-stdio` viable in the testing ssh server. // It does so by appending definition of shell function named `docker` into .bashrc . -func withEmulatedDockerSystemDialStdio(t *testing.T) func() { - t.Helper() +func withEmulatedDockerSystemDialStdio(connConfig *ConnectionConfig) setUpEnvFn { + return func(t *testing.T) func() { + t.Helper() - _, err := runRemote(`echo 'docker () { - if [ "$1" = "system" ] && [ "$2" = "dial-stdio" ]; then - if [ "$3" = "--help" ]; then - echo "\nProxy the stdio stream to the daemon connection."; - else - socat - /home/testuser/test.sock; - fi - fi -}' >> ~/.bashrc`) - if err != nil { - t.Fatal(err) - } + _, err := runRemote(`echo 'docker () { + if [ "$1" = "system" ] && [ "$2" = "dial-stdio" ]; then + if [ "$3" = "--help" ]; then + echo "\nProxy the stdio stream to the daemon connection."; + else + socat - /home/testuser/test.sock; + fi + fi + }' >> ~/.bashrc`, connConfig) + if err != nil { + t.Fatal(err) + } - return func() { - _, _ = runRemote(`echo 'unset -f docker' >> ~/.bashrc`) + return func() { + _, _ = runRemote(`echo 'unset -f docker' >> ~/.bashrc`, connConfig) + } } } // withEmulatingWindows makes changes to the testing ssh server such that // the server appears to be Windows server for simple check done calling the `systeminfo` command -func withEmulatingWindows(t *testing.T) func() { - t.Helper() +func withEmulatingWindows(connConfig *ConnectionConfig) setUpEnvFn { + return func(t *testing.T) func() { + t.Helper() - _, err := runRemote(`echo 'systeminfo () { - echo '\nWindows\n' -}' >> ~/.bashrc`) - if err != nil { - t.Fatal(err) - } + _, err := runRemote(`echo 'systeminfo () { + echo '\nWindows\n' + }' >> ~/.bashrc`, connConfig) + if err != nil { + t.Fatal(err) + } - return func() { - _, _ = runRemote(`echo 'unset -f systeminfo' >> ~/.bashrc`) + return func() { + _, _ = runRemote(`echo 'unset -f systeminfo' >> ~/.bashrc`, connConfig) + } } } // withRemoteDockerHost sets the DOCKER_HOST environment variable in the testing ssh server. // It does so by appending export statement to .bashrc . -func withRemoteDockerHost(host string) setUpEnvFn { +func withRemoteDockerHost(host string, connConfig *ConnectionConfig) setUpEnvFn { return func(t *testing.T) func() { t.Helper() - _, err := runRemote(fmt.Sprintf(`echo 'export DOCKER_HOST=%s' >> ~/.bashrc`, host)) + _, err := runRemote(fmt.Sprintf(`echo 'export DOCKER_HOST=%s' >> ~/.bashrc`, host), connConfig) if err != nil { t.Fatal(err) } return func() { - runRemote(`echo 'unset DOCKER_HOST' >> ~/.bashrc`) + runRemote(`echo 'unset DOCKER_HOST' >> ~/.bashrc`, connConfig) } } } // runRemote runs command it the testing ssh server -func runRemote(cmd string) ([]byte, error) { - u, err := url.Parse(fmt.Sprintf("ssh://testuser@%s:2222", containerIP4)) +func runRemote(cmd string, connConfig *ConnectionConfig) ([]byte, error) { + u, err := url.Parse(fmt.Sprintf("ssh://testuser@%s:%d", + connConfig.containerIPv4, + connConfig.port, + )) if err != nil { - return nil, err + return nil, errors.Wrap(err, "parsing url") } + sshClientConfig, err := sshdialer.NewSSHClientConfig(u, sshdialer.Config{ HostKeyCallback: func(hostPort string, pubKey ssh.PublicKey) error { return nil @@ -1127,18 +1238,18 @@ func runRemote(cmd string) ([]byte, error) { }, }) if err != nil { - return nil, err + return nil, errors.Wrap(err, "creating ssh config") } sshClient, err := ssh.Dial("tcp", u.Host, sshClientConfig) if err != nil { - return nil, err + return nil, errors.Wrap(err, "connecting") } defer sshClient.Close() session, err := sshClient.NewSession() if err != nil { - return nil, err + return nil, errors.Wrap(err, "starting session") } defer session.Close() diff --git a/internal/sshdialer/testdata/Dockerfile b/internal/sshdialer/testdata/Dockerfile index f125105d29..49dbf96073 100644 --- a/internal/sshdialer/testdata/Dockerfile +++ b/internal/sshdialer/testdata/Dockerfile @@ -27,6 +27,5 @@ RUN cat /tmp/id_ed25519.pub /tmp/id_rsa.pub >> /home/testuser/.ssh/authorized_ke COPY --from=builder /workspace/serve-socket /usr/local/bin EXPOSE 22 -EXPOSE 2222 CMD ["/usr/local/bin/entrypoint.sh"] diff --git a/internal/sshdialer/testdata/etc/ssh/sshd_config b/internal/sshdialer/testdata/etc/ssh/sshd_config index 95740bbc89..d9b6222334 100644 --- a/internal/sshdialer/testdata/etc/ssh/sshd_config +++ b/internal/sshdialer/testdata/etc/ssh/sshd_config @@ -11,7 +11,6 @@ # default value. Port 22 -Port 2222 AddressFamily any ListenAddress 0.0.0.0 ListenAddress :: From b03c31bfedaf481f1315b00f293aad62b6d42a13 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Tue, 2 Nov 2021 13:14:39 -0500 Subject: [PATCH 14/15] Fix sshdialer tests on Linux Signed-off-by: Javier Romero --- internal/sshdialer/ssh_dialer_test.go | 473 +++++++++++++------------- 1 file changed, 239 insertions(+), 234 deletions(-) diff --git a/internal/sshdialer/ssh_dialer_test.go b/internal/sshdialer/ssh_dialer_test.go index a37d6a7ec4..7f85d686ef 100644 --- a/internal/sshdialer/ssh_dialer_test.go +++ b/internal/sshdialer/ssh_dialer_test.go @@ -37,164 +37,6 @@ const ( sshPort = "22/tcp" ) -type ConnectionConfig struct { - containerIPv4 string - containerIPv6 string - port int -} - -// We need to set up the test container running sshd against which we will run tests. -// This will return IPv4 and IPv6 of the container, -// cleanUp procedure to remove the test container and possibly error. -func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func(), err error) { - th.RequireDocker(t) - - connConfig = &ConnectionConfig{ - containerIPv4: "127.0.0.1", - containerIPv6: "::1", - port: 0, - } - - var cleanUps []func() - cleanUp = func() { - for i := range cleanUps { - cleanUps[i]() - } - } - - ctx := context.Background() - - cli, err := client.NewClientWithOpts( - client.FromEnv, - client.WithAPIVersionNegotiation(), - ) - if err != nil { - return - } - - info, err := cli.Info(ctx) - th.SkipIf(t, info.OSType == "windows", "These tests are not yet compatible with Windows-based containers") - - wd, err := os.Getwd() - if err != nil { - return - } - - th.CreateImageFromDir(t, cli, imageName, filepath.Join(wd, "testdata")) - - config := container.Config{ - Image: imageName, - } - - var hostConfig *container.HostConfig - if runtime.GOOS != "linux" { - hostConfig = &container.HostConfig{ - PortBindings: map[nat.Port][]nat.PortBinding{ - sshPort: {nat.PortBinding{HostIP: "localhost"}}, - }, - } - } - - // just in case the container has not been cleaned up - _ = cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true}) - - ctr, err := cli.ContainerCreate(ctx, &config, hostConfig, nil, nil, containerName) - if err != nil { - return - } - - defer func() { - f := func() { cli.ContainerRemove(ctx, ctr.ID, types.ContainerRemoveOptions{Force: true}) } - if err != nil { - f() - } else { - cleanUps = append(cleanUps, f) - } - }() - - ctrStartOpts := types.ContainerStartOptions{} - err = cli.ContainerStart(ctx, ctr.ID, ctrStartOpts) - if err != nil { - return - } - - defer func() { - f := func() { cli.ContainerKill(ctx, ctr.ID, "SIGKILL") } - if err != nil { - f() - } else { - cleanUps = append(cleanUps, f) - } - }() - - var ctrJSON types.ContainerJSON - ctrJSON, err = cli.ContainerInspect(ctx, ctr.ID) - if err != nil { - return - } - - if runtime.GOOS == "linux" { - connConfig.containerIPv4 = ctrJSON.NetworkSettings.IPAddress - connConfig.containerIPv6 = ctrJSON.NetworkSettings.GlobalIPv6Address - } - - sshPortBinds := ctrJSON.NetworkSettings.Ports[sshPort] - if len(sshPortBinds) == 0 { - err = errors.New("SSH port was not bound to host") - return - } - - connConfig.port, err = strconv.Atoi(sshPortBinds[0].HostPort) - if err != nil { - return - } - - // wait for ssh container to start serving ssh - for { - select { - case <-time.After(time.Second * 20): - err = fmt.Errorf("test container failed to start serving ssh") - return - case <-time.After(time.Second * 2): - } - - t.Logf("connecting to ssh: %s:%d", connConfig.containerIPv4, connConfig.port) - conn, err := net.Dial("tcp", net.JoinHostPort(connConfig.containerIPv4, strconv.Itoa(connConfig.port))) - if err != nil { - continue - } - conn.Close() - - break - } - - return connConfig, cleanUp, err -} - -// function that prepares testing environment and returns clean up function -// this should be used in conjunction with defer: `defer fn()()` -// e.g. sets environment variables or starts mock up services -// it returns clean up procedure that restores old values of environment variables -// or shuts down mock up services -type setUpEnvFn func(t *testing.T) func() - -// combines multiple setUp routines into one setUp routine -func all(fns ...setUpEnvFn) setUpEnvFn { - return func(t *testing.T) func() { - t.Helper() - var cleanUps []func() - for _, fn := range fns { - cleanUps = append(cleanUps, fn(t)) - } - - return func() { - for i := len(cleanUps) - 1; i >= 0; i-- { - cleanUps[i]() - } - } - } -} - func TestCreateDialer(t *testing.T) { for _, privateKey := range []string{"id_ed25519", "id_rsa", "id_dsa"} { path := filepath.Join("testdata", privateKey) @@ -227,8 +69,8 @@ func TestCreateDialer(t *testing.T) { name: "read password from input", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{PasswordCallback: func() (string, error) { return "idkfa", nil @@ -239,16 +81,16 @@ func TestCreateDialer(t *testing.T) { { name: "password in url", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { name: "server key is not in known_hosts (the file doesn't exists)", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome), CreateError: sshdialer.ErrKeyUnknownMsg, @@ -256,8 +98,8 @@ func TestCreateDialer(t *testing.T) { { name: "server key is not in known_hosts (the file exists)", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withEmptyKnownHosts), CreateError: sshdialer.ErrKeyUnknownMsg, @@ -266,8 +108,8 @@ func TestCreateDialer(t *testing.T) { name: "server key is not in known_hosts (the filed doesn't exists) - user force trust", args: args{ connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{HostKeyCallback: func(hostPort string, pubKey ssh.PublicKey) error { return nil @@ -279,8 +121,8 @@ func TestCreateDialer(t *testing.T) { name: "server key is not in known_hosts (the file exists) - user force trust", args: args{ connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{HostKeyCallback: func(hostPort string, pubKey ssh.PublicKey) error { return nil @@ -291,8 +133,8 @@ func TestCreateDialer(t *testing.T) { { name: "server key does not match the respective key in known_host", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withBadKnownHosts(connConfig)), CreateError: sshdialer.ErrKeyMismatchMsg, @@ -301,8 +143,8 @@ func TestCreateDialer(t *testing.T) { name: "key from identity parameter", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -312,8 +154,8 @@ func TestCreateDialer(t *testing.T) { name: "key at standard location with need to read passphrase", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{PassPhraseCallback: func() (string, error) { return "idfa", nil @@ -325,8 +167,8 @@ func TestCreateDialer(t *testing.T) { name: "key at standard location with explicitly set passphrase", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{PassPhrase: "idfa"}, }, @@ -335,37 +177,32 @@ func TestCreateDialer(t *testing.T) { { name: "key at standard location with no passphrase", args: args{connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_ed25519"), withKnowHosts(connConfig)), }, { name: "key from ssh-agent", args: args{connStr: fmt.Sprintf("ssh://testuser@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withGoodSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, { name: "password in url with IPv6", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]:%d/home/testuser/test.sock", - connConfig.containerIPv6, - connConfig.port, + connConfig.hostIPv6, + connConfig.portIPv6, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), }, - { - name: "password in url with IPv6 standard port", - args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@[%s]/home/testuser/test.sock", connConfig.containerIPv6)}, - setUpEnv: all(withoutSSHAgent, withCleanHome, withKnowHosts(connConfig)), - }, { name: "broken known host", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withBrokenKnownHosts), CreateError: "missing host pattern", @@ -373,8 +210,8 @@ func TestCreateDialer(t *testing.T) { { name: "inaccessible known host", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withInaccessibleKnownHosts), skipOnWin: true, @@ -384,8 +221,8 @@ func TestCreateDialer(t *testing.T) { name: "failing pass phrase cbk", args: args{ connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{PassPhraseCallback: func() (string, error) { return "", errors.New("test_error_msg") @@ -397,8 +234,8 @@ func TestCreateDialer(t *testing.T) { { name: "with broken key at default location", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withKey(t, "id_dsa"), withKnowHosts(connConfig)), CreateError: "failed to parse private key", @@ -407,8 +244,8 @@ func TestCreateDialer(t *testing.T) { name: "with broken key explicit", args: args{ connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_dsa")}, }, @@ -418,8 +255,8 @@ func TestCreateDialer(t *testing.T) { { name: "with inaccessible key", args: args{connStr: fmt.Sprintf("ssh://testuser:idkfa@%s:%d/home/testuser/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )}, setUpEnv: all(withoutSSHAgent, withCleanHome, withInaccessibleKey("id_rsa"), withKnowHosts(connConfig)), skipOnWin: true, @@ -429,8 +266,8 @@ func TestCreateDialer(t *testing.T) { name: "socket doesn't exist in remote", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{PasswordCallback: func() (string, error) { return "idkfa", nil @@ -443,8 +280,8 @@ func TestCreateDialer(t *testing.T) { name: "ssh agent non-existent socket", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), }, setUpEnv: all(withBadSSHAgentSocket, withCleanHome, withKnowHosts(connConfig)), @@ -454,8 +291,8 @@ func TestCreateDialer(t *testing.T) { name: "bad ssh agent", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d/does/not/exist/test.sock", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), }, setUpEnv: all(withBadSSHAgent, withCleanHome, withKnowHosts(connConfig)), @@ -465,8 +302,8 @@ func TestCreateDialer(t *testing.T) { name: "use docker host from remote unix", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -477,8 +314,8 @@ func TestCreateDialer(t *testing.T) { name: "use docker host from remote tcp", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -489,8 +326,8 @@ func TestCreateDialer(t *testing.T) { name: "use docker host from remote fd", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -501,8 +338,8 @@ func TestCreateDialer(t *testing.T) { name: "use docker host from remote npipe", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -514,8 +351,8 @@ func TestCreateDialer(t *testing.T) { name: "use emulated windows with default docker host", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -527,8 +364,8 @@ func TestCreateDialer(t *testing.T) { name: "use emulated windows with tcp docker host", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -539,8 +376,8 @@ func TestCreateDialer(t *testing.T) { name: "use docker system dial-stdio", args: args{ connStr: fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, ), credentialConfig: sshdialer.Config{Identity: filepath.Join("testdata", "id_ed25519")}, }, @@ -559,11 +396,11 @@ func TestCreateDialer(t *testing.T) { } if (u.Port() == "" || u.Port() == "22") && runtime.GOOS != "linux" { - t.Skip("skipping test against standard port (22) on non-linux platform") + t.Skip("skipping test against standard portIPv4 (22) on non-linux platform") } - if net.ParseIP(u.Hostname()).To4() == nil && connConfig.containerIPv6 == "" { - t.Skip("skipping ipv6 test since test environment doesn't support ipv6 connection") + if net.ParseIP(u.Hostname()).To4() == nil && connConfig.hostIPv6 == "" { + t.Skip("skipping hostIPv6 test since test environment doesn't support hostIPv6 connection") } if tt.skipOnWin && runtime.GOOS == "windows" { @@ -618,6 +455,174 @@ func TestCreateDialer(t *testing.T) { } } +type ConnectionConfig struct { + hostIPv4 string + hostIPv6 string + portIPv4 int + portIPv6 int +} + +// We need to set up the test container running sshd against which we will run tests. +// This will return IPv4 and IPv6 of the container, +// cleanUp procedure to remove the test container and possibly error. +func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func(), err error) { + th.RequireDocker(t) + + connConfig = &ConnectionConfig{ + hostIPv4: "127.0.0.1", + hostIPv6: "::1", + portIPv4: 0, + portIPv6: 0, + } + + var cleanUps []func() + cleanUp = func() { + for i := range cleanUps { + cleanUps[i]() + } + } + + ctx := context.Background() + + cli, err := client.NewClientWithOpts( + client.FromEnv, + client.WithAPIVersionNegotiation(), + ) + if err != nil { + return + } + + info, err := cli.Info(ctx) + th.SkipIf(t, info.OSType == "windows", "These tests are not yet compatible with Windows-based containers") + + wd, err := os.Getwd() + if err != nil { + return + } + + th.CreateImageFromDir(t, cli, imageName, filepath.Join(wd, "testdata")) + + config := container.Config{ + Image: imageName, + } + + hostConfig := &container.HostConfig{ + PortBindings: map[nat.Port][]nat.PortBinding{ + sshPort: {nat.PortBinding{HostIP: connConfig.hostIPv4}, nat.PortBinding{HostIP: connConfig.hostIPv6}}, + }, + } + + // just in case the container has not been cleaned up + _ = cli.ContainerRemove(ctx, containerName, types.ContainerRemoveOptions{Force: true}) + + ctr, err := cli.ContainerCreate(ctx, &config, hostConfig, nil, nil, containerName) + if err != nil { + return + } + + defer func() { + f := func() { cli.ContainerRemove(ctx, ctr.ID, types.ContainerRemoveOptions{Force: true}) } + if err != nil { + f() + } else { + cleanUps = append(cleanUps, f) + } + }() + + ctrStartOpts := types.ContainerStartOptions{} + err = cli.ContainerStart(ctx, ctr.ID, ctrStartOpts) + if err != nil { + return + } + + defer func() { + f := func() { cli.ContainerKill(ctx, ctr.ID, "SIGKILL") } + if err != nil { + f() + } else { + cleanUps = append(cleanUps, f) + } + }() + + var ctrJSON types.ContainerJSON + ctrJSON, err = cli.ContainerInspect(ctx, ctr.ID) + if err != nil { + return + } + + sshPortBinds := ctrJSON.NetworkSettings.Ports[sshPort] + + var found bool + connConfig.portIPv4, found = portForHost(sshPortBinds, connConfig.hostIPv4) + if !found { + err = errors.Errorf("SSH port for %s not found", connConfig.hostIPv4) + return + } + + connConfig.portIPv6, found = portForHost(sshPortBinds, connConfig.hostIPv6) + if !found { + err = errors.Errorf("SSH port for %s not found", connConfig.hostIPv6) + return + } + + // wait for ssh container to start serving ssh + for { + select { + case <-time.After(time.Second * 20): + err = fmt.Errorf("test container failed to start serving ssh") + return + case <-time.After(time.Second * 2): + } + + t.Logf("connecting to ssh: %s:%d", connConfig.hostIPv4, connConfig.portIPv4) + conn, err := net.Dial("tcp", net.JoinHostPort(connConfig.hostIPv4, strconv.Itoa(connConfig.portIPv4))) + if err != nil { + continue + } + conn.Close() + + break + } + + return connConfig, cleanUp, err +} + +func portForHost(bindings []nat.PortBinding, host string) (int, bool) { + for _, pb := range bindings { + if pb.HostIP == host { + if port, err := strconv.Atoi(pb.HostPort); err == nil { + return port, true + } + } + } + + return 0, false +} + +// function that prepares testing environment and returns clean up function +// this should be used in conjunction with defer: `defer fn()()` +// e.g. sets environment variables or starts mock up services +// it returns clean up procedure that restores old values of environment variables +// or shuts down mock up services +type setUpEnvFn func(t *testing.T) func() + +// combines multiple setUp routines into one setUp routine +func all(fns ...setUpEnvFn) setUpEnvFn { + return func(t *testing.T) func() { + t.Helper() + var cleanUps []func() + for _, fn := range fns { + cleanUps = append(cleanUps, fn(t)) + } + + return func() { + for i := len(cleanUps) - 1; i >= 0; i-- { + cleanUps[i]() + } + } + } +} + func cp(src, dest string) error { srcFs, err := os.Stat(src) if err != nil { @@ -754,12 +759,12 @@ func withKnowHosts(connConfig *ConnectionConfig) setUpEnvFn { t.Fatal(t) } - fmt.Fprintf(f, "%s %s", connConfig.containerIPv4, string(key)) - fmt.Fprintf(f, "[%s]:%d %s", connConfig.containerIPv4, connConfig.port, string(key)) + fmt.Fprintf(f, "%s %s", connConfig.hostIPv4, string(key)) + fmt.Fprintf(f, "[%s]:%d %s", connConfig.hostIPv4, connConfig.portIPv4, string(key)) - if connConfig.containerIPv6 != "" { - fmt.Fprintf(f, "%s %s", connConfig.containerIPv6, string(key)) - fmt.Fprintf(f, "[%s]:%d %s", connConfig.containerIPv6, connConfig.port, string(key)) + if connConfig.hostIPv6 != "" { + fmt.Fprintf(f, "%s %s", connConfig.hostIPv6, string(key)) + fmt.Fprintf(f, "[%s]:%d %s", connConfig.hostIPv6, connConfig.portIPv6, string(key)) } } @@ -805,9 +810,9 @@ func withBadKnownHosts(connConfig *ConnectionConfig) setUpEnvFn { } hosts := make([]string, 0, 4) - hosts = append(hosts, connConfig.containerIPv4, fmt.Sprintf("[%s]:%d", connConfig.containerIPv4, connConfig.port)) - if connConfig.containerIPv6 != "" { - hosts = append(hosts, connConfig.containerIPv6, fmt.Sprintf("[%s]:%d", connConfig.containerIPv6, connConfig.port)) + hosts = append(hosts, connConfig.hostIPv4, fmt.Sprintf("[%s]:%d", connConfig.hostIPv4, connConfig.portIPv4)) + if connConfig.hostIPv6 != "" { + hosts = append(hosts, connConfig.hostIPv6, fmt.Sprintf("[%s]:%d", connConfig.hostIPv6, connConfig.portIPv4)) } err = tmpl.Execute(f, hosts) @@ -1222,8 +1227,8 @@ func withRemoteDockerHost(host string, connConfig *ConnectionConfig) setUpEnvFn // runRemote runs command it the testing ssh server func runRemote(cmd string, connConfig *ConnectionConfig) ([]byte, error) { u, err := url.Parse(fmt.Sprintf("ssh://testuser@%s:%d", - connConfig.containerIPv4, - connConfig.port, + connConfig.hostIPv4, + connConfig.portIPv4, )) if err != nil { return nil, errors.Wrap(err, "parsing url") From 7ee83ee776893af8736edb4347b575d54f34f535 Mon Sep 17 00:00:00 2001 From: Javier Romero Date: Tue, 2 Nov 2021 13:46:08 -0500 Subject: [PATCH 15/15] Fix: sshdialer tests on lcow Signed-off-by: Javier Romero --- internal/sshdialer/ssh_dialer_test.go | 45 ++++++++++++++++----------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/internal/sshdialer/ssh_dialer_test.go b/internal/sshdialer/ssh_dialer_test.go index 7f85d686ef..1f07bd9f3d 100644 --- a/internal/sshdialer/ssh_dialer_test.go +++ b/internal/sshdialer/ssh_dialer_test.go @@ -395,12 +395,8 @@ func TestCreateDialer(t *testing.T) { t.Fatal(err) } - if (u.Port() == "" || u.Port() == "22") && runtime.GOOS != "linux" { - t.Skip("skipping test against standard portIPv4 (22) on non-linux platform") - } - if net.ParseIP(u.Hostname()).To4() == nil && connConfig.hostIPv6 == "" { - t.Skip("skipping hostIPv6 test since test environment doesn't support hostIPv6 connection") + t.Skip("skipping ipv6 test since test environment doesn't support ipv6 connection") } if tt.skipOnWin && runtime.GOOS == "windows" { @@ -468,13 +464,6 @@ type ConnectionConfig struct { func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func(), err error) { th.RequireDocker(t) - connConfig = &ConnectionConfig{ - hostIPv4: "127.0.0.1", - hostIPv6: "::1", - portIPv4: 0, - portIPv6: 0, - } - var cleanUps []func() cleanUp = func() { for i := range cleanUps { @@ -506,10 +495,26 @@ func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func( Image: imageName, } + connConfig = &ConnectionConfig{ + hostIPv4: "127.0.0.1", + hostIPv6: "", + portIPv4: 0, + portIPv6: 0, + } + + portBindings := []nat.PortBinding{ + {HostIP: connConfig.hostIPv4}, + } + + // lcow doesn't support ipv6 port bindings + // see https://github.com/docker/for-win/issues/8211 + if !(runtime.GOOS == "windows" && info.OSType == "linux") { + connConfig.hostIPv6 = "::1" + portBindings = append(portBindings, nat.PortBinding{HostIP: connConfig.hostIPv6}) + } + hostConfig := &container.HostConfig{ - PortBindings: map[nat.Port][]nat.PortBinding{ - sshPort: {nat.PortBinding{HostIP: connConfig.hostIPv4}, nat.PortBinding{HostIP: connConfig.hostIPv6}}, - }, + PortBindings: map[nat.Port][]nat.PortBinding{sshPort: portBindings}, } // just in case the container has not been cleaned up @@ -559,10 +564,12 @@ func prepareSSHServer(t *testing.T) (connConfig *ConnectionConfig, cleanUp func( return } - connConfig.portIPv6, found = portForHost(sshPortBinds, connConfig.hostIPv6) - if !found { - err = errors.Errorf("SSH port for %s not found", connConfig.hostIPv6) - return + if connConfig.hostIPv6 != "" { + connConfig.portIPv6, found = portForHost(sshPortBinds, connConfig.hostIPv6) + if !found { + err = errors.Errorf("SSH port for %s not found", connConfig.hostIPv6) + return + } } // wait for ssh container to start serving ssh