Class: Shakapacker::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/shakapacker/runner.rb

Direct Known Subclasses

DevServerRunner, RspackRunner, WebpackRunner

Constant Summary collapse

BASE_COMMANDS =

Common commands that don’t work with –config option

[
  "help",
  "h",
  "--help",
  "-h",
  "version",
  "v",
  "--version",
  "-v",
  "info",
  "i"
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv, build_config = nil, bundler_override = nil) ⇒ Runner

Returns a new instance of Runner.



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/shakapacker/runner.rb', line 215

def initialize(argv, build_config = nil, bundler_override = nil)
  @argv = argv
  @build_config = build_config
  @bundler_override = bundler_override

  @app_path           = File.expand_path(".", Dir.pwd)
  @shakapacker_config = ENV["SHAKAPACKER_CONFIG"] || File.join(@app_path, "config/shakapacker.yml")

  # Create config with bundler override if provided
  config_opts = {
    root_path: Pathname.new(@app_path),
    config_path: Pathname.new(@shakapacker_config),
    env: ENV["RAILS_ENV"] || ENV["NODE_ENV"] || "development"
  }
  config_opts[:bundler_override] = bundler_override if bundler_override

  @config = Configuration.new(**config_opts)

  @webpack_config = find_webpack_config_from_build_or_default

  Shakapacker::Utils::Manager.error_unless_package_manager_is_obvious!
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



13
14
15
# File 'lib/shakapacker/runner.rb', line 13

def config
  @config
end

Class Method Details

.run(argv) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/shakapacker/runner.rb', line 28

def self.run(argv)
  $stdout.sync = true

  # Show Shakapacker help and exit (don't call bundler)
  # Support --help, -h, and --help=verbose formats
  help_verbose = argv.any? { |arg| arg == "--help=verbose" }
  if argv.include?("--help") || argv.include?("-h") || help_verbose
    print_help(verbose: help_verbose)
    exit(0)
  elsif argv.include?("--version") || argv.include?("-v")
    print_version
    exit(0)
  elsif argv.include?("--init")
    init_config_file
    exit(0)
  elsif argv.include?("--list-builds")
    list_builds
    exit(0)
  end

  # Check for --bundler flag
  bundler_override = nil
  bundler_index = argv.index("--bundler")
  if bundler_index
    bundler_value = argv[bundler_index + 1]
    unless bundler_value && %w[webpack rspack].include?(bundler_value)
      $stderr.puts "[Shakapacker] Error: --bundler requires 'webpack' or 'rspack'"
      $stderr.puts "Usage: bin/shakapacker --bundler <webpack|rspack>"
      exit(1)
    end
    bundler_override = bundler_value
  end

  # Check for --build flag
  build_index = argv.index("--build")
  if build_index
    build_name = argv[build_index + 1]

    unless build_name
      $stderr.puts "[Shakapacker] Error: --build requires a build name"
      $stderr.puts "Usage: bin/shakapacker --build <name>"
      exit(1)
    end

    loader = BuildConfigLoader.new

    unless loader.exists?
      $stderr.puts "[Shakapacker] Config file not found: #{loader.config_file_path}"
      $stderr.puts "Run 'bin/shakapacker --init' to create one"
      exit(1)
    end

    begin
      # Pass bundler override to resolve_build_config
      resolve_opts = {}
      resolve_opts[:default_bundler] = bundler_override if bundler_override
      build_config = loader.resolve_build_config(build_name, **resolve_opts)

      # Remove --build and build name from argv
      remaining_argv = argv.dup
      remaining_argv.delete_at(build_index + 1)
      remaining_argv.delete_at(build_index)

      # Remove --bundler and bundler value from argv if present
      if bundler_index
        bundler_idx_in_remaining = remaining_argv.index("--bundler")
        if bundler_idx_in_remaining
          remaining_argv.delete_at(bundler_idx_in_remaining + 1)
          remaining_argv.delete_at(bundler_idx_in_remaining)
        end
      end

      # If this build uses dev server, delegate to DevServerRunner
      if loader.uses_dev_server?(build_config)
        $stdout.puts "[Shakapacker] Build '#{build_name}' requires dev server"
        $stdout.puts "[Shakapacker] Running: bin/shakapacker-dev-server --build #{build_name}"
        $stdout.puts ""
        require_relative "dev_server_runner"
        DevServerRunner.run_with_build_config(remaining_argv, build_config)
        return
      end

      # Otherwise run with this build config
      run_with_build_config(remaining_argv, build_config)
      return
    rescue ArgumentError => e
      $stderr.puts "[Shakapacker] #{e.message}"
      exit(1)
    end
  end

  Shakapacker.ensure_node_env!

  # Remove --bundler flag from argv if present (not using --build)
  remaining_argv = argv.dup
  if bundler_index
    bundler_idx = remaining_argv.index("--bundler")
    if bundler_idx
      remaining_argv.delete_at(bundler_idx + 1)
      remaining_argv.delete_at(bundler_idx)
    end
  end

  # Set SHAKAPACKER_ASSETS_BUNDLER if bundler override is specified
  # This ensures JS/TS config files use the correct bundler
  ENV["SHAKAPACKER_ASSETS_BUNDLER"] = bundler_override if bundler_override

  # Create a single runner instance to avoid loading configuration twice.
  # We extend it with the appropriate build command based on the bundler type.
  runner = new(remaining_argv, nil, bundler_override)

  # Determine which bundler to use (override takes precedence)
  use_rspack = bundler_override ? (bundler_override == "rspack") : runner.config.rspack?

  if use_rspack
    require_relative "rspack_runner"
    # Extend the runner instance with rspack-specific methods
    # This avoids creating a new RspackRunner which would reload the configuration
    runner.extend(Module.new do
      def build_cmd
        package_json.manager.native_exec_command("rspack")
      end

      def assets_bundler_commands
        BASE_COMMANDS + %w[build watch]
      end
    end)
    runner.run
  else
    require_relative "webpack_runner"
    # Extend the runner instance with webpack-specific methods
    # This avoids creating a new WebpackRunner which would reload the configuration
    runner.extend(Module.new do
      def build_cmd
        package_json.manager.native_exec_command("webpack")
      end
    end)
    runner.run
  end
