Module: Tempest::Commands::Base

Defined in:
lib/tempest/commands/base.rb

Constant Summary collapse

VALID_FORMATS =
%i[line json raw].freeze

Class Method Summary collapse

Class Method Details

.authenticate(env:, stderr:, store: nil) ⇒ Object

Loads the cached session and refreshes it. Returns the session on success. On failure (no cache, refresh rejected) writes a single human-readable line to stderr and returns nil; callers translate the nil into exit code 3.



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/tempest/commands/base.rb', line 17

def authenticate(env:, stderr:, store: nil)
  store ||= Tempest::SessionStore.new(path: Tempest::SessionStore.default_path(env))
  session = store.load(identifier: env["TEMPEST_IDENTIFIER"], pds_host: env["TEMPEST_PDS_HOST"])
  if session.nil?
    stderr.puts "error: no cached session — run `tempest tui` once to sign in"
    return nil
  end
  session.on_change = ->(s) { store.save(s, identifier: s.identifier) }
  begin
    session.refresh!
  rescue Tempest::Error => e
    stderr.puts "error: cached session refresh failed: #{e.message}"
    return nil
  end
  session
end

.default_format(stdout:, env:) ⇒ Object

Returns one of :line, :json, :raw. Callers may override with –format.



35
36
37
# File 'lib/tempest/commands/base.rb', line 35

def default_format(stdout:, env:)
  stdout.respond_to?(:tty?) && stdout.tty? ? :line : :json
end

.exit_code_for(error) ⇒ Object



58
59
60
61
62
63
64
65
66
# File 'lib/tempest/commands/base.rb', line 58

def exit_code_for(error)
  case error
  when Tempest::Config::MissingValue then 2
  when Tempest::AuthenticationError  then 3
  when Tempest::APIError             then 4
  when ArgumentError                 then 64
  else                                    1
  end
end

.take_format(argv, default:) ⇒ Object

Parses –format=NAME from argv (destructive: returns [format, argv_without_flag]). Raises ArgumentError on unknown format names.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tempest/commands/base.rb', line 41

def take_format(argv, default:)
  out = []
  chosen = default
  argv.each do |arg|
    if (m = arg.match(/\A--format=(\S+)\z/))
      sym = m[1].to_sym
      raise ArgumentError, "invalid --format: #{m[1].inspect}" unless VALID_FORMATS.include?(sym)
      chosen = sym
    elsif arg == "--no-color"
      Tempest::REPL::Formatter.color = false if defined?(Tempest::REPL::Formatter)
    else
      out << arg
    end
  end
  [chosen, out]
end