Module: CodexNotify::HookCLI

Defined in:
lib/codex_notify/hook_cli.rb

Constant Summary collapse

MAX_STDIN_BYTES =
1_048_576

Class Method Summary collapse

Class Method Details

.main(argv = nil, stdin: $stdin, stderr: $stderr, stdout: $stdout, runner_factory: HookRunner.method(:new), legacy_checkout_root: nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
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
# File 'lib/codex_notify/hook_cli.rb', line 16

def main(argv = nil, stdin: $stdin, stderr: $stderr, stdout: $stdout,
         runner_factory: HookRunner.method(:new), legacy_checkout_root: nil)
  args = HookConfig.parse_args(argv, stderr:, legacy_checkout_root:)

  if args.migrate_config
    env_path = args.env_file if args.env_file_explicit
    return ConfigMigrator.new(legacy_checkout_root:, stdout:, stderr:).run(
      env_path:,
      config_path: args.config_file
    )
  end

  if args.outbox_action
    return OutboxCommands.run(
      action: args.outbox_action,
      id: args.outbox_id,
      outbox_dir: args.outbox_dir,
      token: args.token,
      channel: args.channel,
      state_file: args.state_file,
      stdout:,
      stderr:
    )
  end

  unless args.token && args.channel
    stderr.puts('ERROR: need --token/--channel or a Slack destination from environment or config file')
    return 2
  end

  payload = parse_stdin(stdin)
  event = HookInputValidator.validate(event_name: args.event_name, payload:)

  runner = runner_factory.call(
    token: args.token,
    channel: args.channel,
    user_name: args.user_name,
    title: args.title,
    state_file: args.state_file,
    outbox_dir: args.outbox_dir,
    mode: args.mode,
    stdout: stdout
  )
  code = runner.run(event:)
  stderr.puts('ERROR: Slack delivery requires outbox review; run --outbox-status') if code == 1
  code
rescue Interrupt
  0
rescue HookInputError => e
  stderr.puts("ERROR: #{e.message}")
  2
rescue HookConfig::Error, ConfigMigrator::Error, OptionParser::ParseError => e
  stderr.puts("ERROR: #{e.message}")
  2
rescue StandardError => e
  stderr.puts("ERROR: #{e.class}: #{e.message}")
  1
end

.parse_stdin(stdin) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/codex_notify/hook_cli.rb', line 75

def parse_stdin(stdin)
  raw = stdin.read(MAX_STDIN_BYTES + 1).to_s
  if raw.bytesize > MAX_STDIN_BYTES
    raise HookInputError, "hook stdin exceeds maximum size of #{MAX_STDIN_BYTES} bytes"
  end
  raise HookInputError, 'hook stdin is empty' if raw.strip.empty?

  payload = JSON.parse(raw)
  raise HookInputError, 'hook payload must be a JSON object' unless payload.is_a?(Hash)

  payload
rescue JSON::ParserError
  raise HookInputError, 'hook stdin is not valid JSON'
end