From 2f889d7f183e08dbb5210feb14bebe3fe5613fdf Mon Sep 17 00:00:00 2001 From: ns Date: Thu, 5 Dec 2024 12:47:39 +0530 Subject: [PATCH] Added plan.sh file (#237) * Added plan.sh file Signed-off-by: nitin sanghi * Change gem file for app bundler on windows and plan.ps1 added Signed-off-by: nitin sanghi * Habitat pkg version sync with version file Signed-off-by: nitin sanghi * Removed duplicate dep and check linux gem are not trying to install on windows Signed-off-by: nitin sanghi * Change in linux plan file and Rakefile to add install task Signed-off-by: nitin sanghi * added hab path aware code changes Signed-off-by: nikhil2611 * fixing the git issue Signed-off-by: nikhil2611 * added the hab env and few command fix for hab path Signed-off-by: nikhil2611 * testing for plan.sh as of now Signed-off-by: nikhil2611 * adding back omnibus methods for testing Signed-off-by: nikhil2611 * initializing pkg_prefix in hab_env Signed-off-by: nikhil2611 * updated the origin variable for chef-cli Signed-off-by: nikhil2611 * Added chef spec gem Signed-off-by: nitin sanghi * testing chefspec changes Signed-off-by: nikhil2611 * Added rspec in bin dir for linking issue Signed-off-by: nitin sanghi * Chefspec dep for rspec fix to 3.12 Signed-off-by: nitin sanghi * Pinning rspec version Signed-off-by: nitin sanghi * Change chef-cli hab pkg origin Signed-off-by: nitin sanghi * Hab channel changed Signed-off-by: nitin sanghi * Chef 17400 pipeline (#241) * Add github action for hab pkg and publish Signed-off-by: nitin sanghi * Added version check on new hab pkg Signed-off-by: nitin sanghi * removed extra keyword for triggering pipeline Signed-off-by: nitin sanghi * pkg iden added using vars Signed-off-by: nitin sanghi * list all pkg to verify pkg installed Signed-off-by: nitin sanghi * Installing hab build using hart file Signed-off-by: nitin sanghi * Installing hab build using hart file Signed-off-by: nitin sanghi * Installing hab build using hart file Signed-off-by: nitin sanghi * pipeline test commit Signed-off-by: nitin sanghi * pipeline test commit Signed-off-by: nitin sanghi * pipeline test commit Signed-off-by: nitin sanghi * pipeline test commit Signed-off-by: nitin sanghi * pipeline test commit Signed-off-by: nitin sanghi * sudo for installing hab pkg Signed-off-by: nitin sanghi * sudo for installing hab pkg Signed-off-by: nitin sanghi * sudo for installing hab pkg Signed-off-by: nitin sanghi * sudo for installing hab pkg Signed-off-by: nitin sanghi * hart file version change Signed-off-by: nitin sanghi * Change pkg_indent Signed-off-by: nitin sanghi * Change pkg_indent Signed-off-by: nitin sanghi * version regex changed Signed-off-by: nitin sanghi * windows pipeline change Signed-off-by: nitin sanghi * windows pipeline change Signed-off-by: nitin sanghi * windows pipeline change Signed-off-by: nitin sanghi * windows pipeline change Signed-off-by: nitin sanghi * Windows chef-cli hab version check Signed-off-by: nitin sanghi * Windows chef-cli hab version check Signed-off-by: nitin sanghi * Windows chef-cli hab version check Signed-off-by: nitin sanghi * Change the message in test phase and throw error Signed-off-by: nitin sanghi * Change the message in test phase and throw error Signed-off-by: nitin sanghi * Hab pipeline using buildkite Signed-off-by: nitin sanghi * hab build yml file added Signed-off-by: nitin sanghi --------- Signed-off-by: nitin sanghi --------- Signed-off-by: nitin sanghi Signed-off-by: nikhil2611 Co-authored-by: nikhil2611 Co-authored-by: Nikhil Gupta <35272911+nikhil2611@users.noreply.github.com> --- .expeditor/build.habitat.yml | 9 ++ .../buildkite/artifact.habitat.test.ps1 | 86 +++++++++++++++++ .expeditor/buildkite/artifact.habitat.test.sh | 71 ++++++++++++++ .expeditor/config.yml | 35 ++++++- .expeditor/habitat-test.pipeline.yml | 35 +++++++ Gemfile | 15 +-- Rakefile | 3 + chef-cli.gemspec | 1 - habitat/plan.ps1 | 92 +++++++++++++++++++ habitat/plan.sh | 76 +++++++++++++++ habitat/tests/test.ps1 | 21 +++++ habitat/tests/test.sh | 26 ++++++ lib/chef-cli/command/env.rb | 14 +-- lib/chef-cli/command/exec.rb | 2 +- lib/chef-cli/helpers.rb | 47 +++++++--- 15 files changed, 502 insertions(+), 31 deletions(-) create mode 100644 .expeditor/build.habitat.yml create mode 100755 .expeditor/buildkite/artifact.habitat.test.ps1 create mode 100755 .expeditor/buildkite/artifact.habitat.test.sh create mode 100644 .expeditor/habitat-test.pipeline.yml create mode 100644 habitat/plan.ps1 create mode 100644 habitat/plan.sh create mode 100644 habitat/tests/test.ps1 create mode 100755 habitat/tests/test.sh diff --git a/.expeditor/build.habitat.yml b/.expeditor/build.habitat.yml new file mode 100644 index 00000000..72ea2567 --- /dev/null +++ b/.expeditor/build.habitat.yml @@ -0,0 +1,9 @@ +--- +origin: chef + +expeditor: + defaults: + buildkite: + retry: + automatic: + limit: 1 diff --git a/.expeditor/buildkite/artifact.habitat.test.ps1 b/.expeditor/buildkite/artifact.habitat.test.ps1 new file mode 100755 index 00000000..adeb59f6 --- /dev/null +++ b/.expeditor/buildkite/artifact.habitat.test.ps1 @@ -0,0 +1,86 @@ +#!/usr/bin/env powershell + +#Requires -Version 5 +# https://stackoverflow.com/questions/9948517 +# TODO: Set-StrictMode -Version Latest +$PSDefaultParameterValues['*:ErrorAction']='Stop' +$ErrorActionPreference = 'Stop' +$env:HAB_BLDR_CHANNEL = "LTS-2024" +$env:HAB_ORIGIN = 'ci' +$env:CHEF_LICENSE = 'accept-no-persist' +$env:HAB_LICENSE = 'accept-no-persist' +$Plan = 'chef-cli' + +Write-Host "--- system details" +$Properties = 'Caption', 'CSName', 'Version', 'BuildType', 'OSArchitecture' +Get-CimInstance Win32_OperatingSystem | Select-Object $Properties | Format-Table -AutoSize + +Write-Host "--- Installing the version of Habitat required" + +function Stop-HabProcess { + $habProcess = Get-Process hab -ErrorAction SilentlyContinue + if ($habProcess) { + Write-Host "Stopping hab process..." + Stop-Process -Name hab -Force + } +} + +# Installing Habitat +function Install-Habitat { + Write-Host "Downloading and installing Habitat..." + Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.ps1')) +} + +try { + hab --version +} +catch { + Set-ExecutionPolicy Bypass -Scope Process -Force + + Stop-HabProcess + + # Remove the existing hab.exe if it exists and if you have permissions + $habPath = "C:\ProgramData\Habitat\hab.exe" + if (Test-Path $habPath) { + Write-Host "Attempting to remove existing hab.exe..." + Remove-Item $habPath -Force -ErrorAction SilentlyContinue + if (Test-Path $habPath) { + Write-Host "Failed to remove hab.exe, re-running script with elevated permissions." + Start-Process powershell -Verb runAs -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" + exit + } + } + + Install-Habitat +} +finally { + Write-Host ":habicat: I think I have the version I need to build." +} + + +Write-Host "--- Generating fake origin key" +hab origin key generate $env:HAB_ORIGIN + +Write-Host "--- Building $Plan" +$project_root = "$(git rev-parse --show-toplevel)" +Set-Location $project_root + +$env:DO_CHECK=$true; hab pkg build . + +. $project_root/results/last_build.ps1 + +Write-Host "--- Installing $pkg_ident/$pkg_artifact" +hab pkg install -b $project_root/results/$pkg_artifact + +Write-Host "+++ Testing $Plan" + +Push-Location $project_root + +try { + Write-Host "Running unit tests..." + /habitat/tests/test.ps1 $pkg_ident +} +finally { + # Ensure we always return to the original directory + Pop-Location +} \ No newline at end of file diff --git a/.expeditor/buildkite/artifact.habitat.test.sh b/.expeditor/buildkite/artifact.habitat.test.sh new file mode 100755 index 00000000..6ded1be3 --- /dev/null +++ b/.expeditor/buildkite/artifact.habitat.test.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash + +set -eo pipefail + +export HAB_ORIGIN='ci' +export PLAN='chef-cli' +export CHEF_LICENSE="accept-no-persist" +export HAB_LICENSE="accept-no-persist" +export HAB_BLDR_CHANNEL="LTS-2024" + +echo "--- checking if git is installed" +if ! command -v git &> /dev/null; then + echo "Git is not installed. Installing Git..." + sudo yum install -y git +else + echo "Git is already installed." + git --version +fi + +echo "--- add an exception for this directory since detected dubious ownership in repository at /workdir" +git config --global --add safe.directory /workdir + +echo "--- git status for this workdir" +git status + +echo "--- ruby version" +ruby -v + +export project_root="$(git rev-parse --show-toplevel)" +echo "The value for project_root is: $project_root" + +export HAB_NONINTERACTIVE=true +export HAB_NOCOLORING=true +export HAB_STUDIO_SECRET_HAB_NONINTERACTIVE=true + +echo "--- system details" +uname -a + +echo "--- Installing Habitat" +id -a +curl https://raw.githubusercontent.com/habitat-sh/habitat/main/components/hab/install.sh | bash + +echo "--- :key: Generating fake origin key" +hab origin key generate "$HAB_ORIGIN" + + +echo "--- Building $PLAN" +cd "$project_root" +DO_CHECK=true hab pkg build . + +echo "--- Sourcing 'results/last_build.sh'" +if [ -f ./results/last_build.env ]; then + cat ./results/last_build.env + . ./results/last_build.env + export pkg_artifact +fi + +echo "+++ Installing ${pkg_ident:?is undefined}" +echo "++++" +echo $project_root +echo "+++" +hab pkg install -b "${project_root:?is undefined}/results/${pkg_artifact:?is undefined}" + +echo "+++ Testing $PLAN" + +PATH="$(hab pkg path ci/chef-cli)/bin:$PATH" +export PATH +echo "PATH is $PATH" + +echo "--- :mag_right: Testing $PLAN" +${project_root}/habitat/tests/test.sh "$pkg_ident" || error 'failures during test of executables' \ No newline at end of file diff --git a/.expeditor/config.yml b/.expeditor/config.yml index b51f2c1b..29da699e 100644 --- a/.expeditor/config.yml +++ b/.expeditor/config.yml @@ -9,6 +9,9 @@ slack: rubygems: - chef-cli +release_branches: + - workstation-LTS: + version_constraint: 5.* github: # This deletes the GitHub PR branch after successfully merged into the release branch delete_branch_on_merge: true @@ -28,6 +31,19 @@ pipelines: - verify: description: Pull Request validation tests public: true + - habitat/build: + env: + - HAB_NONINTERACTIVE: "true" + - HAB_NOCOLORING: "true" + - HAB_STUDIO_SECRET_HAB_NONINTERACTIVE: "true" + - habitat/test: + description: Execute tests against the habitat artifact + definition: .expeditor/habitat-test.pipeline.yml + env: + - HAB_NONINTERACTIVE: "true" + - HAB_NOCOLORING: "true" + - HAB_STUDIO_SECRET_HAB_NONINTERACTIVE: "true" + trigger: pull_request subscriptions: # These actions are taken, in order they are specified, anytime a Pull Request is merged. @@ -45,7 +61,24 @@ subscriptions: - "Expeditor: Skip All" - built_in:build_gem: only_if: built_in:bump_version + - trigger_pipeline:habitat/test: + only_if: built_in:bump_version + ignore_labels: + - "Expeditor: Skip Habitat" + - "Expeditor: Skip All" + - trigger_pipeline:habitat/build: + only_if: built_in:bump_version + ignore_labels: + - "Expeditor: Skip Habitat" + - "Expeditor: Skip All" + - workload: project_promoted:{{agent_id}}:* actions: - built_in:rollover_changelog - - built_in:publish_rubygems \ No newline at end of file + - built_in:publish_rubygems + # the habitat chain + - workload: buildkite_hab_build_group_published:{{agent_id}}:* + actions: + # when all of the hab package publish to the unstable channel, test and promote them + - trigger_pipeline:habitat/test + \ No newline at end of file diff --git a/.expeditor/habitat-test.pipeline.yml b/.expeditor/habitat-test.pipeline.yml new file mode 100644 index 00000000..98d8b936 --- /dev/null +++ b/.expeditor/habitat-test.pipeline.yml @@ -0,0 +1,35 @@ +--- +expeditor: + defaults: + buildkite: + timeout_in_minutes: 30 + retry: + automatic: + limit: 1 + +steps: + + - label: ":linux: Validate Habitat Builds of Chef-cli" + commands: + - habitat/tests/test.sh + expeditor: + executor: + docker: + image: ruby:3.1 + privileged: true + + - label: ":windows: Validate Habitat Builds of Test Kitchen" + commands: + - .expeditor/buildkite/artifact.habitat.test.ps1 + expeditor: + executor: + docker: + host_os: windows + shell: ["powershell", "-Command"] + image: rubydistros/windows-2019:3.1 + user: 'NT AUTHORITY\SYSTEM' + environment: + - FORCE_FFI_YAJL=ext + - EXPIRE_CACHE=true + - CHEF_LICENSE=accept-no-persist + - CHEF_LICENSE_SERVER=http://hosted-license-service-lb-8000-606952349.us-west-2.elb.amazonaws.com:8000/ diff --git a/Gemfile b/Gemfile index 7461ea33..90f9a343 100644 --- a/Gemfile +++ b/Gemfile @@ -3,10 +3,10 @@ source "https://rubygems.org" gemspec gem "logger", "< 1.6" # 1.6 causes errors with mixlib-log < 3.1.1 - +gem "chefspec" group :test do gem "rake" - gem "rspec", "~> 3.8" + gem "rspec", "=3.12.0" gem "rspec-expectations", "~> 3.8" gem "rspec-mocks", "~> 3.8" gem "cookstyle" @@ -19,10 +19,13 @@ group :development do gem "pry" gem "pry-byebug" gem "rb-readline" + gem "appbundler" end group :profile do - gem "stackprof" - gem "stackprof-webnav" - gem "memory_profiler" -end + unless RUBY_PLATFORM.match?(/mswin|mingw|windows/) + gem "stackprof" + gem "stackprof-webnav" + gem "memory_profiler" + end +end \ No newline at end of file diff --git a/Rakefile b/Rakefile index 3b92ac1a..f25cfd7f 100644 --- a/Rakefile +++ b/Rakefile @@ -14,6 +14,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# +require "bundler/gem_tasks" namespace :style do begin @@ -52,3 +54,4 @@ namespace :style do puts ">>> Gem load error: #{e}, omitting #{task.name}" unless ENV["CI"] end end + diff --git a/chef-cli.gemspec b/chef-cli.gemspec index 35a36fe6..968898d2 100644 --- a/chef-cli.gemspec +++ b/chef-cli.gemspec @@ -50,5 +50,4 @@ Gem::Specification.new do |gem| gem.add_dependency "diff-lcs", ">= 1.0", "< 1.4" # 1.4 changes the output gem.add_dependency "pastel", "~> 0.7" # used for policyfile differ gem.add_dependency "license-acceptance", ">= 1.0.11", "< 3" - gem.add_dependency "chef-licensing", "~> 1.0" end diff --git a/habitat/plan.ps1 b/habitat/plan.ps1 new file mode 100644 index 00000000..ae1e9488 --- /dev/null +++ b/habitat/plan.ps1 @@ -0,0 +1,92 @@ +$ErrorActionPreference = "Stop" +$PSDefaultParameterValues['*:ErrorAction']='Stop' + +$pkg_name="chef-cli" +$pkg_origin="chef" +$pkg_version=$(Get-Content "$PLAN_CONTEXT/../VERSION") +$pkg_maintainer="The Chef Maintainers " + +$pkg_deps=@( + "chef/ruby31-plus-devkit" + "core/git" +) +$pkg_bin_dirs=@("bin" + "vendor/bin") +$project_root= (Resolve-Path "$PLAN_CONTEXT/../").Path + +function pkg_version { + Get-Content "$SRC_PATH/VERSION" +} + +function Invoke-Before { + Set-PkgVersion +} +function Invoke-SetupEnvironment { + Push-RuntimeEnv -IsPath GEM_PATH "$pkg_prefix/vendor" + + Set-RuntimeEnv APPBUNDLER_ALLOW_RVM "true" # prevent appbundler from clearing out the carefully constructed runtime GEM_PATH + Set-RuntimeEnv FORCE_FFI_YAJL "ext" + Set-RuntimeEnv LANG "en_US.UTF-8" + Set-RuntimeEnv LC_CTYPE "en_US.UTF-8" +} + +function Invoke-Build { + try { + $env:Path += ";c:\\Program Files\\Git\\bin" + Push-Location $project_root + $env:GEM_HOME = "$HAB_CACHE_SRC_PATH/$pkg_dirname/vendor" + + Write-BuildLine " ** Configuring bundler for this build environment" + bundle config --local without integration deploy maintenance + bundle config --local jobs 4 + bundle config --local retry 5 + bundle config --local silence_root_warning 1 + Write-BuildLine " ** Using bundler to retrieve the Ruby dependencies" + bundle install + + gem build chef-cli.gemspec + Write-BuildLine " ** Using gem to install" + gem install chef-cli-*.gem --no-document + + + If ($lastexitcode -ne 0) { Exit $lastexitcode } + } finally { + Pop-Location + } +} + +function Invoke-Install { + Write-BuildLine "** Copy built & cached gems to install directory" + Copy-Item -Path "$HAB_CACHE_SRC_PATH/$pkg_dirname/*" -Destination $pkg_prefix -Recurse -Force -Exclude @("gem_make.out", "mkmf.log", "Makefile", + "*/latest", "latest", + "*/JSON-Schema-Test-Suite", "JSON-Schema-Test-Suite") + + try { + Push-Location $pkg_prefix + bundle config --local gemfile $project_root/Gemfile + Write-BuildLine "** generating binstubs for chef-cli with precise version pins" + Write-BuildLine "** generating binstubs for chef-cli with precise version pins $project_root $pkg_prefix/bin " + Invoke-Expression -Command "appbundler.bat $project_root $pkg_prefix/bin chef-cli" + If ($lastexitcode -ne 0) { Exit $lastexitcode } + Write-BuildLine " ** Running the chef-cli project's 'rake install' to install the path-based gems so they look like any other installed gem." + + If ($lastexitcode -ne 0) { Exit $lastexitcode } + } finally { + Pop-Location + } +} + +function Invoke-After { + # We don't need the cache of downloaded .gem files ... + Remove-Item $pkg_prefix/vendor/cache -Recurse -Force + # We don't need the gem docs. + Remove-Item $pkg_prefix/vendor/doc -Recurse -Force + # We don't need to ship the test suites for every gem dependency, + # only inspec's for package verification. + Get-ChildItem $pkg_prefix/vendor/gems -Filter "spec" -Directory -Recurse -Depth 1 ` + | Where-Object -FilterScript { $_.FullName -notlike "*chef-cli*" } ` + | Remove-Item -Recurse -Force + # Remove the byproducts of compiling gems with extensions + Get-ChildItem $pkg_prefix/vendor/gems -Include @("gem_make.out", "mkmf.log", "Makefile") -File -Recurse ` + | Remove-Item -Force +} \ No newline at end of file diff --git a/habitat/plan.sh b/habitat/plan.sh new file mode 100644 index 00000000..5b4953de --- /dev/null +++ b/habitat/plan.sh @@ -0,0 +1,76 @@ +export HAB_BLDR_CHANNEL="LTS-2024" +pkg_name=chef-cli +pkg_origin=chef +ruby_pkg="core/ruby3_1" +pkg_deps=(${ruby_pkg} core/coreutils) +pkg_build_deps=( + core/make + core/sed + core/gcc + core/libarchive + ) +pkg_bin_dirs=(bin) +do_setup_environment() { + build_line 'Setting GEM_HOME="$pkg_prefix/vendor"' + export GEM_HOME="$pkg_prefix/vendor" + + build_line "Setting GEM_PATH=$GEM_HOME" + export GEM_PATH="$GEM_HOME" +} + +pkg_version() { + cat "$SRC_PATH/VERSION" +} +do_before() { + update_pkg_version +} +do_unpack() { + mkdir -pv "$HAB_CACHE_SRC_PATH/$pkg_dirname" + cp -RT "$PLAN_CONTEXT"/.. "$HAB_CACHE_SRC_PATH/$pkg_dirname/" +} +do_build() { + + export GEM_HOME="$pkg_prefix/vendor" + + build_line "Setting GEM_PATH=$GEM_HOME" + export GEM_PATH="$GEM_HOME" + bundle config --local without integration deploy maintenance + bundle config --local jobs 4 + bundle config --local retry 5 + bundle config --local silence_root_warning 1 + bundle install + gem build chef-cli.gemspec +} +do_install() { + export GEM_HOME="$pkg_prefix/vendor" + + build_line "Setting GEM_PATH=$GEM_HOME" + export GEM_PATH="$GEM_HOME" + gem install chef-cli-*.gem --no-document + set_runtime_env "GEM_PATH" "${pkg_prefix}/vendor" + wrap_ruby_bin +} +wrap_ruby_bin() { + local bin="$pkg_prefix/bin/$pkg_name" + local real_bin="$GEM_HOME/gems/chef-cli-${pkg_version}/bin/chef-cli" + build_line "Adding wrapper $bin to $real_bin" + cat < "$bin" +#!$(pkg_path_for core/bash)/bin/bash +set -e + +# Set binary path that allows InSpec to use non-Hab pkg binaries +export PATH="/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:\$PATH" + +# Set Ruby paths defined from 'do_setup_environment()' + export GEM_HOME="$pkg_prefix/vendor" + export GEM_PATH="$GEM_PATH" + +exec $(pkg_path_for ${ruby_pkg})/bin/ruby $real_bin \$@ +EOF + chmod -v 755 "$bin" +} + + +do_strip() { + return 0 +} \ No newline at end of file diff --git a/habitat/tests/test.ps1 b/habitat/tests/test.ps1 new file mode 100644 index 00000000..a712fea5 --- /dev/null +++ b/habitat/tests/test.ps1 @@ -0,0 +1,21 @@ +param ( + [Parameter()] + [string]$PackageIdentifier = $(throw "Usage: test.ps1 [test_pkg_ident] e.g. test.ps1 ci/user-windows/1.0.0/20190812103929") +) + + +Write-Host "--- :fire: Smokish test" +# Pester the Package +$version=hab pkg exec "${pkg_ident}" chef-cli -v +$actual_version=[Regex]::Match($version,"([0-9]+.[0-9]+.[0-9]+)").Value +$package_version=$PackageIdentifier.split("/",4)[2] + +Write-Host "package_version $package_version actual version $actual_version" +if ($package_version -eq $actual_version) +{ + Write "Chef-cli working fine" +} +else { + Write-Error "chef-cli version not met expected $package_version actual version $actual_version " + throw "Chef cli windows pipeline not working for hab pkg" +} \ No newline at end of file diff --git a/habitat/tests/test.sh b/habitat/tests/test.sh new file mode 100755 index 00000000..72e288a4 --- /dev/null +++ b/habitat/tests/test.sh @@ -0,0 +1,26 @@ + +set -euo pipefail + + +project_root="$(git rev-parse --show-toplevel)" +pkg_ident="$1" +# print error message followed by usage and exit +error () { + local message="$1" + + echo -e "\nERROR: ${message}\n" >&2 + + exit 1 +} + +[[ -n "$pkg_ident" ]] || error 'no hab package identity provided' + +package_version=$(awk -F / '{print $3}' <<<"$pkg_ident") + +cd "${project_root}" + +echo "--- :mag_right: Testing ${pkg_ident} executables" +actual_version=$(hab pkg exec "${pkg_ident}" chef-cli -v | sed -E 's/.*version: ([0-9]+\.[0-9]+\.[0-9]+).*/\1/') +[[ "$package_version" = "$actual_version" ]] || error "chef-cli version is not the expected version. Expected '$package_version', got '$actual_version'" + + diff --git a/lib/chef-cli/command/env.rb b/lib/chef-cli/command/env.rb index d1aed4b2..c44e4c4e 100644 --- a/lib/chef-cli/command/env.rb +++ b/lib/chef-cli/command/env.rb @@ -73,19 +73,19 @@ def ruby_info def gem_environment h = {} - h["GEM ROOT"] = omnibus_env["GEM_ROOT"] - h["GEM HOME"] = omnibus_env["GEM_HOME"] - h["GEM PATHS"] = omnibus_env["GEM_PATH"].split(File::PATH_SEPARATOR) - rescue OmnibusInstallNotFound + # h["GEM ROOT"] = omnibus_env["GEM_ROOT"] + # h["GEM HOME"] = omnibus_env["GEM_HOME"] + # h["GEM PATHS"] = omnibus_env["GEM_PATH"].split(File::PATH_SEPARATOR) + # rescue OmnibusInstallNotFound h["GEM_ROOT"] = ENV["GEM_ROOT"] if ENV.key?("GEM_ROOT") h["GEM_HOME"] = ENV["GEM_HOME"] if ENV.key?("GEM_HOME") h["GEM PATHS"] = ENV["GEM_PATH"].split(File::PATH_SEPARATOR) if ENV.key?("GEM_PATH") && !ENV.key?("GEM_PATH").nil? - ensure - h + # ensure + # h end def paths - omnibus_env["PATH"].split(File::PATH_SEPARATOR) + habitat_env["PATH"].split(File::PATH_SEPARATOR) rescue OmnibusInstallNotFound ENV["PATH"].split(File::PATH_SEPARATOR) end diff --git a/lib/chef-cli/command/exec.rb b/lib/chef-cli/command/exec.rb index f1e19bde..9b86bbea 100644 --- a/lib/chef-cli/command/exec.rb +++ b/lib/chef-cli/command/exec.rb @@ -30,7 +30,7 @@ class Exec < ChefCLI::Command::Base def run(params) # Set ENV directly on the "parent" process (us) before running #exec to # ensure the custom PATH is honored when finding the command to exec - omnibus_env.each { |var, value| ENV[var] = value } + habitat_env.each { |var, value| ENV[var] = value } exec(*params) raise "Exec failed without an exception, your ruby is buggy" # should never get here end diff --git a/lib/chef-cli/helpers.rb b/lib/chef-cli/helpers.rb index 6c72237e..e658bf54 100644 --- a/lib/chef-cli/helpers.rb +++ b/lib/chef-cli/helpers.rb @@ -111,22 +111,39 @@ def git_windows_bin_dir end # - # environment vars for omnibus + # environment vars for habitat # - def omnibus_env - @omnibus_env ||= - begin - user_bin_dir = File.expand_path(File.join(Gem.user_dir, "bin")) - path = [ omnibus_bin_dir, user_bin_dir, omnibus_embedded_bin_dir, ENV["PATH"].split(File::PATH_SEPARATOR) ] - path << git_bin_dir if Dir.exist?(git_bin_dir) - path << git_windows_bin_dir if Dir.exist?(git_windows_bin_dir) - { - "PATH" => path.flatten.uniq.join(File::PATH_SEPARATOR), - "GEM_ROOT" => Gem.default_dir, - "GEM_HOME" => Gem.user_dir, - "GEM_PATH" => Gem.path.join(File::PATH_SEPARATOR), - } - end + def habitat_env + @habitat_env ||= + begin + # Define the necessary paths for the Habitat environment + # Custom GEM_HOME within Habitat + pkg_prefix = get_pkg_prefix + vendor_dir = File.join(pkg_prefix, "vendor") + path = [ + File.join(pkg_prefix, "bin"), + ENV["PATH"].split(File::PATH_SEPARATOR) # Preserve existing PATH + ].flatten.uniq + + { + "PATH" => path.join(File::PATH_SEPARATOR), + "GEM_ROOT" => Gem.default_dir, # Default directory for gems + "GEM_HOME" => vendor_dir, # GEM_HOME pointing to the vendor directory + "GEM_PATH" => vendor_dir, # GEM_PATH also pointing to the vendor directory + } + end + end + + def get_pkg_prefix + pkg_origin = "chef" + pkg_name = "#{pkg_origin}/chef-cli" # Your origin and package name + path = `hab pkg path #{pkg_name}`.strip + + if $?.success? && !path.empty? + path + else + raise "Failed to get pkg_prefix for #{pkg_name}: #{path}" + end end def omnibus_expand_path(*paths)