discourse-disco-cli 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ff6af9157046dd4c925075c0bbc104743a31a68e608226611a1c0dc612d63142
4
+ data.tar.gz: a6e859510df7fac5aa1b8588e0ea5d0b983b865d4109a57034ca116330c37ec1
5
+ SHA512:
6
+ metadata.gz: dfe3cbca1bcb2f7aa8fe6d61e17adaa760a5d9487d9a8fb04109abee0a5fb9925b53e4fdc6442741bb4f3c415e14bbcb7f7cec3f7ca7498d6430ffbccbe0c07f
7
+ data.tar.gz: ed02ef6b32c85ea8428aa300d84d6f541c7de83807c23928a3252f9781ff3d234703300cda09b83ef1c0f8f69dedc55c16ee739109599239c3dffc1cd4543b0b
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Civilized Discourse Construction Kit, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "colored2"
4
+ require "samovar"
5
+
6
+ module DiscourseDisco
7
+ module CLI
8
+ # Builds the Samovar command tree from the registry, selects the command for
9
+ # the given argv, lazily boots Rails when the selected command requires it,
10
+ # and dispatches.
11
+ module Bootstrap
12
+ # `program_name` is how users call the launcher; it's shown in usage and
13
+ # hints. `boot_rails` is a callable that boots the Rails app, or `nil`
14
+ # when the launcher runs without one.
15
+ def self.run(argv, program_name:, boot_rails: nil, description: nil)
16
+ CLI.configure(program_name:, boot_rails:)
17
+
18
+ argv = normalize_option_args(argv)
19
+ # The top-level command has no options, so a command name can only be
20
+ # the first token.
21
+ selected = Registry.entries[argv.first]
22
+ if selected
23
+ selected.loader&.call
24
+ CLI.boot_rails!("#{program_name} #{selected.name}") if selected.requires_rails
25
+ end
26
+
27
+ top = build_top_command_class(description, selected&.name).new(argv, name: program_name)
28
+
29
+ leaf = deepest_command(top)
30
+ if leaf.class.respond_to?(:requires_rails?) && leaf.class.requires_rails?
31
+ CLI.boot_rails!(command_line(leaf))
32
+ end
33
+
34
+ top.call
35
+ rescue Samovar::Error => e
36
+ # The top-level command has no `--help` option, so a help request
37
+ # surfaces as an unparsable token.
38
+ help_request = e.is_a?(Samovar::InvalidInputError) && %w[--help -h].include?(e.token)
39
+
40
+ if !help_request
41
+ # e.g. `Could not parse token "validat"` — without it, an
42
+ # unrecognized command or argument prints bare usage with no
43
+ # explanation of what was wrong.
44
+ puts e.message.red
45
+ puts
46
+ end
47
+
48
+ e.command.print_usage
49
+ exit(help_request ? 0 : 1)
50
+ end
51
+
52
+ # Samovar expects `--opt value`, but users also type `--opt=value`, so
53
+ # split that form into two tokens. Only long options are touched; `--`,
54
+ # short flags, and bare positional values pass through unchanged.
55
+ def self.normalize_option_args(argv)
56
+ argv.flat_map do |arg|
57
+ if arg.start_with?("--") && (index = arg.index("=")) && index > 2
58
+ [arg[0...index], arg[(index + 1)..]]
59
+ else
60
+ arg
61
+ end
62
+ end
63
+ end
64
+
65
+ # Walks the nested `command` chain to the deepest selected sub-command.
66
+ def self.deepest_command(command)
67
+ node = command
68
+ node = node.command while node.respond_to?(:command) && node.command
69
+ node
70
+ end
71
+
72
+ # Lists a command whose class needs Rails or a loader, so usage and
73
+ # `--help` stay fast. It's never called: selecting the command loads the
74
+ # real class.
75
+ def self.placeholder(entry)
76
+ Class.new(Command) { self.description = entry.description }
77
+ end
78
+
79
+ def self.command_line(command)
80
+ names = []
81
+ node = command
82
+ while node
83
+ names.unshift(node.name)
84
+ node = node.parent
85
+ end
86
+ names.join(" ")
87
+ end
88
+
89
+ def self.build_top_command_class(description, selected_name)
90
+ commands =
91
+ Registry
92
+ .entries
93
+ .sort_by { |name, _| name }
94
+ .to_h do |name, entry|
95
+ if entry.deferred? && name != selected_name
96
+ [name, placeholder(entry)]
97
+ else
98
+ [name, Registry.resolve(name)]
99
+ end
100
+ end
101
+
102
+ Class.new(Command) do
103
+ self.description = description
104
+ nested :command, commands
105
+
106
+ def call
107
+ if @command
108
+ @command.call
109
+ else
110
+ print_usage
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "samovar"
4
+
5
+ module DiscourseDisco
6
+ module CLI
7
+ # Base class for all `disco` commands. Commands that need a booted Rails
8
+ # environment declare `requires_rails!`; the binary boots Rails only after
9
+ # such a command has been selected, keeping help and Rails-free commands
10
+ # fast.
11
+ class Command < Samovar::Command
12
+ # Raised by {#require_positional!} when a required positional is missing.
13
+ class MissingPositionalError < StandardError
14
+ include PresentableError
15
+ end
16
+
17
+ def self.requires_rails!
18
+ @requires_rails = true
19
+ end
20
+
21
+ def self.requires_rails?
22
+ return true if @requires_rails == true
23
+ superclass.respond_to?(:requires_rails?) && superclass.requires_rails?
24
+ end
25
+
26
+ # Samovar parses each declaration once, front-to-back, and only matches
27
+ # options at the front of the remaining input — so by default options must
28
+ # precede positionals (`convert --only x discourse`). Hoist any recognized
29
+ # option flags (and their values) to the front so they may also appear
30
+ # after positionals (`convert discourse --only x`), as users expect from
31
+ # most CLIs. Everything after a `--` separator is left as-is.
32
+ def parse(input)
33
+ # Reorder in place: Samovar consumes the input array by reference (nested
34
+ # commands rely on it being emptied), so we must mutate it rather than
35
+ # pass a copy.
36
+ input.replace(hoist_options(input))
37
+ super(input)
38
+ end
39
+
40
+ private
41
+
42
+ # Samovar can't enforce required positionals: `one :x, required: true`
43
+ # raises during parsing, before `call` runs, which would break the
44
+ # `-h/--help` handling. Commands validate required positionals at the
45
+ # top of `call` with this helper instead.
46
+ def require_positional!(value, name, hint: nil)
47
+ return value unless value.nil?
48
+
49
+ message = +"Missing required argument: <#{name}>"
50
+ message << "\n#{hint}" if hint
51
+ raise MissingPositionalError, message
52
+ end
53
+
54
+ def hoist_options(input)
55
+ options = self.class.table.merged[:options]
56
+ return input unless options
57
+
58
+ takes_value = {}
59
+ options.each do |option|
60
+ option.flags.each do |flag|
61
+ [flag.prefix, *Array(flag.alternatives)].each do |prefix|
62
+ takes_value[prefix] = !flag.boolean?
63
+ end
64
+ end
65
+ end
66
+
67
+ flags = []
68
+ positionals = []
69
+ index = 0
70
+
71
+ while index < input.size
72
+ token = input[index]
73
+
74
+ if token == "--"
75
+ positionals.concat(input[index..])
76
+ break
77
+ elsif takes_value.key?(token)
78
+ flags << token
79
+ if takes_value[token] && index + 1 < input.size
80
+ flags << input[index + 1]
81
+ index += 1
82
+ end
83
+ else
84
+ positionals << token
85
+ end
86
+
87
+ index += 1
88
+ end
89
+
90
+ flags + positionals
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "colored2"
4
+
5
+ module DiscourseDisco
6
+ module CLI
7
+ class ExceptionHandler
8
+ def self.handle_and_exit(&block)
9
+ block.call
10
+ rescue PresentableError => e
11
+ e.present
12
+ exit(1)
13
+ rescue => e
14
+ puts "An error occurred: #{e.message}".red
15
+ puts e.backtrace.join("\n")
16
+ exit(1)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "colored2"
4
+
5
+ module DiscourseDisco
6
+ module CLI
7
+ # Errors including this module are shown to the user as a clean, red message
8
+ # (no backtrace) by the ExceptionHandler.
9
+ module PresentableError
10
+ # Override to print more than the message, e.g. suggestions for a typo.
11
+ def present
12
+ puts message.red
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiscourseDisco
4
+ module CLI
5
+ # Central registry of top-level commands. Launchers, gems and plugins
6
+ # register their commands here at startup. The Samovar command tree is
7
+ # built from this registry just before argv is parsed.
8
+ module Registry
9
+ # `requires_rails` means the command class itself can only be loaded
10
+ # after Rails booted, e.g. because it comes from a gem that Rails
11
+ # activates. `loader` is a callable that makes the class loadable some
12
+ # other way, e.g. by activating the gems it comes from. Either way the
13
+ # class is loaded only when its command is called.
14
+ Entry =
15
+ Struct.new(
16
+ :name,
17
+ :command_class,
18
+ :description,
19
+ :requires_rails,
20
+ :loader,
21
+ keyword_init: true,
22
+ ) do
23
+ def deferred?
24
+ requires_rails || !loader.nil?
25
+ end
26
+ end
27
+
28
+ def self.entries
29
+ @entries ||= {}
30
+ end
31
+
32
+ def self.register(name:, command_class:, description: nil, requires_rails: nil, loader: nil)
33
+ name = name.to_s
34
+ raise "A command named '#{name}' is already registered" if entries.key?(name)
35
+
36
+ defaults = @defaults || {}
37
+ requires_rails = defaults[:requires_rails] if requires_rails.nil?
38
+ entries[name] = Entry.new(
39
+ name:,
40
+ command_class:,
41
+ description:,
42
+ requires_rails: requires_rails || false,
43
+ loader: loader || defaults[:loader],
44
+ )
45
+ end
46
+
47
+ # Applies `requires_rails` and `loader` to the commands registered in the
48
+ # block. A launcher wraps the registration files of code that it loads in
49
+ # a special way, so the same files work for a launcher that loads that
50
+ # code directly.
51
+ def self.with_defaults(requires_rails: nil, loader: nil)
52
+ previous = @defaults
53
+ @defaults = (previous || {}).merge({ requires_rails:, loader: }.compact)
54
+ yield
55
+ ensure
56
+ @defaults = previous
57
+ end
58
+
59
+ def self.reset!
60
+ @entries = {}
61
+ end
62
+
63
+ # Classes may be registered by name, so registering doesn't load them
64
+ # (or Rails) early.
65
+ def self.resolve(name)
66
+ klass = entries.fetch(name).command_class
67
+ klass = Object.const_get(klass.to_s) if klass.is_a?(String) || klass.is_a?(Symbol)
68
+ klass
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module DiscourseDisco
4
+ module CLI
5
+ VERSION = "0.3.0"
6
+ end
7
+ end
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cli/presentable_error"
4
+
5
+ module DiscourseDisco
6
+ module CLI
7
+ # Raised when a command needs Rails but the launcher can't boot it, e.g. a
8
+ # standalone launcher that runs outside of a Discourse install.
9
+ class RailsUnavailableError < StandardError
10
+ include PresentableError
11
+ end
12
+
13
+ # Module-level so that code outside the command tree, like generated hints,
14
+ # can show how to call the program. Falls back to the script name when
15
+ # nothing was configured, which is also what Samovar uses.
16
+ def self.program_name
17
+ @program_name || File.basename($PROGRAM_NAME)
18
+ end
19
+
20
+ def self.configure(program_name:, boot_rails: nil)
21
+ @program_name = program_name
22
+ @boot_rails = boot_rails
23
+ @rails_booted = false
24
+ end
25
+
26
+ def self.rails_available?
27
+ !@boot_rails.nil?
28
+ end
29
+
30
+ # Commands that need Rails only in some modes call this instead of declaring
31
+ # `requires_rails!`, so their other modes and `--help` stay fast.
32
+ def self.boot_rails!(command_line = nil)
33
+ return if @rails_booted
34
+
35
+ if !rails_available?
36
+ subject = command_line ? "`#{command_line}`" : "This command"
37
+ raise RailsUnavailableError, "#{subject} needs a Discourse install."
38
+ end
39
+
40
+ @boot_rails.call
41
+ @rails_booted = true
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "discourse_disco/cli/version"
4
+ require_relative "discourse_disco/cli"
5
+ require_relative "discourse_disco/cli/presentable_error"
6
+ require_relative "discourse_disco/cli/registry"
7
+ require_relative "discourse_disco/cli/command"
8
+ require_relative "discourse_disco/cli/bootstrap"
9
+ require_relative "discourse_disco/cli/exception_handler"
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: discourse-disco-cli
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Discourse Team
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: colored2
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '4.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '4.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: samovar
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '2.5'
33
+ type: :runtime
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '2.5'
40
+ description: 'Provides the building blocks of the disco command line tool: a registry
41
+ that applications and plugins add their commands to, a bootstrap that parses the
42
+ command line and boots Rails only for commands that need it, a base class for commands,
43
+ and an exception handler that prints user-facing errors without a backtrace.'
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - LICENSE.txt
49
+ - lib/discourse_disco/cli.rb
50
+ - lib/discourse_disco/cli/bootstrap.rb
51
+ - lib/discourse_disco/cli/command.rb
52
+ - lib/discourse_disco/cli/exception_handler.rb
53
+ - lib/discourse_disco/cli/presentable_error.rb
54
+ - lib/discourse_disco/cli/registry.rb
55
+ - lib/discourse_disco/cli/version.rb
56
+ - lib/discourse_disco_cli.rb
57
+ homepage: https://github.com/discourse/discourse-disco-cli
58
+ licenses:
59
+ - MIT
60
+ metadata:
61
+ allowed_push_host: https://rubygems.org
62
+ homepage_uri: https://github.com/discourse/discourse-disco-cli
63
+ source_code_uri: https://github.com/discourse/discourse-disco-cli
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: '3.4'
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.6.9
79
+ specification_version: 4
80
+ summary: Command framework for Discourse's disco command line tool
81
+ test_files: []