end

.run_with_build_config(argv, build_config) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/shakapacker/runner.rb', line 169

def self.run_with_build_config(argv, build_config)
  $stdout.sync = true
  Shakapacker.ensure_node_env!

  # Apply build config environment variables
  build_config[:environment].each do |key, value|
    ENV[key] = value.to_s
  end

  # Set SHAKAPACKER_ASSETS_BUNDLER so JS/TS config files use the correct bundler
  # This ensures the bundler override (from --bundler or build config) is respected
  ENV["SHAKAPACKER_ASSETS_BUNDLER"] = build_config[:bundler]

  puts "[Shakapacker] Running build: #{build_config[:name]}"
  puts "[Shakapacker] Description: #{build_config[:description]}" if build_config[:description]
  puts "[Shakapacker] Bundler: #{build_config[:bundler]}"
  puts "[Shakapacker] Config file: #{build_config[:config_file]}" if build_config[:config_file]

  # Create runner with modified argv and bundler from build_config
  # The build_config[:bundler] already has any CLI --bundler override applied
  runner = new(argv, build_config, build_config[:bundler])

  # Use bundler from build_config (which includes CLI override)
  if build_config[:bundler] == "rspack"
    require_relative "rspack_runner"
    runner.extend(Module.new do
      def build_cmd
        package_json.manager.native_exec_command("rspack")
      end

      def assets_bundler_commands
        BASE_COMMANDS + %w[build watch]
      end
    end)
    runner.run
  else
    require_relative "webpack_runner"
    runner.extend(Module.new do
      def build_cmd
        package_json.manager.native_exec_command("webpack")
      end
    end)
    runner.run
  end
end

Instance Method Details

#package_jsonObject



238
239
240
# File 'lib/shakapacker/runner.rb', line 238

def package_json
  @package_json ||= PackageJson.read(@app_path)
end

#runObject



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/shakapacker/runner.rb', line 242

def run
  puts "[Shakapacker] Preparing environment for assets bundler execution..."
  env = Shakapacker::Compiler.env
  env["SHAKAPACKER_CONFIG"] = @shakapacker_config
  env["NODE_OPTIONS"] = ENV["NODE_OPTIONS"] || ""

  cmd = build_cmd
  puts "[Shakapacker] Base command: #{cmd.join(" ")}"

  if @argv.delete("--debug-shakapacker")
    puts "[Shakapacker] Debug mode enabled (--debug-shakapacker)"
    env["NODE_OPTIONS"] = "#{env["NODE_OPTIONS"]} --inspect-brk"
  end

  if @argv.delete "--trace-deprecation"
    puts "[Shakapacker] Trace deprecation enabled (--trace-deprecation)"
    env["NODE_OPTIONS"] = "#{env["NODE_OPTIONS"]} --trace-deprecation"
  end

  if @argv.delete "--no-deprecation"
    puts "[Shakapacker] Deprecation warnings disabled (--no-deprecation)"
    env["NODE_OPTIONS"] = "#{env["NODE_OPTIONS"]} --no-deprecation"
  end

  # Commands are not compatible with --config option.
  if (@argv & assets_bundler_commands).empty?
    puts "[Shakapacker] Adding config file: #{@webpack_config}"
    cmd += ["--config", @webpack_config]
  else
    puts "[Shakapacker] Skipping config file (running assets bundler command: #{(@argv & assets_bundler_commands).join(", ")})"
  end

  cmd += @argv
  puts "[Shakapacker] Final command: #{cmd.join(" ")}"
  puts "[Shakapacker] Working directory: #{@app_path}"

  watch_mode = @argv.include?("--watch") || @argv.include?("-w")
  start_time = Time.now unless watch_mode

  Dir.chdir(@app_path) do
    system(env, *cmd)
  end

  if !watch_mode && start_time
    bundler_name = @config.rspack? ? "rspack" : "webpack"
    elapsed_time = Time.now - start_time
    minutes = (elapsed_time / 60).floor
    seconds = (elapsed_time % 60).round(2)
    time_display = minutes > 0 ? "#{minutes}:#{format('%05.2f', seconds)}s" : "#{elapsed_time.round(2)}s"
    puts "[Shakapacker] Completed #{bundler_name} build in #{time_display} (#{elapsed_time.round(2)}s)"
  end
  exit($?.exitstatus || 1) unless $?.success?
end