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

.execute_bundler_command(*bundler_args) {|stdout| ... } ⇒ Object

Shared helper to execute bundler commands with output suppression Returns [bundler_type, processed_output] or [nil, nil] on error

Parameters:

  • bundler_args (String, Array<String>)

    Arguments to pass to bundler command

Yields:

  • (stdout)

    Block to process the command output

Yield Parameters:

  • stdout (String)

    The raw stdout from the bundler command

Yield Returns:

  • (Object)

    The processed output to return



535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/shakapacker/runner.rb', line 535

def self.execute_bundler_command(*bundler_args)
  # Check if we're in a Rails project with necessary files
  app_path = File.expand_path(".", Dir.pwd)
  config_path = ENV["SHAKAPACKER_CONFIG"] || File.join(app_path, "config/shakapacker.yml")
  return [nil, nil] unless File.exist?(config_path)

  original_stdout = $stdout
  original_stderr = $stderr

  begin
    # Suppress any output during config loading
    $stdout = StringIO.new
    $stderr = StringIO.new

    # Try to detect bundler type
    runner = new([])
    return [nil, nil] unless runner.config

    bundler_type = runner.config.rspack? ? :rspack : :webpack
    bundler_name = bundler_type == :rspack ? "rspack" : "webpack"
    cmd = runner.package_json.manager.native_exec_command(bundler_name, bundler_args.flatten)

    # Restore output before running command
    $stdout = original_stdout
    $stderr = original_stderr

    # Capture command output
    require "open3"
    stdout, _stderr, status = Open3.capture3(*cmd)
    return [nil, nil] unless status.success?

    # Process output using the provided block
    processed_output = yield(stdout)
    [bundler_type, processed_output]
  rescue StandardError => e
    [nil, nil]
  ensure
    # Always restore output streams
    $stdout = original_stdout
    $stderr = original_stderr
  end
end

.filter_managed_options(help_text) ⇒ Object

Filter bundler help output to remove Shakapacker-managed options

This method processes the raw help output from webpack/rspack and removes:

  1. Command sections (e.g., “Commands: webpack build”)

  2. Options that Shakapacker manages automatically (–config, –nodeEnv, etc.)

  3. Help/version flags (shown separately in Shakapacker’s help)

The filtering uses stateful line-by-line processing:

  • in_commands_section: tracks when we’re inside a Commands: block

  • skip_until_blank: tracks multi-line option descriptions to skip entirely

Note: This relies on bundler help format conventions. If webpack/rspack significantly changes their help output format, this may need adjustment.



414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/shakapacker/runner.rb', line 414

def self.filter_managed_options(help_text)
  lines = help_text.lines
  filtered_lines = []
  skip_until_blank = false
  in_commands_section = false

  lines.each do |line|
    # Skip the [options] line and Commands section headers
    # These appear in formats like "[options]" or "Commands:"
    if line.match?(/^\[options\]/) || line.match?(/^Commands:/)
      in_commands_section = true
      next
    end

    # Continue skipping until we exit the commands section
    # Exit when we hit "Options:" header or double blank lines
    if in_commands_section
      if line.match?(/^Options:/) || (line.strip.empty? && filtered_lines.last&.strip&.empty?)
        in_commands_section = false
      else
        next
      end
    end

    # Skip options that Shakapacker manages and their descriptions
    # These options are shown in the "Options managed by Shakapacker" section
    if line.match?(/^\s*(-c,\s*)?--config\b/) ||
       line.match?(/^\s*--configName\b/) ||
       line.match?(/^\s*--configLoader\b/) ||
       line.match?(/^\s*--nodeEnv\b/) ||
       line.match?(/^\s*(-h,\s*)?--help\b/) ||
       line.match?(/^\s*(-v,\s*)?--version\b/)
      skip_until_blank = true
      next
    end

    # Continue skipping lines that are part of a filtered option's description
    # Reset when we hit a blank line or the start of a new option (starts with -)
    if skip_until_blank
      if line.strip.empty? || line.match?(/^\s*-/)
        skip_until_blank = false
      else
        next
      end
    end

    filtered_lines << line
  end

  filtered_lines.join
end

.get_bundler_help(help_flag = "--help") ⇒ Object



397
398
399
# File 'lib/shakapacker/runner.rb', line 397

def self.get_bundler_help(help_flag = "--help")
  execute_bundler_command(help_flag) { |stdout| stdout }
end

.get_bundler_versionObject



524
525
526
# File 'lib/shakapacker/runner.rb', line 524

def self.get_bundler_version
  execute_bundler_command("--version") { |stdout| stdout.strip }
end

.init_config_fileObject



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/shakapacker/runner.rb', line 478

def self.init_config_file
  loader = BuildConfigLoader.new
  config_path = loader.config_file_path

  if loader.exists?
    puts "[Shakapacker] Config file already exists: #{config_path}"
    puts "Use --list-builds to see available builds"
    return
  end

  # Delegate to bin/shakapacker-config
  app_path = File.expand_path(".", Dir.pwd)
  shakapacker_config_path = File.join(app_path, "bin", "shakapacker-config")

  unless File.exist?(shakapacker_config_path)
    $stderr.puts "[Shakapacker] Error: bin/shakapacker-config not found"
    $stderr.puts "Please ensure Shakapacker is properly installed"
    exit(1)
  end

  # Run the init command and check if it succeeded
  unless system(shakapacker_config_path, "--init")
    exit_code = $?.exitstatus || 1
    $stderr.puts "[Shakapacker] Error: Failed to run: #{shakapacker_config_path} --init"
    $stderr.puts "[Shakapacker] Command exited with status: #{exit_code}"
    exit(exit_code)
  end
end

.list_buildsObject



507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/shakapacker/runner.rb', line 507

def self.list_builds
  loader = BuildConfigLoader.new

  unless loader.exists?
    puts "[Shakapacker] No config file found: #{loader.config_file_path}"
    puts "Run 'bin/shakapacker --init' to create one"
    return
  end

  begin
    loader.list_builds
  rescue ArgumentError => e
    $stderr.puts "[Shakapacker] Error: #{e.message}"
    exit(1)
  end
end


372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/shakapacker/runner.rb', line 372

def self.print_bundler_help(verbose: false)
  help_flag = verbose ? "--help=verbose" : "--help"
  bundler_type, bundler_help = get_bundler_help(help_flag)

  if bundler_help
    bundler_name = bundler_type == :rspack ? "RSPACK" : "WEBPACK"
    puts "=" * 80
    puts "AVAILABLE #{bundler_name} OPTIONS (Passed directly to #{bundler_name.downcase})"
    puts "=" * 80
    puts
    puts filter_managed_options(bundler_help)
    puts
    puts "For complete documentation:"
    if bundler_type == :rspack
      puts "  https://rspack.dev/api/cli"
    else
      puts "  https://webpack.js.org/api/cli/"
    end
  else
    puts "For complete documentation:"
    puts "  Webpack: https://webpack.js.org/api/cli/"
    puts "  Rspack:  https://rspack.dev/api/cli"
  end
end


315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/shakapacker/runner.rb', line 315

def self.print_help(verbose: false)
  puts "  ================================================================================\n  SHAKAPACKER - Rails Webpack/Rspack Integration\n  ================================================================================\n\n  Usage: bin/shakapacker [options]\n\n  Shakapacker-specific options:\n    -h, --help                Show this help message\n        --help=verbose        Show verbose help including all bundler options\n    -v, --version             Show Shakapacker version\n    --debug-shakapacker       Enable Node.js debugging (--inspect-brk)\n    --trace-deprecation       Show stack traces for deprecations\n    --no-deprecation          Silence deprecation warnings\n    --bundler <webpack|rspack>\n                              Override bundler (defaults to shakapacker.yml)\n\n  Build configurations (config/shakapacker-builds.yml):\n    --init                    Create config/shakapacker-builds.yml\n    --list-builds             List available builds\n    --build <name>            Run a specific build configuration\n\n  Examples (build configs):\n    bin/shakapacker --init                       # Create config file\n    bin/shakapacker --list-builds                # Show available builds\n    bin/shakapacker --build dev-hmr              # Run the 'dev-hmr' build\n    bin/shakapacker --build prod                 # Run the 'prod' build\n    bin/shakapacker --build prod --bundler rspack # Override to use rspack\n\n    Note: If a build has dev_server: true in its config, it will\n    automatically use bin/shakapacker-dev-server instead.\n\n    Advanced: Use bin/shakapacker-config for more config management options\n    (validate builds, export configs, etc.)\n\n  HELP\n\n  print_bundler_help(verbose: verbose)\n\n  puts <<~HELP\n\n  Examples (passing options to webpack/rspack):\n    bin/shakapacker                              # Build for production\n    bin/shakapacker --bundler rspack             # Build with rspack instead of webpack\n    bin/shakapacker --mode development           # Build for development\n    bin/shakapacker --watch                      # Watch mode\n    bin/shakapacker --mode development --analyze # Development build with analysis\n    bin/shakapacker --debug-shakapacker          # Debug with Node inspector\n\n  Options managed by Shakapacker (configured via config files):\n    --config                  Set automatically based on assets_bundler_config_path\n                              (defaults to config/webpack or config/rspack)\n    --node-env                Set from RAILS_ENV or NODE_ENV\n  HELP\nend\n"


466
467
468
469
470
471
472
473
474
475
476
# File 'lib/shakapacker/runner.rb', line 466

def self.print_version
  puts "Shakapacker #{Shakapacker::VERSION}"
  puts "Framework: Rails #{Rails.version}" if defined?(Rails)

  # Try to get bundler version
  bundler_type, bundler_version = get_bundler_version
  if bundler_version
    bundler_name = bundler_type == :rspack ? "Rspack" : "Webpack"
    puts "Bundler: #{bundler_name} #{bundler_version}"
  end
end

.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