repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/scope_spec.rb
spec/lib/guard/commands/scope_spec.rb
# frozen_string_literal: true require "guard/commands/scope" RSpec.describe Guard::Commands::Scope, :stub_ui do include_context "with engine" include_context "with fake pry" let!(:frontend_group) { engine.groups.add("frontend") } let!(:dummy_plugin) { engine.plugins.add("dummy", group: frontend_group) } before do allow(Pry::Commands).to receive(:create_command).with("scope") do |&block| FakePry.instance_eval(&block) end described_class.import end context "without scope" do it "does not call :scope= and shows usage" do expect(output).to receive(:puts).with("Usage: scope <scope>") expect(engine.session).to_not receive(:interactor_scopes=) FakePry.process end end context "with a valid Guard group scope" do it "sets up the scope with the given scope" do expect(engine.session).to receive(:interactor_scopes=) .with(groups: [:frontend], plugins: []) FakePry.process("frontend") end end context "with a valid Guard plugin scope" do it "runs the :scope= action with the given scope" do expect(engine.session).to receive(:interactor_scopes=) .with(plugins: [:dummy], groups: []) FakePry.process("dummy") end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/notification_spec.rb
spec/lib/guard/commands/notification_spec.rb
# frozen_string_literal: true require "guard/commands/notification" RSpec.describe Guard::Commands::Notification, :stub_ui do include_context "with engine" include_context "with fake pry" let(:output) { instance_double(Pry::Output) } before do allow(Pry::Commands).to receive(:create_command) .with("notification") do |&block| FakePry.instance_eval(&block) end described_class.import end it "toggles the Guard notifier" do expect(::Guard::Notifier).to receive(:toggle) FakePry.process end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/change_spec.rb
spec/lib/guard/commands/change_spec.rb
# frozen_string_literal: true require "guard/commands/change" RSpec.describe Guard::Commands::Change, :stub_ui do include_context "with engine" include_context "with fake pry" let(:output) { instance_double(Pry::Output) } before do allow(Pry::Commands).to receive(:create_command).with("change") do |&block| FakePry.instance_eval(&block) end described_class.import end context "with a file" do it "runs the :run_on_changes action with the given file" do expect(engine).to receive(:async_queue_add) .with(modified: ["foo"], added: [], removed: []) FakePry.process("foo") end end context "with multiple files" do it "runs the :run_on_changes action with the given files" do expect(engine).to receive(:async_queue_add) .with(modified: %w[foo bar baz], added: [], removed: []) FakePry.process("foo", "bar", "baz") end end context "without a file" do it "does not run the :run_on_changes action" do expect(engine).to_not receive(:async_queue_add) expect(output).to receive(:puts).with("Please specify a file.") FakePry.process end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/groups_spec.rb
spec/lib/guard/internals/groups_spec.rb
# frozen_string_literal: true require "guard/internals/groups" RSpec.describe Guard::Internals::Groups do describe "#all" do let(:default) { instance_double("Guard::Group", name: :default) } before do allow(Guard::Group).to receive(:new).with(:default).and_return(default) end context "with only default groups" do it "initializes the groups" do expect(subject.all.map(&:name)).to eq %i[default] end end context "with existing groups" do let(:frontend) { instance_double("Guard::Group", name: :frontend) } let(:backend) { instance_double("Guard::Group", name: :backend) } before do allow(Guard::Group).to receive(:new).with(:frontend, {}) .and_return(frontend) allow(Guard::Group).to receive(:new).with(:backend, {}) .and_return(backend) subject.add(:frontend) subject.add(:backend) end context "with no arguments" do let(:args) { [] } it "returns all groups" do expect(subject.all(*args)).to eq [default, frontend, backend] end end context "with a string argument" do it "returns an array of groups if plugins are found" do expect(subject.all("backend")).to eq [backend] end end context "with a symbol argument matching a group" do it "returns an array of groups if plugins are found" do expect(subject.all(:backend)).to eq [backend] end end context "with a symbol argument not matching a group" do it "returns an empty array when no group is found" do expect(subject.all(:foo)).to be_empty end end context "with a regexp argument matching a group" do it "returns an array of groups" do expect(subject.all(/^back/)).to eq [backend] end end context "with a regexp argument not matching a group" do it "returns an empty array when no group is found" do expect(subject.all(/back$/)).to be_empty end end end end describe "#add" do let(:default) { instance_double("Guard::Group", name: :default) } before do allow(Guard::Group).to receive(:new).with(:default).and_return(default) end context "with existing groups" do let(:frontend) { instance_double("Guard::Group", name: :frontend) } let(:backend) { instance_double("Guard::Group", name: :backend) } before do allow(Guard::Group).to receive(:new).with("frontend", {}) .and_return(frontend) subject.add("frontend") end it "add the given group" do subject.add("frontend") expect(subject.all).to match_array([default, frontend]) end it "add the given group with options" do subject.add("frontend", foo: :bar) expect(subject.all).to match_array([default, frontend]) end context "with an existing group" do before { subject.add("frontend") } it "does not add duplicate groups when name is a string" do subject.add("frontend") expect(subject.all).to match_array([default, frontend]) end it "does not add duplicate groups when name is a symbol" do subject.add(:frontend) expect(subject.all).to match_array([default, frontend]) end it "does not add duplicate groups even if options are different" do subject.add(:frontend, halt_on_fail: true) subject.add(:frontend, halt_on_fail: false) expect(subject.all).to match_array([default, frontend]) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/session_spec.rb
spec/lib/guard/internals/session_spec.rb
# frozen_string_literal: true require "guard/internals/session" RSpec.describe Guard::Internals::Session, :stub_ui do include_context "with engine" let(:options) { {} } subject { engine.session } describe "#initialize" do describe "#listener_args" do subject { described_class.new(options).listener_args } context "with a single watchdir" do let(:options) { { watchdirs: ["/usr"] } } let(:dir) { Gem.win_platform? ? "C:/usr" : "/usr" } it { is_expected.to eq [:to, dir, {}] } end context "with multiple watchdirs" do let(:options) { { watchdirs: ["/usr", "/bin"] } } let(:dir1) { Gem.win_platform? ? "C:/usr" : "/usr" } let(:dir2) { Gem.win_platform? ? "C:/bin" : "/bin" } it { is_expected.to eq [:to, dir1, dir2, {}] } end context "with force_polling option" do let(:options) { { force_polling: true } } it { is_expected.to eq [:to, Dir.pwd, force_polling: true] } end context "with latency option" do let(:options) { { latency: 1.5 } } it { is_expected.to eq [:to, Dir.pwd, latency: 1.5] } end end context "with the plugin option" do let(:options) do { plugin: %w[dummy doe] } end it "initializes the plugin scope" do expect(subject.cmdline_scopes.plugins).to match_array(%w[dummy doe]) end end context "with the group option" do let(:options) do { group: %w[backend frontend] } end it "initializes the group scope" do expect(subject.cmdline_scopes.groups).to match_array(%w[backend frontend]) end end describe "debugging" do let(:options) { { debug: debug } } context "when debug is set to true" do let(:debug) { true } it "sets up debugging" do expect(Guard::Internals::Debugging).to receive(:start) subject end end context "when debug is set to false" do let(:debug) { false } it "does not set up debugging" do expect(Guard::Internals::Debugging).to_not receive(:start) subject end end end end describe "#clearing" do context "when not set" do context "when clearing is not set from commandline" do it { is_expected.to_not be_clearing } end context "when clearing is set from commandline" do let(:options) { { clear: false } } it { is_expected.to_not be_clearing } end end context "when set from guardfile" do context "when set to :on" do before { subject.clearing(true) } it { is_expected.to be_clearing } end context "when set to :off" do before { subject.clearing(false) } it { is_expected.to_not be_clearing } end end end describe "#guardfile_ignore=" do context "when set from guardfile" do before { subject.guardfile_ignore = [/foo/] } specify { expect(subject.guardfile_ignore).to eq([/foo/]) } end context "when set multiple times from guardfile" do before do subject.guardfile_ignore = [/foo/] subject.guardfile_ignore = [/bar/] end specify { expect(subject.guardfile_ignore).to eq([/foo/, /bar/]) } end context "when unset" do specify { expect(subject.guardfile_ignore).to eq([]) } end end describe "#guardfile_ignore_bang=" do context "when set from guardfile" do before { subject.guardfile_ignore_bang = [/foo/] } specify { expect(subject.guardfile_ignore_bang).to eq([/foo/]) } end context "when unset" do specify { expect(subject.guardfile_ignore_bang).to eq([]) } end end describe "#guardfile_scope" do before do subject.guardfile_scopes = scopes end context "with a groups scope" do let(:scopes) { { groups: [:foo] } } it "sets the groups" do expect(subject.guardfile_scopes.groups).to eq([:foo]) end end context "with a group scope" do let(:scopes) { { group: [:foo] } } it "sets the groups" do expect(subject.guardfile_scopes.groups).to eq([:foo]) end end context "with a plugin scope" do let(:scopes) { { plugin: [:foo] } } it "sets the plugins" do expect(subject.guardfile_scopes.plugins).to eq([:foo]) end end context "with a plugins scope" do let(:scopes) { { plugins: [:foo] } } it "sets the plugins" do expect(subject.guardfile_scopes.plugins).to eq([:foo]) end end end describe "#guardfile_notification=" do context "when set from guardfile" do before do subject.guardfile_notification = { foo: { bar: :baz } } end specify do expect(subject.notify_options).to eq( notify: true, notifiers: { foo: { bar: :baz } } ) end end context "when set multiple times from guardfile" do before do subject.guardfile_notification = { foo: { param: 1 } } subject.guardfile_notification = { bar: { param: 2 } } end it "merges results" do expect(subject.notify_options).to eq( notify: true, notifiers: { foo: { param: 1 }, bar: { param: 2 } } ) end end context "when unset" do specify do expect(subject.notify_options).to eq(notify: true, notifiers: {}) end end end describe "#convert_scopes" do let!(:frontend_group) { groups.add("frontend") } let!(:backend_group) { groups.add("backend") } let!(:dummy_plugin) { plugins.add("dummy", group: "frontend") } let!(:doe_plugin) { plugins.add("doe", group: "backend") } it "returns a group scope" do scopes, = subject.convert_scopes(:backend) expect(scopes).to eq(groups: [:backend], plugins: []) scopes, = subject.convert_scopes(%w[frontend]) expect(scopes).to eq(groups: [:frontend], plugins: []) end it "returns a plugin scope" do scopes, = subject.convert_scopes("dummy") expect(scopes).to eq(plugins: [:dummy], groups: []) scopes, = subject.convert_scopes(%w[doe]) expect(scopes).to eq(plugins: [:doe], groups: []) end it "returns multiple group scopes" do scopes, = subject.convert_scopes(%w[backend frontend]) expected = { groups: %i[backend frontend], plugins: [] } expect(scopes).to eq(expected) end it "returns multiple plugin scopes" do scopes, = subject.convert_scopes(%w[dummy doe]) expect(scopes).to eq(plugins: %i[dummy doe], groups: []) end it "returns a plugin and group scope" do scopes, = subject.convert_scopes(%w[backend dummy]) expect(scopes).to eq(groups: [:backend], plugins: [:dummy]) end it "returns the unkown scopes" do _, unknown = subject.convert_scopes(%w[unknown scope]) expect(unknown).to eq(%w[unknown scope]) end end describe "#grouped_plugins" do let!(:frontend_group) { subject.groups.add("frontend") } let!(:backend_group) { subject.groups.add("backend") } let!(:dummy_plugin) { subject.plugins.add("dummy", group: frontend_group) } let!(:doe_plugin) { subject.plugins.add("doe", group: backend_group) } context "with no arguments given" do it "returns all the grouped plugins" do expect(subject.grouped_plugins).to eq({ frontend_group => [dummy_plugin], backend_group => [doe_plugin] }) end end context "with a single :plugins scope given" do it "returns the given grouped plugins" do expect(subject.grouped_plugins(plugins: :dummy)).to eq({ frontend_group => [dummy_plugin] }) end end context "with multiple :plugins scope given" do it "returns the given grouped plugins" do expect(subject.grouped_plugins(plugins: %i[dummy doe])) .to eq({ frontend_group => [dummy_plugin], backend_group => [doe_plugin] }) end end context "with a single :groups scope given" do it "returns the given grouped plugins" do expect(subject.grouped_plugins(groups: :frontend)).to eq({ frontend_group => [dummy_plugin] }) end end context "with multiple :plugins scope given" do it "returns the given grouped plugins" do expect(subject.grouped_plugins(groups: %i[frontend backend])) .to eq({ frontend_group => [dummy_plugin], backend_group => [doe_plugin] }) end end shared_examples "scopes titles" do it "return the titles for the given scopes" do expect(subject.grouped_plugins).to eq({ frontend_group => [dummy_plugin] }) end end shared_examples "empty scopes titles" do it "return an empty array" do expect(subject.grouped_plugins).to be_empty end end { groups: "frontend", plugins: "dummy" }.each do |scope, name| let(:given_scope) { scope } let(:name_for_scope) { name } describe "#{scope.inspect} (#{name})" do context "when set from interactor" do before do session.interactor_scopes = { given_scope => name_for_scope } end it_behaves_like "scopes titles" end context "when not set in interactor" do context "when set in commandline" do let(:options) { { given_scope => [name_for_scope] } } it_behaves_like "scopes titles" end context "when not set in commandline" do context "when set in Guardfile" do before do session.guardfile_scopes = { given_scope => name_for_scope } end it_behaves_like "scopes titles" end end end end end describe "with groups and plugins scopes" do before do session.interactor_scopes = { groups: "frontend", plugins: "dummy" } end it "return only the plugins titles" do expect(subject.grouped_plugins).to eq({ frontend_group => [dummy_plugin] }) end end end describe "#scope_titles" do let!(:frontend_group) { subject.groups.add("frontend") } let!(:dummy_plugin) { subject.plugins.add("dummy", group: "frontend") } context "with no arguments given" do it "returns 'all'" do expect(subject.scope_titles).to eq ["all"] end end context "with a 'plugins' scope given" do it "returns the plugins' titles" do expect(subject.scope_titles([:dummy])).to eq ["Dummy"] end end context "with a 'groups' scope given" do it "returns the groups' titles" do expect(subject.scope_titles(:default)).to eq ["Default"] end end context "with a 'groups' scope given" do it "returns the groups' titles" do expect(subject.scope_titles([:frontend])).to eq ["Frontend"] end end context "with both 'plugins' and 'groups' scopes given" do it "returns only the plugins' titles" do expect(subject.scope_titles(%i[dummy frontend])).to eq ["Dummy"] end end shared_examples "scopes titles" do it "return the titles for the given scopes" do expect(subject.scope_titles).to eq subject.public_send(given_scope).all(name_for_scope).map(&:title) end end shared_examples "empty scopes titles" do it "return an empty array" do expect(subject.scope_titles).to be_empty end end { groups: "frontend", plugins: "dummy" }.each do |scope, name| let(:given_scope) { scope } let(:name_for_scope) { name } describe "#{scope.inspect} (#{name})" do context "when set from interactor" do before do session.interactor_scopes = { given_scope => name_for_scope } end it_behaves_like "scopes titles" end context "when not set in interactor" do context "when set in commandline" do let(:options) { { given_scope => [name_for_scope] } } it_behaves_like "scopes titles" end context "when not set in commandline" do context "when set in Guardfile" do before do session.guardfile_scopes = { given_scope => name_for_scope } end it_behaves_like "scopes titles" end end end end end describe "with groups and plugins scopes" do before do session.interactor_scopes = { groups: "frontend", plugins: "dummy" } end it "return only the plugins titles" do expect(subject.scope_titles).to eq subject.plugins.all.map(&:title) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/tracing_spec.rb
spec/lib/guard/internals/tracing_spec.rb
# frozen_string_literal: true require "guard/internals/tracing" RSpec.describe Guard::Internals::Tracing do let(:null) { IO::NULL } # NOTE: Calling system() is different from calling Kernel.system() # # We can capture system() calls by stubbing Kernel.system, but to capture # Kernel.system() calls, we need to stub the module's metaclass methods. # # Stubbing just Kernel.system isn't "deep" enough, but not only that, # we don't want to stub here, we want to TEST the stubbing # describe "Module method tracing" do let(:result) { Kernel.send(meth, *args) } subject { result } let(:callback) { double("callback", call: true) } # Since we can't stub the C code in Ruby, only "right" way to test this is: # actually call a real command and compare the output before { allow(Kernel).to receive(meth).and_call_original } context "when tracing" do before do described_class.trace(Kernel, meth) { |*args| callback.call(*args) } subject end after { described_class.untrace(Kernel, meth) } context "with no command arguments" do let(:args) { ["echo >#{null}"] } context "when #system" do let(:meth) { "system" } it { is_expected.to eq(true) } it "outputs command" do expect(callback).to have_received(:call).with("echo >#{null}") end end context "when backticks" do let(:meth) { :` } it { is_expected.to eq("") } it "outputs command" do expect(callback).to have_received(:call).with("echo >#{null}") end end end context "with command arguments" do let(:args) { %w[true 123] } context "when #system" do let(:meth) { "system" } it { is_expected.to eq(true) } it "outputs command arguments" do expect(callback).to have_received(:call).with("true", "123") end end end end context "when not tracing" do before { subject } context "with no command arguments" do let(:args) { ["echo test > #{null}"] } context "when #system" do let(:meth) { :system } it { is_expected.to eq(true) } it "does not output anything" do expect(callback).to_not have_received(:call) end end context "when backticks" do let(:meth) { :` } it { is_expected.to eq("") } it "does not output anything" do expect(callback).to_not have_received(:call) end end end context "with command arguments" do let(:args) { %w[true 123] } context "when #system" do let(:meth) { :system } it { is_expected.to eq(true) } it "does not output anything" do expect(callback).to_not have_received(:call) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/traps_spec.rb
spec/lib/guard/internals/traps_spec.rb
# frozen_string_literal: true require "guard/internals/traps" RSpec.describe Guard::Internals::Traps do describe ".handle" do let(:signal_class) { class_double(Signal) } before do stub_const("Signal", signal_class) end context "with a supported signal name" do let(:signal) { "USR1" } it "sets up a handler" do allow(Signal).to receive(:list).and_return("USR1" => 10) allow(Signal).to receive(:trap).with(signal) do |_, &block| block.call end expect { |b| described_class.handle(signal, &b) }.to yield_control end end context "with an unsupported signal name" do let(:signal) { "ABCD" } it "does not set a handler" do allow(Signal).to receive(:list).and_return("KILL" => 9) expect(Signal).to_not receive(:trap) described_class.handle(signal) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/debugging_spec.rb
spec/lib/guard/internals/debugging_spec.rb
# frozen_string_literal: true require "guard/internals/debugging" RSpec.describe Guard::Internals::Debugging do let(:null) { IO::NULL } let(:ui) { class_double(::Guard::UI) } let(:tracing) { class_spy(::Guard::Internals::Tracing) } before do stub_const("::Guard::Internals::Tracing", tracing) stub_const("::Guard::UI", ui) allow(ui).to receive(:debug) allow(ui).to receive(:level=) allow(Thread).to receive(:abort_on_exception=) end after do described_class.send(:_reset) end describe "#start" do it "traces Kernel.system" do expect(tracing).to receive(:trace).with(Kernel, :system) do |*_, &block| expect(ui).to receive(:debug).with("Command execution: foo") block.call "foo" end described_class.start end it "traces Kernel.`" do expect(tracing).to receive(:trace).with(Kernel, :`) do |*_, &block| expect(ui).to receive(:debug).with("Command execution: foo") block.call("foo") end described_class.start end it "traces Open3.popen3" do expect(tracing).to receive(:trace).with(Open3, :popen3) do |*_, &block| expect(ui).to receive(:debug).with("Command execution: foo") block.call("foo") end described_class.start end it "traces Kernel.spawn" do expect(tracing).to receive(:trace).with(Kernel, :spawn) do |*_, &block| expect(ui).to receive(:debug).with("Command execution: foo") block.call("foo") end described_class.start end context "when not started" do before { described_class.start } it "sets logger to debug" do expect(ui).to have_received(:level=).with(Logger::DEBUG) end it "makes threads abort on exceptions" do expect(Thread).to have_received(:abort_on_exception=).with(true) end end context "when already started" do before do allow(tracing).to receive(:trace) described_class.start end it "does not set log level" do expect(ui).to_not receive(:level=) described_class.start end end end describe "#stop" do context "when already started" do before do described_class.start described_class.stop end it "sets logger level to info" do expect(ui).to have_received(:level=).with(Logger::INFO) end it "untraces Kernel.system" do expect(tracing).to have_received(:untrace).with(Kernel, :system) end it "untraces Kernel.`" do expect(tracing).to have_received(:untrace).with(Kernel, :`) end it "untraces Open3.popen3" do expect(tracing).to have_received(:untrace).with(Kernel, :popen3) end end context "when not started" do it "does not set logger level" do described_class.stop expect(ui).to_not have_received(:level=) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/internals/plugins_spec.rb
spec/lib/guard/internals/plugins_spec.rb
# frozen_string_literal: true require "guard/internals/plugins" RSpec.describe Guard::Internals::Plugins, :stub_ui do include_context "with testing plugins" let(:frontend_group) { Guard::Group.new(:frontend) } let(:backend_group) { Guard::Group.new(:backend) } let!(:dummy_plugin) { subject.add("dummy", group: frontend_group) } let!(:doe_plugin) { subject.add("doe", group: frontend_group) } let!(:foobar_plugin) { subject.add("foobar", group: backend_group) } let!(:foobaz_plugin) { subject.add("foobaz", group: backend_group) } describe "#add" do it "adds given plugin" do dummy_plugin2 = subject.add("dummy", group: "backend") expect(subject.all).to match_array [ dummy_plugin, doe_plugin, foobar_plugin, foobaz_plugin, dummy_plugin2 ] end end describe "#remove" do it "removes given plugin" do subject.remove(dummy_plugin) expect(subject.all).to match_array [ doe_plugin, foobar_plugin, foobaz_plugin ] end end describe "#all" do context "with no arguments" do it "returns all plugins" do expect(subject.all).to match_array [ dummy_plugin, doe_plugin, foobar_plugin, foobaz_plugin ] end end context "find a plugin by string" do it "returns an array of plugins if plugins are found" do expect(subject.all("dummy")) .to match_array([dummy_plugin]) end end context "find a plugin by symbol" do it "returns an array of plugins if plugins are found" do expect(subject.all(:dummy)) .to match_array([dummy_plugin]) end it "returns an empty array when no plugin is found" do expect(subject.all("foo-foo")).to be_empty end end context "find plugins matching a regexp" do it "returns an array of plugins if plugins are found" do expect(subject.all(/^foo/)) .to match_array([foobar_plugin, foobaz_plugin]) end it "returns an empty array when no plugin is found" do expect(subject.all(/unknown$/)).to be_empty end end context "find plugins by their group as a string" do it "returns an array of plugins if plugins are found" do expect(subject.all(group: "frontend")) .to match_array([dummy_plugin, doe_plugin]) end end context "find plugins by their group as a symbol" do it "returns an array of plugins if plugins are found" do expect(subject.all(group: :frontend)) .to match_array([dummy_plugin, doe_plugin]) end it "returns an empty array when no plugin is found" do expect(subject.all(group: :unknown)).to be_empty end end context "find plugins by their group & name" do it "returns an array of plugins if plugins are found" do expect(subject.all(group: "backend", name: "foobar")) .to match_array [foobar_plugin] end it "returns an empty array when no plugin is found" do expect(subject.all(group: :unknown, name: :'foo-baz')) .to be_empty end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/cli/environments/read_only_spec.rb
spec/lib/guard/cli/environments/read_only_spec.rb
# frozen_string_literal: true require "guard/cli/environments/read_only" RSpec.describe Guard::Cli::Environments::ReadOnly, :stub_ui do include_context "Guard options" before do allow(subject).to receive(:bundler_check) end subject { described_class.new(options) } describe "#evaluate" do let(:evaluator) { instance_double("Guard::Guardfile::Evaluator", evaluate: true) } def evaluate subject.evaluate(evaluator: evaluator) end it "checks Bundler" do expect(subject).to receive(:bundler_check) evaluate end it "evaluates the guardfile" do expect(evaluator).to receive(:evaluate) evaluate end it "passes options to evaluator" do expect(Guard::Guardfile::Evaluator).to receive(:new).with(options).and_return(evaluator) subject.evaluate end [ Guard::Dsl::Error, Guard::Guardfile::Evaluator::NoGuardfileError, Guard::Guardfile::Evaluator::NoCustomGuardfile ].each do |error_class| context "when a #{error_class} error occurs" do before do allow(evaluator).to receive(:evaluate) .and_raise(error_class, "#{error_class} error!") end it "aborts and shows error message" do expect(Guard::UI).to receive(:error).with(/#{error_class} error!/) expect { evaluate }.to raise_error(SystemExit) end end end context "without a valid bundler setup" do before do allow(subject).to receive(:bundler_check).and_raise(SystemExit) end it "does not evaluate the Guardfile" do expect(evaluator).not_to receive(:evaluate) expect { evaluate }.to raise_error(SystemExit) end end end describe "#start" do let(:engine) { instance_double("Guard::Engine") } def start subject.start(engine: engine) end before do allow(engine).to receive(:start).and_return(0) end it "checks Bundler" do expect(subject).to receive(:bundler_check) start end it "start engine with options" do expect(engine).to receive(:start) start end it "returns exit code" do exitcode = double("exitcode") expect(engine).to receive(:start).and_return(exitcode) expect(start).to be(exitcode) end [ Guard::Dsl::Error, Guard::Guardfile::Evaluator::NoGuardfileError, Guard::Guardfile::Evaluator::NoCustomGuardfile ].each do |error_class| context "when a #{error_class} error occurs" do before do allow(engine).to receive(:start) .and_raise(error_class, "#{error_class} error!") end it "aborts" do expect { start }.to raise_error(SystemExit) end it "shows error message" do expect(Guard::UI).to receive(:error).with(/#{error_class} error!/) expect { start }.to raise_error(SystemExit) end end end context "without a valid bundler setup" do before do allow(subject).to receive(:bundler_check).and_raise(SystemExit) end it "does not start engine" do expect(engine).not_to receive(:start) expect { start }.to raise_error(SystemExit) end end describe "return value" do let(:exitcode) { double("Fixnum") } before do allow(engine).to receive(:start).and_return(exitcode) end it "matches return value of Guard.start" do expect(start).to be(exitcode) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/cli/environments/write_spec.rb
spec/lib/guard/cli/environments/write_spec.rb
# frozen_string_literal: true require "guard/cli/environments/write" RSpec.describe Guard::Cli::Environments::Write, :stub_ui do let(:options) { {} } subject { described_class.new(options) } before do allow(subject).to receive(:bundler_check) end describe "#initialize_guardfile" do let(:evaluator) { instance_double("Guard::Guardfile::Evaluator") } let(:generator) { instance_double("Guard::Guardfile::Generator") } def initialize_guardfile(plugin_names = []) subject.initialize_guardfile(plugin_names, evaluator: evaluator, generator: generator) end before do allow(evaluator).to receive(:evaluate) allow(generator).to receive(:create_guardfile) allow(generator).to receive(:initialize_all_templates) end context "with bare option" do let(:options) { { bare: true } } it "only creates the Guardfile without initializing any Guard template" do allow(evaluator).to receive(:evaluate) .and_raise(Guard::Guardfile::Evaluator::NoGuardfileError) expect(generator).to receive(:create_guardfile) expect(generator).not_to receive(:initialize_template) expect(generator).not_to receive(:initialize_all_templates) initialize_guardfile end it "returns an exit code" do expect(initialize_guardfile).to be_zero end end it "evaluates created or existing guardfile" do expect(evaluator).to receive(:evaluate) initialize_guardfile end it "creates a Guardfile" do expect(evaluator).to receive(:evaluate) .and_raise(Guard::Guardfile::Evaluator::NoGuardfileError).once expect(generator).to receive(:create_guardfile) initialize_guardfile end it "initializes templates of all installed Guards" do expect(generator).to receive(:initialize_all_templates) initialize_guardfile end it "initializes each passed template" do expect(generator).to receive(:initialize_template).with("rspec") expect(generator).to receive(:initialize_template).with("pow") initialize_guardfile(%w[rspec pow]) end context "when passed a guard name" do context "when the Guardfile is empty" do before do allow(evaluator).to receive(:evaluate) allow(generator).to receive(:initialize_template) end it "works without without errors" do expect(initialize_guardfile(%w[rspec])).to be_zero end it "adds the template" do expect(generator).to receive(:initialize_template).with("rspec") initialize_guardfile(%w[rspec]) end end it "initializes the template of the passed Guard" do expect(generator).to receive(:initialize_template).with("rspec") initialize_guardfile(%w[rspec]) end end it "returns an exit code" do expect(initialize_guardfile).to be_zero end context "when passed an unknown guard name" do before do expect(generator).to receive(:initialize_template).with("foo") .and_raise(Guard::Guardfile::Generator::NoSuchPlugin, "foo") end it "returns an exit code" do expect(::Guard::UI).to receive(:error).with( "Could not load 'guard/foo' or '~/.guard/templates/foo'"\ " or find class Guard::Foo\n" ) expect(initialize_guardfile(%w[foo])).to be(1) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/cli/environments/base_spec.rb
spec/lib/guard/cli/environments/base_spec.rb
# frozen_string_literal: true require "guard/cli/environments/base" RSpec.describe Guard::Cli::Environments::Base, :stub_ui do let(:no_bundler_warning) { false } let(:options) { { no_bundler_warning: no_bundler_warning } } shared_examples "avoids Bundler warning" do it "does not show the Bundler warning" do expect(Guard::UI).to_not have_received(:info).with(/Guard here!/) end end shared_examples "shows Bundler warning" do it "shows the Bundler warning" do expect(Guard::UI).to have_received(:info).with(/Guard here!/) end end subject { described_class.new(options) } describe "#bundler_check" do let(:gemdeps) { nil } let(:gemfile) { nil } before do allow(ENV).to receive(:[]).with("BUNDLE_GEMFILE").and_return(gemfile) allow(ENV).to receive(:[]).with("RUBYGEMS_GEMDEPS").and_return(gemdeps) allow(File).to receive(:exist?).with("Gemfile") .and_return(gemfile_present) subject.__send__(:bundler_check) end context "without an existing Gemfile" do let(:gemfile_present) { false } include_examples "avoids Bundler warning" end context "with an existing Gemfile" do let(:gemfile_present) { true } context "with Bundler" do let(:gemdeps) { nil } let(:gemfile) { "Gemfile" } include_examples "avoids Bundler warning" end context "without Bundler" do let(:gemfile) { nil } context "with Rubygems Gemfile autodetection or custom Gemfile" do let(:gemdeps) { "-" } include_examples "avoids Bundler warning" end context "without Rubygems Gemfile handling" do let(:gemdeps) { nil } include_examples "shows Bundler warning" context "when options[:no_bundler_warning] == true" do let(:no_bundler_warning) { true } include_examples "avoids Bundler warning" end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/guardfile/result_spec.rb
spec/lib/guard/guardfile/result_spec.rb
# frozen_string_literal: true require "guard/guardfile/result" RSpec.describe Guard::Guardfile::Result, :stub_ui do let(:options) { {} } let(:valid_guardfile_string) { "group :foo; do guard :bar; end; end; " } let(:dsl) { instance_double("Guard::Dsl") } subject { described_class.new } describe "#plugin_names" do it "returns encountered names" do subject.plugins << ["foo", { bar: :baz }] subject.plugins << [:bar, { bar: :baz }] subject.plugins << ["baz", { bar: :baz }] expect(subject.plugin_names).to eq(%i[foo bar baz]) end end describe "#notification" do it "stores notification as a hash" do hash = { foo: :bar } subject.notification.merge!(hash) expect(subject.notification).to eq(hash) end end describe "#interactor" do it "stores interactor as a hash" do hash = { foo: :bar } subject.interactor.merge!(hash) expect(subject.interactor).to eq(hash) end end describe "#groups" do it "defaults to { default: {} }" do expect(subject.groups).to eq(default: {}) end it "stores groups as a hash" do hash = { foo: { opt1: :hello } } subject.groups.merge!(hash) expect(subject.groups).to eq(default: {}, **hash) end end describe "#plugins" do it "stores plugins as a hash" do hash = [:foo, { opt1: :hello }] subject.plugins << hash expect(subject.plugins).to eq([hash]) end end describe "#ignore" do it "stores ignore as a hash" do regex = /foo/ subject.ignore << regex expect(subject.ignore).to eq([regex]) end end describe "#ignore_bang" do it "stores ignore_bang as a hash" do regex = /foo/ subject.ignore_bang << regex expect(subject.ignore_bang).to eq([regex]) end end describe "#logger" do it "stores logger as a hash" do hash = { foo: :bar } subject.logger.merge!(hash) expect(subject.logger).to eq(hash) end end describe "#scopes" do it "stores scopes as a hash" do hash = { foo: :bar } subject.scopes.merge!(hash) expect(subject.scopes).to eq(hash) end end describe "#directories" do it "stores directories as a hash" do string = "foo" subject.directories << string expect(subject.directories).to eq([string]) end end describe "#clearing=" do it "stores clearing as a boolean" do subject.clearing = true expect(subject.clearing).to eq(true) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/guardfile/evaluator_spec.rb
spec/lib/guard/guardfile/evaluator_spec.rb
# frozen_string_literal: true require "guard/guardfile/evaluator" RSpec.describe Guard::Guardfile::Evaluator, :stub_ui do let(:options) { { inline: "guard :dummy" } } let(:plugin_options) { { callbacks: [], group: :default, watchers: [] } } let(:valid_guardfile_string) { "group :foo; do guard :bar; end; end; " } let(:result) { Guard::Guardfile::Result.new } subject { described_class.new(options) } before do stub_user_guard_rb end describe ".evaluate" do describe "error cases" do context "with an invalid Guardfile" do let(:options) { { inline: "guard :foo Bad Guardfile" } } it "displays an error message and raises original exception" do expect { subject.evaluate }.to raise_error(Guard::Dsl::Error) end end context "with no Guardfile at all" do let(:options) { {} } it "displays an error message and exits" do stub_guardfile_rb stub_guardfile stub_user_guardfile stub_user_project_guardfile expect { subject.evaluate } .to raise_error(described_class::NoGuardfileError) end end context "with Guardfile as guardfile.rb" do let(:options) { {} } it "evalutates guardfile.rb" do stub_guardfile_rb("guard :awesome_plugin") expect(subject.evaluate.plugins).to eq([[:awesome_plugin, plugin_options]]) end end context "with a problem reading a Guardfile" do let(:options) { {} } let(:path) { File.expand_path("Guardfile") } before do stub_user_project_guardfile stub_guardfile_rb stub_guardfile(" ") do fail Errno::EACCES.new("permission error") end end it "displays an error message and exits" do expect(Guard::UI).to receive(:error).with(/^Error reading file/) expect { subject.evaluate }.to raise_error(SystemExit) end end context "when provided :inline is nil" do let(:options) { { inline: nil } } before do stub_guardfile("guard :awesome_plugin") stub_guardfile_rb end it "does not raise error and skip it" do expect(Guard::UI).to_not receive(:error) expect do expect(subject.evaluate.plugins).to eq([[:awesome_plugin, plugin_options]]) end.to_not raise_error end end context "with a non-existing Guardfile given" do let(:non_existing_path) { "/non/existing/path/to/Guardfile" } let(:options) { { guardfile: non_existing_path } } before do stub_file(non_existing_path) end it "raises error" do expect { subject.evaluate } .to raise_error(described_class::NoCustomGuardfile) end end end describe "selection of the Guardfile data contents" do context "with a valid :contents option" do context "with inline content and other Guardfiles available" do let(:inline_code) { "guard :awesome_plugin" } let(:options) do { inline: inline_code, guardfile: "/abc/Guardfile" } end before do stub_file("/abc/Guardfile", "guard :bar") stub_guardfile_rb("guard :baz") stub_guardfile("guard :baz") stub_user_guardfile("guard :buz") end it "gives ultimate precedence to inline content" do expect(subject.evaluate.plugins).to eq([[:awesome_plugin, plugin_options]]) end end end context "with the :guardfile option" do let(:options) { { guardfile: "../relative_path_to_Guardfile" } } before do stub_file(File.expand_path(options[:guardfile]), valid_guardfile_string) expect(dsl).to receive(:evaluate) .with(valid_guardfile_string, anything, 1) end end end end describe "#inline?" do context "when no content is provided" do let(:options) { {} } it { is_expected.to_not be_inline } end context "when guardfile_contents is provided" do let(:options) { { inline: "guard :dummy" } } it { is_expected.to be_inline } end end describe ".guardfile_include?" do context "when plugin is present" do it "returns true" do expect(subject).to be_guardfile_include("dummy") end end context "when plugin is not present" do let(:options) { { inline: "guard :other" } } it "returns false" do expect(subject).not_to be_guardfile_include("test") end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/guardfile/generator_spec.rb
spec/lib/guard/guardfile/generator_spec.rb
# frozen_string_literal: true require "guard/guardfile/generator" RSpec.describe Guard::Guardfile::Generator, :stub_ui do let(:plugin_util) { instance_double("Guard::PluginUtil") } it "has a valid Guardfile template" do allow(File).to receive(:exist?) .with(described_class::GUARDFILE_TEMPLATE).and_call_original expect(File.exist?(described_class::GUARDFILE_TEMPLATE)).to be_truthy end describe "#create_guardfile" do context "with an existing Guardfile" do before do stub_guardfile("foo") end it "does not copy the Guardfile template or notify the user" do expect(::Guard::UI).to_not receive(:info) expect(FileUtils).to_not receive(:cp) begin subject.create_guardfile rescue SystemExit end end it "does not display information" do expect(::Guard::UI).to_not receive(:info) begin subject.create_guardfile rescue SystemExit end end it "displays an error message" do expect(::Guard::UI).to receive(:error) .with("Guardfile already exists at Guardfile") begin subject.create_guardfile rescue SystemExit end end it "aborts" do expect { subject.create_guardfile }.to raise_error(SystemExit) end end context "without an existing Guardfile" do before do stub_guardfile allow(FileUtils).to receive(:cp) end it "does not display any kind of error or abort" do expect(::Guard::UI).to_not receive(:error) expect(described_class).to_not receive(:abort) subject.create_guardfile end it "copies the Guardfile template and notifies the user" do expect(::Guard::UI).to receive(:info) expect(FileUtils).to receive(:cp) subject.create_guardfile end end end describe "#initialize_template" do before do @guardfile = stub_guardfile end context "with an installed Guard implementation" do before do expect(Guard::PluginUtil).to receive(:new) { plugin_util } expect(plugin_util).to receive(:valid?).and_return(true) end it "initializes the plugin" do expect(plugin_util).to receive(:add_to_guardfile).and_return(true) subject.initialize_template("foo") end context "with a non-existing template" do it "initializes the plugin" do expect(plugin_util).to receive(:add_to_guardfile).and_raise(Errno::ENOENT) expect(plugin_util).to receive(:plugin_class).and_return("Guard::Foo") expect(::Guard::UI).to receive(:error) .with("Found class Guard::Foo but loading its template failed.") subject.initialize_template("foo") end end end context "with a user defined template" do let(:template) { File.join(described_class::HOME_TEMPLATES, "/bar") } let(:template_content) { "Template content" } before do stub_file("bar") stub_file(File.expand_path("~/.guard/templates/bar"), "Template content") end it "copies the Guardfile template and initializes the Guard" do expect(@guardfile).to receive(:binwrite) .with("\n#{template_content}\n", open_args: ["a"]) expect(plugin_util).to receive(:valid?).and_return(false) expect(Guard::PluginUtil).to receive(:new).with("bar") .and_return(plugin_util) subject.initialize_template("bar") end end context "when the passed plugin can't be found" do before do expect(::Guard::PluginUtil).to receive(:new) { plugin_util } allow(plugin_util).to receive(:valid?).and_return(false) stub_file("foo") stub_file(File.expand_path("~/.guard/templates/foo")) end it "notifies the user about the problem" do expect { subject.initialize_template("foo") } .to raise_error(Guard::Guardfile::Generator::NoSuchPlugin) end end end describe "#initialize_all_templates" do let(:plugins) { %w[rspec spork phpunit] } before do expect(::Guard::PluginUtil).to receive(:plugin_names) { plugins } end it "calls #initialize_template on all installed plugins" do plugins.each do |g| expect(subject).to receive(:initialize_template).with(g) end subject.initialize_all_templates end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/ui/logger_config_spec.rb
spec/lib/guard/ui/logger_config_spec.rb
# frozen_string_literal: true require "guard/ui/logger_config" RSpec.describe Guard::UI::LoggerConfig do describe "defaults" do it "flushes device by default" do expect(subject[:flush_seconds]).to eq(0) end end describe "#level=" do context "with a valid value" do before do subject.level = ::Logger::WARN end it "stores the level" do expect(subject[:level]).to eq(::Logger::WARN) expect(subject["level"]).to eq(::Logger::WARN) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/ui/config_spec.rb
spec/lib/guard/ui/config_spec.rb
# frozen_string_literal: true require "guard/ui/config" RSpec.describe Guard::UI::Config do describe "#device" do context "when not set" do context "when accessed as a method" do it "returns $stderr" do expect(subject.device).to be($stderr) end end context "when accessed as a string" do it "returns $stderr" do expect(subject["device"]).to be($stderr) end end context "when accessed as a symbol" do it "returns $stderr" do expect(subject[:device]).to be($stderr) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard.rb
lib/guard.rb
# frozen_string_literal: true # Guard plugins should use this namespace. module Guard end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/tasks/releaser.rb
lib/tasks/releaser.rb
# frozen_string_literal: true # TODO: extract to gem? # @private class Releaser def initialize(options = {}) @project_name = options.delete(:project_name) do fail "project_name is needed!" end @gem_name = options.delete(:gem_name) do fail "gem_name is needed!" end @github_repo = options.delete(:github_repo) do fail "github_repo is needed!" end @version = options.delete(:version) do fail "version is needed!" end end def full rubygems github end def rubygems input = nil loop do STDOUT.puts "Release #{@project_name} #{@version} to RubyGems? (y/n)" input = STDIN.gets.chomp.downcase break if %w(y n).include?(input) end exit if input == "n" Rake::Task["release"].invoke end def github tag_name = "v#{@version}" require "gems" _verify_released _verify_tag_pushed require "octokit" gh_client = Octokit::Client.new(netrc: true) gh_release = _detect_gh_release(gh_client, tag_name, true) return unless gh_release STDOUT.puts "Draft release for #{tag_name}:\n" STDOUT.puts gh_release.body STDOUT.puts "\n-------------------------\n\n" _confirm_publish return unless _update_release(gh_client, gh_release, tag_name) gh_release = _detect_gh_release(gh_client, tag_name, false) _success_summary(gh_release, tag_name) end private def _verify_released if @version != Gems.info(@gem_name)["version"] STDOUT.puts "#{@project_name} #{@version} is not yet released." STDOUT.puts "Please release it first with: rake release:gem" exit end end def _verify_tag_pushed tags = `git ls-remote --tags origin`.split("\n") return if tags.detect { |tag| tag =~ /v#{@version}$/ } STDOUT.puts "The tag v#{@version} has not yet been pushed." STDOUT.puts "Please push it first with: rake release:gem" exit end def _success_summary(gh_release, tag_name) href = gh_release.rels[:html].href STDOUT.puts "GitHub release #{tag_name} has been published!" STDOUT.puts "\nPlease enjoy and spread the word!" STDOUT.puts "Lack of inspiration? Here's a tweet you could improve:\n\n" STDOUT.puts "Just released #{@project_name} #{@version}! #{href}" end def _detect_gh_release(gh_client, tag_name, draft) gh_releases = gh_client.releases(@github_repo) gh_releases.detect { |r| r.tag_name == tag_name && r.draft == draft } end def _confirm_publish input = nil loop do STDOUT.puts "Would you like to publish this GitHub release now? (y/n)" input = STDIN.gets.chomp.downcase break if %w(y n).include?(input) end exit if input == "n" end def _update_release(gh_client, gh_release, tag_name) result = gh_client.update_release(gh_release.rels[:self].href, draft: false) return true if result STDOUT.puts "GitHub release #{tag_name} couldn't be published!" false end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/watcher.rb
lib/guard/watcher.rb
# frozen_string_literal: true require "guard/ui" require "guard/watcher/pattern" require "guard/watcher/pattern/match_result" module Guard # The watcher defines a RegExp that will be matched against file system # modifications. # When a watcher matches a change, an optional action block is executed to # enable processing the file system change result. # class Watcher attr_accessor :pattern, :action # Initializes a file watcher. # # @param [String, Regexp] pattern the pattern to be watched by the Guard # plugin # @param [Block] action the action to execute before passing the result to # the Guard plugin # def initialize(pattern, action = nil) @action = action @pattern = Pattern.create(pattern) end # Compare with other watcher # @param other [Guard::Watcher] other watcher for comparing # @return [true, false] equal or not def ==(other) action == other.action && pattern == other.pattern end # Finds the files that matches a Guard plugin. # # @param [Guard::Plugin] guard the Guard plugin which watchers are used # @param [Array<String>] files the changed files # @return [Array<Object>] the matched watcher response # def self.match_files(guard, files) return [] if files.empty? files.inject([]) do |paths, file| guard.watchers.each do |watcher| matches = watcher.match(file) next(paths) unless matches if watcher.action result = watcher.call_action(matches) if guard.options[:any_return] paths << result elsif result.respond_to?(:empty?) && !result.empty? paths << Array(result) else next(paths) end else paths << matches[0] end break if guard.options[:first_match] end guard.options[:any_return] ? paths : paths.flatten.map(&:to_s) end end def match(string_or_pathname) m = pattern.match(string_or_pathname) m ? Pattern::MatchResult.new(m, string_or_pathname) : nil end # @private # Executes a watcher action. # # @param [String, MatchData] matches the matched path or the match from the # Regex # @return [String] the final paths # def call_action(matches) @action.arity.positive? ? @action.call(matches) : @action.call rescue StandardError => e UI.error "Problem with watch action!\n#{e.message}" UI.error e.backtrace.join("\n") end def to_s pattern end alias_method :inspect, :to_s end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/version.rb
lib/guard/version.rb
# frozen_string_literal: true module Guard VERSION = "3.0.0-rc1" end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/ui.rb
lib/guard/ui.rb
# frozen_string_literal: true require "guard/ui/colors" require "guard/ui/config" require "guard/ui/logger_config" require "guard/terminal" require "forwardable" # TODO: rework this class from the bottom-up # - remove dependency on Session # - extract into a separate gem # - change UI to class module Guard # The UI class helps to format messages for the user. Everything that is # logged through this class is considered either as an error message or a # diagnostic message and is written to standard error ($stderr). # # If your Guard plugin does some output that is piped into another process # for further processing, please just write it to STDOUT with `puts`. # module UI include Colors class << self # @private # Get the Guard::UI logger instance # def logger @logger ||= begin require "lumberjack" Lumberjack::Logger.new(options.device, logger_config) end end # @private # Since logger is global, for Aruba in-process to properly # separate output between calls, we need to reset # # We don't use logger=() since it's expected to be a Lumberjack instance def reset @options = nil @logger_config = nil @logger = nil end # @private # Get the logger options # # @return [Hash] the logger options # def options @options ||= Config.new end # Set the logger options # # @param [Hash] options the logger options # @option options [Symbol] level the log level # @option options [String] template the logger template # @option options [String] time_format the time format # def options=(options) @options = Config.new(options) end # @private def logger_config @logger_config ||= LoggerConfig.new end # @private # Assigns a logger template def template=(new_template) logger_config.template = new_template @logger.template = new_template if @logger end # @private # Assigns a log level def level=(new_level) logger_config.level = new_level @logger.level = new_level if @logger end # Show an info message. # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before # @option options [String] plugin manually define the calling plugin # def info(message, options = {}) _filtered_logger_message(message, :info, nil, options) end # Show a yellow warning message that is prefixed with WARNING. # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before # @option options [String] plugin manually define the calling plugin # def warning(message, options = {}) _filtered_logger_message(message, :warn, :yellow, options) end # Show a red error message that is prefixed with ERROR. # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before # @option options [String] plugin manually define the calling plugin # def error(message, options = {}) _filtered_logger_message(message, :error, :red, options) end # Show a red deprecation message that is prefixed with DEPRECATION. # It has a log level of `warn`. # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before # @option options [String] plugin manually define the calling plugin # def deprecation(message, options = {}) unless ENV["GUARD_GEM_SILENCE_DEPRECATIONS"] == "1" backtrace = Thread.current.backtrace[1..5].join("\n\t >") msg = format("%<message>s\nDeprecation backtrace: %<backtrace>s", message: message, backtrace: backtrace) warning(msg, options) end end # Show a debug message that is prefixed with DEBUG and a timestamp. # # @param [String] message the message to show # @option options [Boolean] reset whether to clean the output before # @option options [String] plugin manually define the calling plugin # def debug(message, options = {}) _filtered_logger_message(message, :debug, :yellow, options) end # Reset a line. # def reset_line $stderr.print(color_enabled? ? "\r\e[0m" : "\r\n") end # @private def engine Thread.current[:engine] end # Clear the output if clearable. # def clear(opts = {}) return unless engine return unless engine.session.clear? fail "UI not set up!" if clearable.nil? return unless clearable || opts[:force] @clearable = false Terminal.clear rescue Errno::ENOENT => e warning("Failed to clear the screen: #{e.inspect}") end # @private api def reset_and_clear @clearable = false clear(force: true) end # Allow the screen to be cleared again. # def clearable! @clearable = true end # Show a scoped action message. # # @param [String] action the action to show # @param [Hash] scope hash with a guard or a group scope # def action_with_scopes(action, titles) info "#{action} #{titles.join(', ')}" end private attr_accessor :clearable # Filters log messages depending on either the # `:only`` or `:except` option. # # @param [String] plugin the calling plugin name # @yield When the message should be logged # @yieldparam [String] param the calling plugin name # def _filter(plugin) only = options.only except = options.except plugin ||= _calling_plugin_name match = !(only || except) match ||= only&.match(plugin) match ||= (except && !except.match(plugin)) return unless match yield plugin end # @private def _filtered_logger_message(message, method, color_name, options = {}) message = color(message, color_name) if color_name _filter(options[:plugin]) do reset_line if options[:reset] logger.send(method, message) end end # Tries to extract the calling Guard plugin name # from the call stack. # # @param [Integer] depth the stack depth # @return [String] the Guard plugin name # def _calling_plugin_name name = caller.lazy.map do |line| %r{(?<!guard\/lib)\/(guard\/[a-z_]*)(/[a-z_]*)?.rb:}i.match(line) end.reject(&:nil?).take(1).force.first return "Guard" unless name || (name && name[1] == "guard/lib") name[1].split("/").map do |part| part.split(/[^a-z0-9]/i).map(&:capitalize).join end.join("::") end # Checks if color output can be enabled. # # @return [Boolean] whether color is enabled or not # def color_enabled? @color_enabled_initialized ||= false @color_enabled = nil unless @color_enabled_initialized @color_enabled_initialized = true return @color_enabled unless @color_enabled.nil? return (@color_enabled = true) unless Gem.win_platform? return (@color_enabled = true) if ENV["ANSICON"] @color_enabled = begin require "rubygems" unless ENV["NO_RUBYGEMS"] require "Win32/Console/ANSI" true rescue LoadError info "Run 'gem install win32console' to use color on Windows" false end end # Colorizes a text message. See the constant in the UI class for possible # color_options parameters. You can pass optionally :bright, a foreground # color and a background color. # # @example # # color('Hello World', :red, :bright) # # @param [String] text the text to colorize # @param [Array] color_options the color options # def color(text, *color_options) color_code = "" color_options.each do |color_option| color_option = color_option.to_s next if color_option == "" unless color_option.match?(/\d+/) color_option = const_get("ANSI_ESCAPE_#{color_option.upcase}") end color_code += ";" + color_option end color_enabled? ? "\e[0#{color_code}m#{text}\e[0m" : text end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/group.rb
lib/guard/group.rb
# frozen_string_literal: true module Guard # A group of Guard plugins. There are two reasons why you want to group your # Guard plugins: # # * You can start only certain groups from the command line by passing the # `--group` option to `guard start`. # * Abort task execution chain on failure within a group with the # `:halt_on_fail` option. # # @example Group that aborts on failure # # group :frontend, halt_on_fail: true do # guard 'coffeescript', input: 'spec/coffeescripts', # output: 'spec/javascripts' # guard 'jasmine-headless-webkit' do # watch(%r{^spec/javascripts/(.*)\..*}) do |m| # newest_js_file("spec/javascripts/#{m[1]}_spec") # end # end # end # # @see Guard::CLI # class Group attr_accessor :name, :options # @private # Initializes a Group. # # @param [String] name the name of the group # @param [Hash] options the group options # @option options [Boolean] halt_on_fail if a task execution # should be halted for all Guard plugins in this group if a Guard plugin # throws `:task_has_failed` # def initialize(name, options = {}) @name = name.to_sym @options = options end # Returns the group title. # # @example Title for a group named 'backend' # > Guard::Group.new('backend').title # => "Backend" # # @return [String] # def title @title ||= name.to_s.capitalize end # String representation of the group. # # @example String representation of a group named 'backend' # > Guard::Group.new('backend').to_s # => "#<Guard::Group @name=backend @options={}>" # # @return [String] the string representation # def to_s "#<#{self.class} @name=#{name} @options=#{options}>" end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/options.rb
lib/guard/options.rb
# frozen_string_literal: true require "thor/core_ext/hash_with_indifferent_access" module Guard # @private # A class that holds options. Can be instantiated with default options. # class Options < Thor::CoreExt::HashWithIndifferentAccess # Initializes an Guard::Options object. `default_opts` is merged into # `opts`. # # @param [Hash] opts the options # @param [Hash] default_opts the default options # def initialize(opts = {}, default_opts = {}) super(default_opts.merge(opts || {})) end # workaround for: https://github.com/erikhuda/thor/issues/504 def fetch(name) super(name.to_s) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/dsl_describer.rb
lib/guard/dsl_describer.rb
# frozen_string_literal: true require "formatador" require "guard/ui" require "guard/notifier" require "guard/plugin_util" require "set" module Guard # @private # The DslDescriber evaluates the Guardfile and creates an internal structure # of it that is used in some inspection utility methods like the CLI commands # `show` and `list`. # # @see Guard::Dsl # @see Guard::CLI # class DslDescriber def initialize(guardfile_result) @guardfile_result = guardfile_result end # List the Guard plugins that are available for use in your system and marks # those that are currently used in your `Guardfile`. # # @see CLI#list # def list # collect metadata data = PluginUtil.plugin_names.sort.each_with_object({}) do |name, hash| hash[name.capitalize] = guardfile_result.plugin_names.include?(name.to_sym) end # presentation header = %i(Plugin Guardfile) final_rows = [] data.each do |name, used| final_rows << { Plugin: name, Guardfile: used ? "✔" : "✘" } end # render Formatador.display_compact_table(final_rows, header) end # Shows all Guard plugins and their options that are defined in # the `Guardfile`. # # @see CLI#show # def show objects = [] empty_plugin = ["", { "" => nil }] guardfile_result.groups.each do |group_name, options| plugins = guardfile_result.plugins.select { |plugin| plugin.last[:group] == group_name } plugins = [empty_plugin] if plugins.empty? plugins.each do |plugin| plugin_name, options = plugin options.delete(:group) options = empty_plugin.last if options.empty? options.each do |option, value| objects << [group_name, plugin_name, option.to_s, value&.inspect] end end end # presentation rows = [] prev_group = prev_plugin = prev_option = prev_value = nil objects.each do |group, plugin, option, value| group_changed = prev_group != group plugin_changed = (prev_plugin != plugin || group_changed) rows << :split if group_changed || plugin_changed rows << { Group: group_changed ? group : "", Plugin: plugin_changed ? plugin : "", Option: option, Value: value } prev_group = group prev_plugin = plugin prev_option = option prev_value = value end # render Formatador.display_compact_table( rows.drop(1), %i(Group Plugin Option Value) ) end # Shows all notifiers and their options that are defined in # the `Guardfile`. # # @see CLI#show # def notifiers supported = Notifier.supported Notifier.connect(notify: true, silent: true) detected = Notifier.detected Notifier.disconnect detected_names = detected.map { |item| item[:name] } final_rows = supported.each_with_object([]) do |(name, _), rows| available = detected_names.include?(name) ? "✔" : "✘" notifier = detected.detect { |n| n[:name] == name } used = notifier ? "✔" : "✘" options = notifier ? notifier[:options] : {} if options.empty? rows << :split _add_row(rows, name, available, used, "", "") else options.each_with_index do |(option, value), index| if index.zero? rows << :split _add_row(rows, name, available, used, option.to_s, value.inspect) else _add_row(rows, "", "", "", option.to_s, value.inspect) end end end rows end Formatador.display_compact_table( final_rows.drop(1), %i(Name Available Used Option Value) ) end private attr_reader :guardfile_result def _add_row(rows, name, available, used, option, value) rows << { Name: name, Available: available, Used: used, Option: option, Value: value } end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/plugin.rb
lib/guard/plugin.rb
# frozen_string_literal: true require "guard/internals/groups" require "guard/ui" module Guard # Base class from which every Guard plugin implementation must inherit. # # Guard will trigger the {#start}, {#stop}, {#reload}, {#run_all} and # {#run_on_changes} ({#run_on_additions}, {#run_on_modifications} and # {#run_on_removals}) task methods depending on user interaction and file # modification. # # {#run_on_changes} could be implemented to handle all the changes task case # (additions, modifications, removals) in once, or each task can be # implemented separately with a specific behavior. # # In each of these Guard task methods you have to implement some work when # you want to support this kind of task. The return value of each Guard task # method is not evaluated by Guard, but it'll be passed to the "_end" hook # for further evaluation. You can throw `:task_has_failed` to indicate that # your Guard plugin method was not successful, and successive Guard plugin # tasks will be aborted when the group has set the `:halt_on_fail` option. # # @see Guard::Group # # @example Throw :task_has_failed # # def run_all # unless run_all_tasks # throw :task_has_failed # end # end # # Each Guard plugin should provide a template Guardfile located within the Gem # at `lib/guard/guard-name/templates/Guardfile`. # # Watchers for a Guard plugin should return a file path or an array of files # paths to Guard, but if your Guard plugin wants to allow any return value # from a watcher, you can set the `any_return` option to true. # # If one of those methods raises an exception other than `:task_has_failed`, # the `Guard::GuardName` instance will be removed from the active Guard # plugins. # class Plugin TEMPLATE_FORMAT = "%s/lib/guard/%s/templates/Guardfile" # Error raised when no engine is given. NoEngineGiven = Class.new(StandardError) require "guard/ui" # @private # Get all callbacks registered for all Guard plugins present in the # Guardfile. # def self.callbacks @callbacks ||= Hash.new { |hash, key| hash[key] = [] } end # @private # Add a callback. # # @param [Block] listener the listener to notify # @param [Guard::Plugin] guard_plugin the Guard plugin to add the callback # @param [Array<Symbol>] events the events to register # def self.add_callback(listener, guard_plugin, events) Array(events).each do |event| callbacks[[guard_plugin, event]] << listener end end # @private # Notify a callback. # # @param [Guard::Plugin] guard_plugin the Guard plugin to add the callback # @param [Symbol] event the event to trigger # @param [Array] args the arguments for the listener # def self.notify(guard_plugin, event, *args) callbacks[[guard_plugin, event]].each do |listener| listener.call(guard_plugin, event, *args) end end # When event is a Symbol, {#hook} will generate a hook name # by concatenating the method name from where {#hook} is called # with the given Symbol. # # @example Add a hook with a Symbol # # def run_all # hook :foo # end # # Here, when {Guard::Plugin#run_all} is called, {#hook} will notify # callbacks registered for the "run_all_foo" event. # # When event is a String, {#hook} will directly turn the String # into a Symbol. # # @example Add a hook with a String # # def run_all # hook "foo_bar" # end # # When {Guard::Plugin::run_all} is called, {#hook} will notify # callbacks registered for the "foo_bar" event. # # @param [Symbol, String] event the name of the Guard event # @param [Array] args the parameters are passed as is to the callbacks # registered for the given event. # def hook(event, *args) hook_name = if event.is_a? Symbol calling_method = caller(1..1).first[/`([^']*)'/, 1] "#{calling_method}_#{event}" else event end UI.debug "Hook :#{hook_name} executed for #{self.class}" self.class.notify(self, hook_name.to_sym, *args) end attr_accessor :group, :watchers, :callbacks, :options # @return [Guard::Group] # # @!method group # @return [Array<Guard::Watcher>] # # @!method watchers # @return [Hash] # # @!method callbacks # @return [Hash] # # @!method options # @private # Returns the non-namespaced class name of the plugin # # # @example Non-namespaced class name for Guard::RSpec # Guard::RSpec.non_namespaced_classname # #=> "RSpec" # # @return [String] # def self.non_namespaced_classname to_s.sub("Guard::", "") end # @private # Returns the non-namespaced name of the plugin # # # @example Non-namespaced name for Guard::RSpec # Guard::RSpec.non_namespaced_name # #=> "rspec" # # @return [String] # def self.non_namespaced_name non_namespaced_classname.downcase end # @private # Specify the source for the Guardfile template. # Each Guard plugin can redefine this method to add its own logic. # # @param [String] plugin_location the plugin location # def self.template(plugin_location) File.read(format(TEMPLATE_FORMAT, plugin_location, non_namespaced_name)) end # Called once when Guard starts. Please override initialize method to # init stuff. # # @raise [:task_has_failed] when start has failed # @return [Object] the task result # # @!method start # Called when `stop|quit|exit|s|q|e + enter` is pressed (when Guard # quits). # # @raise [:task_has_failed] when stop has failed # @return [Object] the task result # # @!method stop # Called when `reload|r|z + enter` is pressed. # This method should be mainly used for "reload" (really!) actions like # reloading passenger/spork/bundler/... # # @raise [:task_has_failed] when reload has failed # @return [Object] the task result # # @!method reload # Called when just `enter` is pressed # This method should be principally used for long action like running all # specs/tests/... # # @raise [:task_has_failed] when run_all has failed # @return [Object] the task result # # @!method run_all # Default behaviour on file(s) changes that the Guard plugin watches. # # @param [Array<String>] paths the changes files or paths # @raise [:task_has_failed] when run_on_changes has failed # @return [Object] the task result # # @!method run_on_changes(paths) # Called on file(s) additions that the Guard plugin watches. # # @param [Array<String>] paths the changes files or paths # @raise [:task_has_failed] when run_on_additions has failed # @return [Object] the task result # # @!method run_on_additions(paths) # Called on file(s) modifications that the Guard plugin watches. # # @param [Array<String>] paths the changes files or paths # @raise [:task_has_failed] when run_on_modifications has failed # @return [Object] the task result # # @!method run_on_modifications(paths) # Called on file(s) removals that the Guard plugin watches. # # @param [Array<String>] paths the changes files or paths # @raise [:task_has_failed] when run_on_removals has failed # @return [Object] the task result # # @!method run_on_removals(paths) # Returns the plugin's name (without "guard-"). # # @example Name for Guard::RSpec # Guard::RSpec.new.name # #=> "rspec" # # @return [String] # def name @name ||= self.class.non_namespaced_name end # Returns the plugin's class name without the Guard:: namespace. # # @example Title for Guard::RSpec # Guard::RSpec.new.title # #=> "RSpec" # # @return [String] # def title @title ||= self.class.non_namespaced_classname end # String representation of the plugin. # # @example String representation of an instance of the Guard::RSpec plugin # # Guard::RSpec.new.to_s # #=> "#<Guard::RSpec @name=rspec @group=#<Guard::Group @name=default # @options={}> @watchers=[] @callbacks=[] @options={ all_after_pass: true }>" # # @return [String] the string representation # def to_s "#<#{self.class}:#{object_id} @name=#{name} @group=#{group} @watchers=#{watchers}"\ " @callbacks=#{callbacks} @options=#{options}>" end alias_method :inspect, :to_s private # Initializes a Guard plugin. # Don't do any work here, especially as Guard plugins get initialized even # if they are not in an active group! # # @param [Hash] options the Guard plugin options # @option options [Array<Guard::Watcher>] watchers the Guard plugin file # watchers # @option options [Symbol] group the group this Guard plugin belongs to # @option options [Boolean] any_return allow any object to be returned from # a watcher # def initialize(options = {}) @options = options @group = options.delete(:group) @watchers = options.delete(:watchers) { [] } @callbacks = options.delete(:callbacks) { [] } _register_callbacks end # Add all the Guard::Plugin's callbacks to the global @callbacks array # that's used by Guard to know which callbacks to notify. # def _register_callbacks callbacks.each do |callback| self.class.add_callback(callback[:listener], self, callback[:events]) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/plugin_util.rb
lib/guard/plugin_util.rb
# frozen_string_literal: true require "guard/guardfile/evaluator" require "guard/plugin" require "guard/ui" module Guard # @private # This class contains useful methods to: # # * Fetch all the Guard plugins names; # * Initialize a plugin, get its location; # * Return its class name; # * Add its template to the Guardfile. # class PluginUtil ERROR_NO_GUARD_OR_CLASS = "Could not load 'guard/%s' or" \ " find class Guard::%s" INFO_ADDED_GUARD_TO_GUARDFILE = "%s guard added to Guardfile,"\ " feel free to edit it" attr_accessor :name # Returns a list of Guard plugin Gem names installed locally. # # @return [Array<String>] a list of Guard plugin gem names # def self.plugin_names valid = Gem::Specification.find_all.select do |gem| _gem_valid?(gem) end valid.map { |x| x.name.sub(/^guard-/, "") }.uniq end # Initializes a new `Guard::PluginUtil` object. # # @param [String] name the name of the Guard plugin # def initialize(name, evaluator: Guardfile::Evaluator.new) @name = name.to_s.sub(/^guard-/, "") @evaluator = evaluator end # Initializes a new `Guard::Plugin` with the given `options` hash. This # methods handles plugins that inherit from `Guard::Plugin`. # # @see Guard::Plugin # # @return [Guard::Plugin] the initialized plugin # def initialize_plugin(options) klass = plugin_class fail "Could not load class: #{_constant_name.inspect}" unless klass klass.new(options) rescue ArgumentError => e fail "Failed to call #{klass}.new(options): #{e}" end # Locates a path to a Guard plugin gem. # # @return [String] the full path to the plugin gem # def plugin_location @plugin_location ||= _full_gem_path("guard-#{name}") rescue Gem::LoadError UI.error "Could not find 'guard-#{name}' gem path." end # Tries to load the Guard plugin main class. This transforms the supplied # plugin name into a class name: # # * `guardname` will become `Guard::Guardname` # * `dashed-guard-name` will become `Guard::DashedGuardName` # * `underscore_guard_name` will become `Guard::UnderscoreGuardName` # # When no class is found with the strict case sensitive rules, another # try is made to locate the class without matching case: # # * `rspec` will find a class `Guard::RSpec` # # @return [Class, nil] the loaded class # def plugin_class const = _plugin_constant fail TypeError, "no constant: #{_constant_name}" unless const @plugin_class ||= Guard.const_get(const) rescue TypeError begin require "guard/#{name.downcase}" const = _plugin_constant @plugin_class ||= Guard.const_get(const) rescue TypeError, LoadError => e UI.error(format(ERROR_NO_GUARD_OR_CLASS, name.downcase, _constant_name)) raise e end end # @private def valid? plugin_class true rescue TypeError, LoadError false end # Adds a plugin's template to the Guardfile. # def add_to_guardfile if evaluator.guardfile_include?(name) UI.info "Guardfile already includes #{name} guard" else content = File.read("Guardfile") File.open("Guardfile", "wb") do |f| f.puts(content) f.puts("") f.puts(plugin_class.template(plugin_location)) end UI.info INFO_ADDED_GUARD_TO_GUARDFILE % name end end private attr_reader :evaluator # Returns the constant for the current plugin. # # @example Returns the constant for a plugin # > Guard::PluginUtil.new('rspec').send(:_plugin_constant) # => Guard::RSpec # def _plugin_constant @_plugin_constant ||= Guard.constants.detect do |c| c.to_s.casecmp(_constant_name.downcase).zero? end end # Guesses the most probable name for the current plugin based on its name. # # @example Returns the most probable name for a plugin # > Guard::PluginUtil.new('rspec').send(:_constant_name) # => "Rspec" # def _constant_name @_constant_name ||= name.gsub(%r{/(.?)}) { "::#{$1.upcase}" } .gsub(/(?:^|[_-])(.)/) { $1.upcase } end def _full_gem_path(name) Gem::Specification.find_by_name(name).full_gem_path end class << self def _gem_valid?(gem) return false if gem.name == "guard-compat" return true if gem.name =~ /^guard-/ full_path = gem.full_gem_path file = File.join(full_path, "lib", "guard", "#{gem.name}.rb") File.exist?(file) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/rake_task.rb
lib/guard/rake_task.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "rake" require "rake/tasklib" require "guard/cli" module Guard # Provides a method to define a Rake task that # runs the Guard plugins. # class RakeTask < ::Rake::TaskLib # Name of the main, top level task attr_accessor :name # CLI options attr_accessor :options # Initialize the Rake task # # @param [Symbol] name the name of the Rake task # @param [String] options the CLI options # @yield [Guard::RakeTask] the task # def initialize(name = :guard, options = "") @name = name @options = options yield self if block_given? desc "Starts Guard with options: '#{options}'" task name => ["#{name}:start"] namespace(name) do desc "Starts Guard with options: '#{options}'" task(:start) do ::Guard::CLI.start(options.split) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/dsl.rb
lib/guard/dsl.rb
# frozen_string_literal: true require "guard/guardfile/result" require "guard/ui" require "guard/watcher" module Guard # @private # The Dsl class provides the methods that are used in each `Guardfile` to # describe the behaviour of Guard. # # The main keywords of the DSL are {#guard} and {#watch}. These are necessary # to define the used Guard plugins and the file changes they are watching. # # You can optionally group the Guard plugins with the {#group} keyword and # ignore and filter certain paths with the {#ignore} and {#filter} keywords. # # You can set your preferred system notification library with {#notification} # and pass some optional configuration options for the library. If you don't # configure a library, Guard will automatically pick one with default options # (if you don't want notifications, specify `:off` as library). Please see # {Notifier} for more information about the supported libraries. # # A more advanced DSL use is the {#callback} keyword that allows you to # execute arbitrary code before or after any of the {Plugin#start}, # {Plugin#stop}, {Plugin#reload}, {Plugin#run_all}, # {Plugin#run_on_changes}, {Plugin#run_on_additions}, # {Plugin#run_on_modifications} and {Plugin#run_on_removals} # Guard plugins method. # You can even insert more hooks inside these methods. Please [checkout the # Wiki page](https://github.com/guard/guard/wiki/Hooks-and-callbacks) for # more details. # # The DSL will also evaluate normal Ruby code. # # There are two possible locations for the `Guardfile`: # # * The `Guardfile` or `guardfile.rb` in the current directory where Guard # has been started # * The `.Guardfile` in your home directory. # # In addition, if a user configuration `.guard.rb` in your home directory is # found, it will be appended to the current project `Guardfile`. # # @see https://github.com/guard/guard/wiki/Guardfile-examples # class Dsl WARN_INVALID_LOG_LEVEL = "Invalid log level `%s` ignored. "\ "Please use either :debug, :info, :warn or :error." WARN_INVALID_LOG_OPTIONS = "You cannot specify the logger options"\ " :only and :except at the same time." Error = Class.new(RuntimeError) attr_reader :result def initialize @result = Guard::Guardfile::Result.new end def evaluate(contents, filename, lineno) instance_eval(contents, filename.to_s, lineno) rescue StandardError, ScriptError => e prefix = "\n\t(dsl)> " cleaned_backtrace = self.class.cleanup_backtrace(e.backtrace) backtrace = "#{prefix}#{cleaned_backtrace.join(prefix)}" msg = "Invalid Guardfile, original error is: \n\n%s, \nbacktrace: %s" raise Error, format(msg, e, backtrace) end # Set notification options for the system notifications. # You can set multiple notifications, which allows you to show local # system notifications and remote notifications with separate libraries. # You can also pass `:off` as library to turn off notifications. # # @example Define multiple notifications # notification :ruby_gntp # notification :ruby_gntp, host: '192.168.1.5' # # @param [Symbol, String] notifier the name of the notifier to use # @param [Hash] opts the notification library options # # @see Guard::Notifier for available notifier and its options. # def notification(notifier, opts = {}) result.notification.merge!(notifier.to_sym => opts) end # Sets the interactor options or disable the interactor. # # @example Pass options to the interactor # interactor option1: 'value1', option2: 'value2' # # @example Turn off interactions # interactor :off # # @param [Symbol, Hash] options either `:off` or a Hash with interactor # options # def interactor(flag_or_options = {}) result.interactor.merge!(flag_or_options.is_a?(Hash) ? flag_or_options : { options.to_sym => {} }) end # Declares a group of Guard plugins to be run with `guard start --group # group_name`. # # @example Declare two groups of Guard plugins # group :backend do # guard :spork # guard :rspec # end # # group :frontend do # guard :passenger # guard :livereload # end # # @param [Symbol, String, Array<Symbol, String>] name the group name called # from the CLI # @param [Hash] options the options accepted by the group # @yield a block where you can declare several Guard plugins # # @see Group # @see #guard # def group(*args) options = args.last.is_a?(Hash) ? args.pop : {} group = args.pop.to_sym if block_given? fail ArgumentError, "'all' is not an allowed group name!" if group == :all result.groups.merge!(group => options) @current_groups_stack ||= [] @current_groups_stack << group yield @current_groups_stack.pop else UI.error \ "No Guard plugins found in the group '#{group}', please add at least one." end end # Declares a Guard plugin to be used when running `guard start`. # # The name parameter is usually the name of the gem without # the 'guard-' prefix. # # The available options are different for each Guard implementation. # # @example Declare a Guard without `watch` patterns # guard :rspec # # @example Declare a Guard with a `watch` pattern # guard :rspec do # watch %r{.*_spec.rb} # end # # @param [String] name the Guard plugin name # @param [Hash] options the options accepted by the Guard plugin # @yield a block where you can declare several watch patterns and actions # # @see Plugin # @see #watch # @see #group # def guard(name, options = {}) name = name.to_sym @current_plugin_options = options.merge(watchers: [], callbacks: []) yield if block_given? @current_groups_stack ||= [] group = @current_groups_stack.last || :default result.plugins << [name, @current_plugin_options.merge(group: group)] @current_plugin_options = nil end # Defines a pattern to be watched in order to run actions on file # modification. # # @example Declare watchers for a Guard # guard :rspec do # watch('spec/spec_helper.rb') # watch(%r{^.+_spec.rb}) # watch(%r{^app/controllers/(.+).rb}) do |m| # 'spec/acceptance/#{m[1]}s_spec.rb' # end # end # # @example Declare global watchers outside of a Guard # watch(%r{^(.+)$}) { |m| puts "#{m[1]} changed." } # # @param [String, Regexp] pattern the pattern that Guard must watch for # modification # # @yield a block to be run when the pattern is matched # @yieldparam [MatchData] m matches of the pattern # @yieldreturn a directory, a filename, an array of # directories / filenames, or nothing (can be an arbitrary command) # # @see Guard::Watcher # @see #guard # def watch(pattern, &action) # Allow watches in the global scope (to execute arbitrary commands) by # building a generic Guard::Plugin. return guard(:plugin) { watch(pattern, &action) } unless @current_plugin_options @current_plugin_options[:watchers] << Watcher.new(pattern, action) end # Defines a callback to execute arbitrary code before or after any of # the `start`, `stop`, `reload`, `run_all`, `run_on_changes`, # `run_on_additions`, `run_on_modifications` and `run_on_removals` plugin # method. # # @example Add callback before the `reload` action. # callback(:reload_begin) { puts "Let's reload!" } # # @example Add callback before the `start` and `stop` actions. # # my_lambda = lambda do |plugin, event, *args| # puts "Let's #{event} #{plugin} with #{args}!" # end # # callback(my_lambda, [:start_begin, :start_end]) # # @param [Array] args the callback arguments # @yield a callback block # def callback(*args, &block) fail "callback must be called within a guard block" unless @current_plugin_options block, events = if args.size > 1 # block must be the first argument in that case, the # yielded block is ignored args else [block, args[0]] end @current_plugin_options[:callbacks] << { events: events, listener: block } end # Ignores certain paths globally. # # @example Ignore some paths # ignore %r{^ignored/path/}, /man/ # # @param [Regexp] regexps a pattern (or list of patterns) for ignoring paths # def ignore(*regexps) result.ignore.concat(Array(regexps).flatten) end # Replaces ignored paths globally # # @example Ignore only these paths # ignore! %r{^ignored/path/}, /man/ # # @param [Regexp] regexps a pattern (or list of patterns) for ignoring paths # def ignore!(*regexps) result.ignore_bang.concat(Array(regexps).flatten) end # Configures the Guard logger. # # * Log level must be either `:debug`, `:info`, `:warn` or `:error`. # * Template supports the following placeholders: `:time`, `:severity`, # `:progname`, `:pid`, `:unit_of_work_id` and `:message`. # * Time format directives are the same as `Time#strftime` or # `:milliseconds`. # * The `:only` and `:except` options must be a `RegExp`. # # @example Set the log level # logger level: :warn # # @example Set a custom log template # logger template: '[Guard - :severity - :progname - :time] :message' # # @example Set a custom time format # logger time_format: '%h' # # @example Limit logging to a Guard plugin # logger only: :jasmine # # @example Log all but not the messages from a specific Guard plugin # logger except: :jasmine # # @param [Hash] options the log options # @option options [String, Symbol] level the log level # @option options [String] template the logger template # @option options [String, Symbol] time_format the time format # @option options [Regexp] only show only messages from the matching Guard # plugin # @option options [Regexp] except does not show messages from the matching # Guard plugin # def logger(options) logger_options = options.dup if logger_options.key?(:level) level = logger_options.delete(:level).to_sym if %i(debug info warn error).include?(level) logger_options[:level] = level else UI.warning(format(WARN_INVALID_LOG_LEVEL, level)) end end if logger_options[:only] && logger_options[:except] UI.warning WARN_INVALID_LOG_OPTIONS logger_options.delete(:only) logger_options.delete(:except) end # Convert the :only and :except options to a regular expression %i(only except).each do |name| opt = logger_options[name] next unless opt list = [].push(opt).flatten.map do |plugin| Regexp.escape(plugin.to_s) end logger_options[name] = Regexp.new(list.join("|"), Regexp::IGNORECASE) end result.logger.merge!(logger_options) end # Sets the default scope on startup # # @example Scope Guard to a single group # scope group: :frontend # # @example Scope Guard to multiple groups # scope groups: [:specs, :docs] # # @example Scope Guard to a single plugin # scope plugin: :test # # @example Scope Guard to multiple plugins # scope plugins: [:jasmine, :rspec] # # @param [Hash] scope the scope for the groups and plugins # def scope(scopes = {}) result.scopes.merge!(scopes) end # Sets the directories to pass to Listen # # @example watch only given directories # directories %w(lib specs) # # @param [Array] directories directories for Listen to watch # def directories(directories) directories = Array(directories) directories.each do |dir| fail "Directory #{dir.inspect} does not exist!" unless Dir.exist?(dir) end result.directories.concat(directories) end # Sets Guard to clear the screen before every task is run # # @example switching clearing the screen on # clearing(:on) # # @param [Symbol] on ':on' to turn on, ':off' (default) to turn off # def clearing(flag) result.clearing = flag == :on end def self.cleanup_backtrace(backtrace) dirs = { File.realpath(Dir.pwd) => ".", } gem_env = ENV["GEM_HOME"] || "" dirs[gem_env] = "$GEM_HOME" unless gem_env.empty? gem_paths = (ENV["GEM_PATH"] || "").split(File::PATH_SEPARATOR) gem_paths.each_with_index do |path, index| dirs[path] = "$GEM_PATH[#{index}]" end backtrace.dup.map do |raw_line| path = nil symlinked_path = raw_line.split(":").first begin path = raw_line.sub(symlinked_path, File.realpath(symlinked_path)) dirs.detect { |dir, name| path.sub!(File.realpath(dir), name) } path rescue Errno::ENOENT path || symlinked_path end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/runner.rb
lib/guard/runner.rb
# frozen_string_literal: true require "lumberjack" require "guard/ui" require "guard/watcher" module Guard # @private # The runner is responsible for running all methods defined on each plugin. # class Runner def initialize(session) @session = session @plugins = session.plugins end # Runs a Guard-task on all registered plugins. # # @param [Symbol] task the task to run # # @param [Hash] scope_hash either the Guard plugin or the group to run the task # on # def run(task, scope_hash = []) scopes, unknown = session.convert_scopes(scope_hash) if unknown.any? UI.info "Unknown scopes: #{unknown.join(', ')}" end Lumberjack.unit_of_work do grouped_plugins = session.grouped_plugins(scopes) grouped_plugins.each_value do |plugins| _run_group_plugins(plugins) do |plugin| _supervise(plugin, task) if plugin.respond_to?(task) end end end end PLUGIN_FAILED = "%s has failed, other group's plugins will be skipped." MODIFICATION_TASKS = %i( run_on_modifications run_on_changes run_on_change ).freeze ADDITION_TASKS = %i(run_on_additions run_on_changes run_on_change).freeze REMOVAL_TASKS = %i(run_on_removals run_on_changes run_on_deletion).freeze # Runs the appropriate tasks on all registered plugins # based on the passed changes. # # @param [Array<String>] modified the modified paths. # @param [Array<String>] added the added paths. # @param [Array<String>] removed the removed paths. # def run_on_changes(modified, added, removed) types = { MODIFICATION_TASKS => modified, ADDITION_TASKS => added, REMOVAL_TASKS => removed } UI.clearable! session.grouped_plugins.each_value do |plugins| _run_group_plugins(plugins) do |plugin| UI.clear types.each do |tasks, unmatched_paths| next if unmatched_paths.empty? match_result = Watcher.match_files(plugin, unmatched_paths) next if match_result.empty? task = tasks.detect { |meth| plugin.respond_to?(meth) } _supervise(plugin, task, match_result) if task end end end end # Run a Guard plugin task, but remove the Guard plugin when his work leads # to a system failure. # # When the Group has `:halt_on_fail` disabled, we've to catch # `:task_has_failed` here in order to avoid an uncaught throw error. # # @param [Guard::Plugin] plugin guard the Guard to execute # @param [Symbol] task the task to run # @param [Array] args the arguments for the task # @raise [:task_has_failed] when task has failed # def _supervise(plugin, task, *args) catch self.class.stopping_symbol_for(plugin) do plugin.hook("#{task}_begin", *args) result = UI.options.with_progname(plugin.class.name) do plugin.send(task, *args) rescue Interrupt throw(:task_has_failed) end plugin.hook("#{task}_end", result) result end rescue ScriptError, StandardError UI.error("#{plugin.class.name} failed to achieve its"\ " <#{task}>, exception was:" \ "\n#{$!.class}: #{$!.message}" \ "\n#{$!.backtrace.join("\n")}") plugins.remove(plugin) UI.info("\n#{plugin.class.name} has just been fired") $! end # Returns the symbol that has to be caught when running a supervised task. # # @note If a Guard group is being run and it has the `:halt_on_fail` # option set, this method returns :no_catch as it will be caught at the # group level. # # @param [Guard::Plugin] guard the Guard plugin to execute # @return [Symbol] the symbol to catch # def self.stopping_symbol_for(plugin) plugin.group.options[:halt_on_fail] ? :no_catch : :task_has_failed end private attr_reader :session, :plugins def _run_group_plugins(plugins) failed_plugin = nil catch :task_has_failed do plugins.each do |plugin| failed_plugin = plugin yield plugin failed_plugin = nil end end UI.info format(PLUGIN_FAILED, failed_plugin.class.name) if failed_plugin end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/terminal.rb
lib/guard/terminal.rb
# frozen_string_literal: true require "shellany/sheller" module Guard # @private class Terminal class << self def clear cmd = Gem.win_platform? ? "cls" : "printf '\33c\e[3J';" stat, _, stderr = Shellany::Sheller.system(cmd) fail Errno::ENOENT, stderr unless stat.success? end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/cli.rb
lib/guard/cli.rb
# frozen_string_literal: true require "thor" require "guard/cli/environments/read_only" require "guard/cli/environments/write" require "guard/dsl_describer" require "guard/engine" require "guard/version" module Guard # Facade for the Guard command line interface managed by # [Thor](https://github.com/wycats/thor). # # This is the main interface to Guard that is called by the Guard binary # `bin/guard`. Do not put any logic in here, create a class and delegate # instead. # class CLI < Thor default_task :start desc "start", "Starts Guard" method_option :clear, type: :boolean, default: false, aliases: "-c", banner: "Auto clear shell before each action" method_option :notify, type: :boolean, default: true, aliases: "-n", banner: "Notifications feature" method_option :debug, type: :boolean, default: false, aliases: "-d", banner: "Show debug information" method_option :group, type: :array, default: [], aliases: "-g", banner: "Run only the passed groups" method_option :plugin, type: :array, default: [], aliases: "-P", banner: "Run only the passed plugins" method_option :watchdirs, type: :array, aliases: "-w", banner: "Specify the directories to watch" method_option :guardfile, type: :string, aliases: "-G", banner: "Specify a Guardfile" method_option :no_interactions, type: :boolean, default: false, aliases: "-i", banner: "Turn off completely any Guard terminal interactions" method_option :no_bundler_warning, type: :boolean, default: false, aliases: "-B", banner: "Turn off warning when Bundler is not present" # Listen options method_option :latency, type: :numeric, aliases: "-l", banner: "Overwrite Listen's default latency" method_option :force_polling, type: :boolean, default: false, aliases: "-p", banner: "Force usage of the Listen polling listener" method_option :wait_for_delay, type: :numeric, aliases: "-y", banner: "Overwrite Listen's default wait_for_delay" method_option :listen_on, type: :string, aliases: "-o", default: nil, banner: "Specify a network address to Listen on for "\ "file change events (e.g. for use in VMs)" def self.help(shell, subcommand = false) super command_help(shell, default_task) end # Start Guard by initializing the defined Guard plugins and watch the file # system. # # This is the default task, so calling `guard` is the same as calling # `guard start`. # # @see Guard::Engine#start # def start if defined?(JRUBY_VERSION) unless options[:no_interactions] abort "\nSorry, JRuby and interactive mode are incompatible.\n"\ "As a workaround, use the '-i' option instead.\n\n"\ "More info: \n"\ " * https://github.com/guard/guard/issues/754\n"\ " * https://github.com/jruby/jruby/issues/2383\n\n" end end exit(read_only_env.start) end desc "list", "Lists Guard plugins that can be used with init" # List the Guard plugins that are available for use in your system and # marks those that are currently used in your `Guardfile`. # # @see Guard::DslDescriber.list # def list DslDescriber.new(read_only_env.evaluate).list end desc "notifiers", "Lists notifiers and its options" # List the Notifiers for use in your system. # # @see Guard::DslDescriber.notifiers # def notifiers DslDescriber.new(read_only_env.evaluate).notifiers end desc "version", "Show the Guard version" map %w(-v --version) => :version # Shows the current version of Guard. # # @see Guard::VERSION # def version $stdout.puts "Guard version #{VERSION}" end desc "init [GUARDS]", "Generates a Guardfile at the current directory"\ " (if it is not already there) and adds all installed Guard plugins"\ " or the given GUARDS into it" method_option :bare, type: :boolean, default: false, aliases: "-b", banner: "Generate a bare Guardfile without adding any"\ " installed plugin into it" # Initializes the templates of all installed Guard plugins and adds them # to the `Guardfile` when no Guard name is passed. When passing # Guard plugin names it does the same but only for those Guard plugins. # # @see Guard::Guardfile.initialize_template # @see Guard::Guardfile.initialize_all_templates # # @param [Array<String>] plugin_names the name of the Guard plugins to # initialize # def init(*plugin_names) exit(write_env.initialize_guardfile(plugin_names)) end desc "show", "Show all defined Guard plugins and their options" map %w(-T) => :show # Shows all Guard plugins and their options that are defined in # the `Guardfile` # # @see Guard::DslDescriber.show # def show DslDescriber.new(read_only_env.evaluate).show end private def read_only_env Cli::Environments::ReadOnly.new(options) end def write_env Cli::Environments::Write.new(options) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/notifier.rb
lib/guard/notifier.rb
# frozen_string_literal: true require "notiffany/notifier" require "guard/ui" module Guard module Notifier # @private def self.connect(options = {}) @notifier ||= nil fail "Already connected!" if @notifier begin opts = options.merge(namespace: "guard", logger: UI) @notifier = Notiffany.connect(opts) rescue Notiffany::Notifier::Detected::UnknownNotifier => e UI.error "Failed to setup notification: #{e.message}" fail end end # @private def self.disconnect @notifier&.disconnect @notifier = nil end # Shows a notification. # # @param [String] message the message to show in the notification # @param [Hash] options the Notiffany #notify options # def self.notify(message, options = {}) connect(notify: true) unless @notifier @notifier.notify(message, options) rescue RuntimeError => e UI.error "Notification failed for #{@notifier.class.name}: #{e.message}" UI.debug e.backtrace.join("\n") end def self.turn_on @notifier.turn_on end # @private def self.toggle unless @notifier.enabled? UI.error NOTIFICATIONS_DISABLED return end if @notifier.active? UI.info "Turn off notifications" @notifier.turn_off return end @notifier.turn_on end # @private # Used by Guard::DslDescriber def self.supported Notiffany::Notifier::SUPPORTED.inject(:merge) end # @private # Used by Guard::DslDescriber def self.detected @notifier.available.map do |mod| { name: mod.name.to_sym, options: mod.options } end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/test_helpers.rb
lib/guard/test_helpers.rb
# frozen_string_literal: true require "guard/engine" module Guard # @private module TestHelpers extend self def self.plugin_options { engine: Engine.new } end class Template class Session class MultipleGuardNotImplemented < RuntimeError def message "multiple guards not supported!" end end class GlobalWatchesNotImplemented < RuntimeError def message "global watches not supported!" end end def initialize(path, content) @watches = {} @current = nil instance_eval(content, path, 1) end def engine @engine ||= Guard::Engine.new end def match(file) _watches.map do |expr, block| next unless (match = file.match(expr)) block.nil? ? [file] : block.call([file] + match.captures) end.flatten.compact.uniq end def guard(name, _options = {}) @current = name @watches[@current] = [] yield @current = nil end def watch(expr, &block) @watches[@current] << [expr, block] end private def _watches keys = @watches.keys fail ArgumentError, "no watches!" if keys.empty? fail MultipleGuardNotImplemented if keys.size > 1 key = keys.first fail GlobalWatchesNotImplemented unless key @watches[key] end end def initialize(plugin_class) name = plugin_class.to_s.sub("Guard::", "").downcase path = format("lib/guard/%<plugin_name>s/templates/Guardfile", plugin_name: name) content = File.read(path) @session = Session.new(path, content) end def changed(file) @session.match(file) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/config.rb
lib/guard/config.rb
# frozen_string_literal: true require "nenv" module Guard config_class = Nenv::Builder.build do create_method(:strict?) create_method(:gem_silence_deprecations?) end # @private class Config < config_class def initialize super "guard" end def silence_deprecations? gem_silence_deprecations? end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/interactor.rb
lib/guard/interactor.rb
# frozen_string_literal: true require "forwardable" require "guard/jobs/pry_wrapper" require "guard/jobs/sleep" module Guard # @private class Interactor attr_reader :interactive # Initializes the interactor. This configures # Pry and creates some custom commands and aliases # for Guard. # def initialize(engine, interactive = true) @engine = engine @interactive = interactive end alias_method :interactive?, :interactive def options @options ||= {} end def options=(opts) @options = opts _reset end def interactive=(flag) @interactive = flag _reset end def background return unless _idle_job? _idle_job.background end extend Forwardable delegate %i(foreground handle_interrupt) => :_idle_job private attr_reader :engine def _job_klass if interactive Jobs::PryWrapper else Jobs::Sleep end end def _idle_job @_idle_job ||= _job_klass.new(engine, options) end def _idle_job? !!@_idle_job end def _reset return unless _idle_job? background @_idle_job = nil end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/engine.rb
lib/guard/engine.rb
# frozen_string_literal: true require "forwardable" require "listen" require "guard/dsl_describer" require "guard/guardfile/evaluator" require "guard/interactor" require "guard/internals/helpers" require "guard/internals/queue" require "guard/internals/session" require "guard/internals/traps" require "guard/notifier" require "guard/runner" require "guard/ui" # Guard is the main module for all Guard related modules and classes. # Also Guard plugins should use this namespace. module Guard # Engine is the main orchestrator class. class Engine extend Forwardable include Internals::Helpers # @private ERROR_NO_PLUGINS = "No Guard plugins found in Guardfile,"\ " please add at least one." # Initialize a new Guard::Engine object. # # @option options [Boolean] clear if auto clear the UI should be done # @option options [Boolean] notify if system notifications should be shown # @option options [Boolean] debug if debug output should be shown # @option options [Array<String>] group the list of groups to start # @option options [Array<String>] watchdirs the directories to watch # @option options [String] guardfile the path to the Guardfile # @option options [String] inline the inline content of a Guardfile # # @return [Guard::Engine] a Guard::Engine instance def initialize(options = {}) @options = options Thread.current[:engine] = self end def session @session ||= Guard::Internals::Session.new(options) end def evaluator @evaluator ||= Guardfile::Evaluator.new(options) end def to_s "#<#{self.class}:#{object_id} @options=#{options}>" end alias_method :inspect, :to_s delegate %i[plugins groups watchdirs] => :session delegate paused?: :_listener # Evaluate the Guardfile and instantiate internals. # def setup _instantiate UI.reset_and_clear if evaluator.inline? UI.info("Using inline Guardfile.") elsif evaluator.custom? UI.info("Using Guardfile at #{evaluator.guardfile_path}.") end self end # Start Guard by evaluating the `Guardfile`, initializing declared Guard # plugins and starting the available file change listener. # Main method for Guard that is called from the CLI when Guard starts. # # - Setup Guard internals # - Evaluate the `Guardfile` # - Configure Notifiers # - Initialize the declared Guard plugins # - Start the available file change listener # # @option options [Boolean] clear if auto clear the UI should be done # @option options [Boolean] notify if system notifications should be shown # @option options [Boolean] debug if debug output should be shown # @option options [Array<String>] group the list of groups to start # @option options [String] watchdirs the director to watch # @option options [String] guardfile the path to the Guardfile # @see CLI#start # def start setup _initialize_listener _initialize_signal_traps _initialize_notifier UI.debug "Guard starts all plugins" _runner.run(:start) UI.info "Guard is now watching at '#{session.watchdirs.join("', '")}'" _listener.start exitcode = 0 begin loop do break if _interactor.foreground == :exit loop do break unless _queue.pending? _queue.process end end rescue Interrupt rescue SystemExit => e exitcode = e.status end exitcode ensure stop end def stop _listener.stop _interactor.background UI.debug "Guard stops all plugins" _runner.run(:stop) Notifier.disconnect UI.info "Bye bye...", reset: true end # Reload Guardfile and all Guard plugins currently enabled. # If no scope is given, then the Guardfile will be re-evaluated, # which results in a stop/start, which makes the reload obsolete. # # @param [Hash] scopes hash with a Guard plugin or a group scope # def reload(*entries) entries.flatten! UI.clear(force: true) UI.action_with_scopes("Reload", session.scope_titles(entries)) _runner.run(:reload, entries) end # Trigger `run_all` on all Guard plugins currently enabled. # # @param [Hash] scopes hash with a Guard plugin or a group scope # def run_all(*entries) entries.flatten! UI.clear(force: true) UI.action_with_scopes("Run", session.scope_titles(entries)) _runner.run(:run_all, entries) end # Pause Guard listening to file changes. # def pause(expected = nil) states = { paused: true, unpaused: false, toggle: !paused? } key = expected || :toggle raise ArgumentError, "invalid mode: #{expected.inspect}" unless states.key?(key) pause = states[key] return if pause == paused? _listener.public_send(pause ? :pause : :start) UI.info "File event handling has been #{pause ? 'paused' : 'resumed'}" end def show DslDescriber.new(self).show end # @private # Asynchronously trigger changes # # Currently supported args: # # @example Old style hash: # async_queue_add(modified: ['foo'], added: ['bar'], removed: []) # # @example New style signals with args: # async_queue_add([:pause, :unpaused ]) # def async_queue_add(changes) _queue << changes # Putting interactor in background puts guard into foreground # so it can handle change notifications Thread.new { _interactor.background } end private attr_reader :options def _restart stop @session = nil @_listener = nil start end def _runner @_runner ||= Runner.new(session) end def _queue @_queue ||= Internals::Queue.new(self, _runner) end def _listener @_listener ||= Listen.send(*session.listener_args, &_listener_callback) end def _interactor @_interactor ||= Interactor.new(self, session.interactor_name == :pry_wrapper) end # Instantiate Engine internals based on the `Guard::Guardfile::Result` populated from the `Guardfile` evaluation. # # @example Programmatically evaluate a Guardfile # engine = Guard::Engine.new.setup # # @example Programmatically evaluate a Guardfile with a custom Guardfile # path # # options = { guardfile: '/Users/guardfile/MyAwesomeGuardfile' } # engine = Guard::Engine.new(options).setup # # @example Programmatically evaluate a Guardfile with an inline Guardfile # # options = { inline: 'guard :rspec' } # engine = Guard::Engine.new(options).setup # def _instantiate guardfile_result = evaluator.evaluate guardfile_result_plugins = guardfile_result.plugins UI.error(ERROR_NO_PLUGINS) if guardfile_result_plugins.empty? session.guardfile_notification = guardfile_result.notification session.guardfile_ignore = guardfile_result.ignore session.guardfile_ignore_bang = guardfile_result.ignore_bang session.guardfile_scopes = guardfile_result.scopes session.watchdirs = guardfile_result.directories session.clearing(guardfile_result.clearing) _instantiate_logger(guardfile_result.logger.dup) _instantiate_interactor(guardfile_result.interactor) _instantiate_groups(guardfile_result.groups) _instantiate_plugins(guardfile_result_plugins) end def _instantiate_interactor(interactor_options) case interactor_options when :off _interactor.interactive = false when Hash _interactor.options = interactor_options end end def _instantiate_logger(logger_options) if logger_options.key?(:level) UI.level = logger_options.delete(:level) end if logger_options.key?(:template) UI.template = logger_options.delete(:template) end UI.options.merge!(logger_options) end def _instantiate_groups(groups_hash) groups_hash.each do |name, options| groups.add(name, options) end end def _instantiate_plugins(plugins_array) plugins_array.each do |name, options| options[:group] = groups.find(options[:group]) plugins.add(name, options) end end def _listener_callback lambda do |modified, added, removed| relative_paths = { modified: _relative_pathnames(modified), added: _relative_pathnames(added), removed: _relative_pathnames(removed) } async_queue_add(relative_paths) end end def _initialize_listener ignores = session.guardfile_ignore _listener.ignore(ignores) unless ignores.empty? ignores_bang = session.guardfile_ignore_bang _listener.ignore!(ignores_bang) unless ignores_bang.empty? end def _initialize_signal_traps traps = Internals::Traps traps.handle("USR1") { async_queue_add(%i(pause paused)) } traps.handle("USR2") { async_queue_add(%i(pause unpaused)) } traps.handle("INT") { _interactor.handle_interrupt } end def _initialize_notifier Notifier.connect(session.notify_options) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/jobs/base.rb
lib/guard/jobs/base.rb
# frozen_string_literal: true module Guard module Jobs class Base def initialize(engine, _options = {}) @engine = engine end # @return [Symbol] :continue once job is finished # @return [Symbol] :exit to tell Guard to terminate def foreground; end def background; end # Signal handler calls this, so avoid actually doing # anything other than signaling threads def handle_interrupt; end private attr_reader :engine end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/jobs/pry_wrapper.rb
lib/guard/jobs/pry_wrapper.rb
# frozen_string_literal: true require "shellany/sheller" require "guard/commands/all" require "guard/commands/change" require "guard/commands/notification" require "guard/commands/pause" require "guard/commands/reload" require "guard/commands/scope" require "guard/commands/show" require "guard/jobs/base" require "guard/ui" module Guard module Jobs class TerminalSettings def initialize @settings = nil @works = Shellany::Sheller.run("hash", "stty") || false end def restore return unless configurable? && @settings Shellany::Sheller.run("stty #{@setting} 2>#{IO::NULL}") end def save return unless configurable? @settings = Shellany::Sheller.stdout("stty -g 2>#{IO::NULL}").chomp end def echo return unless configurable? Shellany::Sheller.run("stty echo 2>#{IO::NULL}") end def configurable? @works end end class PryWrapper < Base # The default Ruby script to configure Guard Pry if the option `:guard_rc` # is not defined. GUARD_RC = if ENV["XDG_CONFIG_HOME"] && File.exist?(ENV["XDG_CONFIG_HOME"] + "/guard/guardrc") ENV["XDG_CONFIG_HOME"] + "/guard/guardrc" else "~/.guardrc" end # The default Guard Pry history file if the option `:history_file` is not # defined. HISTORY_FILE = if ENV["XDG_DATA_HOME"] && File.exist?(ENV["XDG_DATA_HOME"] + "/guard/history") ENV["XDG_DATA_HOME"] + "/guard/history" else "~/.guard_history" end # List of shortcuts for each interactor command SHORTCUTS = { help: "h", all: "a", reload: "r", change: "c", show: "s", scope: "o", notification: "n", pause: "p", exit: "e", quit: "q" }.freeze def initialize(engine, options = {}) super @mutex = Mutex.new @thread = nil @terminal_settings = TerminalSettings.new _setup(options) end def foreground UI.debug "Start interactor" terminal_settings.save _switch_to_pry _killed? ? :continue : :exit ensure UI.reset_line UI.debug "Interactor was stopped or killed" terminal_settings.restore end def background _kill_pry end def handle_interrupt # thread = @thread fail Interrupt unless thread thread.raise Interrupt end private attr_reader :terminal_settings, :thread def _pry_config Pry.config end def _pry_commands Pry.commands end def _switch_to_pry th = nil @mutex.synchronize do unless @thread @thread = Thread.new { Pry.start } @thread[:engine] = engine @thread.join(0.5) # give pry a chance to start th = @thread end end # check for nil, because it might've been killed between the mutex and # now th&.join end def _killed? th = nil @mutex.synchronize { th = @thread } th.nil? end def _kill_pry @mutex.synchronize do if @thread @thread.kill @thread = nil # set to nil so we know we were killed end end end def _setup(options) _pry_config.should_load_rc = false _pry_config.should_load_local_rc = false _configure_history_file(options[:history_file] || HISTORY_FILE) _add_hooks(options) Commands::All.import Commands::Change.import Commands::Notification.import Commands::Pause.import Commands::Reload.import Commands::Show.import Commands::Scope.import _setup_commands _configure_prompt end def _configure_history_file(history_file) history_file_path = File.expand_path(history_file) # Pry >= 0.13 if _pry_config.respond_to?(:history_file=) _pry_config.history_file = history_file_path else _pry_config.history.file = history_file_path end end # Add Pry hooks: # # * Load `~/.guardrc` within each new Pry session. # * Load project's `.guardrc` within each new Pry session. # * Restore prompt after each evaluation. # def _add_hooks(options) _add_load_guard_rc_hook(Pathname(options[:guard_rc] || GUARD_RC)) _add_load_project_guard_rc_hook(Pathname.pwd + ".guardrc") _add_restore_visibility_hook if terminal_settings.configurable? end # Add a `when_started` hook that loads a global .guardrc if it exists. # def _add_load_guard_rc_hook(guard_rc) _pry_config.hooks.add_hook :when_started, :load_guard_rc do guard_rc.expand_path.tap { |p| load p if p.exist? } end end # Add a `when_started` hook that loads a project .guardrc if it exists. # def _add_load_project_guard_rc_hook(guard_rc) _pry_config.hooks.add_hook :when_started, :load_project_guard_rc do load guard_rc if guard_rc.exist? end end # Add a `after_eval` hook that restores visibility after a command is # eval. def _add_restore_visibility_hook _pry_config.hooks.add_hook :after_eval, :restore_visibility do terminal_settings.echo end end def _setup_commands _replace_reset_command _create_run_all_command _create_command_aliases _create_guard_commands _create_group_commands end # Replaces reset defined inside of Pry with a reset that # instead restarts guard. # def _replace_reset_command _pry_commands.command "reset", "Reset the Guard to a clean state." do output.puts "Guard reset." exec "guard" end end # Creates a command that triggers the `:run_all` action # when the command is empty (just pressing enter on the # beginning of a line). # def _create_run_all_command _pry_commands.block_command(/^$/, "Hit enter to run all") do Pry.run_command "all" end end # Creates command aliases for the commands: `help`, `reload`, `change`, # `scope`, `notification`, `pause`, `exit` and `quit`, which will be the # first letter of the command. # def _create_command_aliases SHORTCUTS.each do |command, shortcut| _pry_commands.alias_command shortcut, command.to_s end end # Create a shorthand command to run the `:run_all` # action on a specific Guard plugin. For example, # when guard-rspec is available, then a command # `rspec` is created that runs `all rspec`. # def _create_guard_commands engine.session.plugins.all.each do |guard_plugin| cmd = "Run all #{guard_plugin.title}" _pry_commands.create_command guard_plugin.name, cmd do group "Guard" def process # rubocop:disable Lint/NestedMethodDefinition Pry.run_command "all #{match}" end end end end # Create a shorthand command to run the `:run_all` # action on a specific Guard group. For example, # when you have a group `frontend`, then a command # `frontend` is created that runs `all frontend`. # def _create_group_commands engine.session.groups.all.each do |group| next if group.name == :default cmd = "Run all #{group.title}" _pry_commands.create_command group.name.to_s, cmd do group "Guard" def process # rubocop:disable Lint/NestedMethodDefinition Pry.run_command "all #{match}" end end end end # Configures the pry prompt to see `guard` instead of # `pry`. # def _configure_prompt prompt_procs = [_prompt(">"), _prompt("*")] prompt = if Pry::Prompt.is_a?(Class) Pry::Prompt.new("Guard", "Guard Pry prompt", prompt_procs) else prompt_procs end _pry_config.prompt = prompt end # Returns the plugins scope, or the groups scope ready for display in the # prompt. # def _scope_for_prompt titles = engine.session.scope_titles.join(",") titles == "all" ? "" : titles + " " end # Returns a proc that will return itself a string ending with the given # `ending_char` when called. # def _prompt(ending_char) proc do |target_self, nest_level, pry| process = engine.paused? ? "pause" : "guard" level = ":#{nest_level}" unless nest_level.zero? "[#{_history(pry)}] #{_scope_for_prompt}#{process}"\ "(#{_clip_name(target_self)})#{level}#{ending_char} " end end def _clip_name(target) Pry.view_clip(target) end def _history(pry) if pry.respond_to?(:input_ring) pry.input_ring.size else pry.input_array.size end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/jobs/sleep.rb
lib/guard/jobs/sleep.rb
# frozen_string_literal: true require "guard/jobs/base" require "guard/ui" module Guard module Jobs class Sleep < Base def foreground UI.debug "Guards jobs done. Sleeping..." sleep UI.debug "Sleep interrupted by events." :continue rescue Interrupt UI.debug "Sleep interrupted by user." :exit end def background Thread.main.wakeup end def handle_interrupt Thread.main.raise Interrupt end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/watcher/pattern.rb
lib/guard/watcher/pattern.rb
# frozen_string_literal: true require "guard/ui" require_relative "pattern/matcher" require_relative "pattern/simple_path" module Guard class Watcher # @private class Pattern def self.create(pattern) case pattern when String, Pathname SimplePath.new(pattern) else Matcher.new(pattern) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/watcher/pattern/simple_path.rb
lib/guard/watcher/pattern/simple_path.rb
# frozen_string_literal: true module Guard class Watcher class Pattern class SimplePath def initialize(string_or_pathname) @path = normalize(string_or_pathname) end def to_s @path end alias_method :inspect, :to_s def match(string_or_pathname) cleaned = normalize(string_or_pathname) return nil unless @path == cleaned [cleaned] end protected def normalize(string_or_pathname) Pathname.new(string_or_pathname).cleanpath.to_s end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/watcher/pattern/matcher.rb
lib/guard/watcher/pattern/matcher.rb
# frozen_string_literal: true module Guard class Watcher class Pattern class Matcher attr_reader :matcher def initialize(obj) @matcher = obj end def to_s matcher.to_s end alias_method :inspect, :to_s # Compare with other matcher # @param other [Guard::Watcher::Pattern::Matcher] # other matcher for comparing # @return [true, false] equal or not def ==(other) matcher == other.matcher end def match(string_or_pathname) @matcher.match(normalized(string_or_pathname)) end private def normalized(string_or_pathname) path = Pathname.new(string_or_pathname).cleanpath return path.to_s if @matcher.is_a?(Regexp) path end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/watcher/pattern/match_result.rb
lib/guard/watcher/pattern/match_result.rb
# frozen_string_literal: true module Guard class Watcher class Pattern class MatchResult def initialize(match_result, original_value) @match_result = match_result @original_value = original_value end def [](index) return @match_result[index] if index.is_a?(Symbol) return @original_value if index.zero? @match_result.to_a[index] end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/reload.rb
lib/guard/commands/reload.rb
# frozen_string_literal: true require "pry" module Guard module Commands class Reload def self.import Pry::Commands.create_command "reload" do group "Guard" description "Reload all plugins." banner <<-BANNER Usage: reload <scope> Run the Guard plugin `reload` action. You may want to specify an optional scope to the action, either the name of a Guard plugin or a plugin group. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process(*entries) # rubocop:disable Lint/NestedMethodDefinition engine.async_queue_add([:reload, entries]) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/pause.rb
lib/guard/commands/pause.rb
# frozen_string_literal: true require "pry" module Guard module Commands class Pause def self.import Pry::Commands.create_command "pause" do group "Guard" description "Toggles the file listener." banner <<-BANNER Usage: pause Toggles the file listener on and off. When the file listener is paused, the default Guard Pry prompt will show the pause sign `[p]`. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process # rubocop:disable Lint/NestedMethodDefinition engine.async_queue_add([:pause]) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/change.rb
lib/guard/commands/change.rb
# frozen_string_literal: true require "pry" require "guard" module Guard module Commands class Change def self.import Pry::Commands.create_command "change" do group "Guard" description "Trigger a file change." banner <<-BANNER Usage: change <file> <other_file> Pass the given files to the Guard plugin `run_on_changes` action. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process(*files) # rubocop:disable Lint/NestedMethodDefinition if files.empty? output.puts "Please specify a file." return end engine.async_queue_add(modified: files, added: [], removed: []) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/scope.rb
lib/guard/commands/scope.rb
# frozen_string_literal: true require "pry" module Guard module Commands class Scope def self.import Pry::Commands.create_command "scope" do group "Guard" description "Scope Guard actions to groups and plugins." banner <<-BANNER Usage: scope <scope> Set the global Guard scope. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process(*entries) # rubocop:disable Lint/NestedMethodDefinition session = engine.session scopes, = session.convert_scopes([]) if entries != ["all"] scopes, = session.convert_scopes(entries) if scopes[:plugins].empty? && scopes[:groups].empty? output.puts "Usage: scope <scope>" return end end session.interactor_scopes = scopes end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/notification.rb
lib/guard/commands/notification.rb
# frozen_string_literal: true require "pry" require "guard/notifier" module Guard module Commands class Notification def self.import Pry::Commands.create_command "notification" do group "Guard" description "Toggles the notifications." banner <<-BANNER Usage: notification Toggles the notifications on and off. BANNER def process # rubocop:disable Lint/NestedMethodDefinition Notifier.toggle end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/show.rb
lib/guard/commands/show.rb
# frozen_string_literal: true require "pry" module Guard module Commands class Show def self.import Pry::Commands.create_command "show" do group "Guard" description "Show all Guard plugins." banner <<-BANNER Usage: show Show all defined Guard plugins and their options. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process # rubocop:disable Lint/NestedMethodDefinition engine.async_queue_add([:show]) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/commands/all.rb
lib/guard/commands/all.rb
# frozen_string_literal: true require "pry" module Guard module Commands class All def self.import Pry::Commands.create_command "all" do group "Guard" description "Run all plugins." banner <<-BANNER Usage: all <scope> Run the Guard plugin `run_all` action. You may want to specify an optional scope to the action, either the name of a Guard plugin or a plugin group. BANNER def engine # rubocop:disable Lint/NestedMethodDefinition Thread.current[:engine] end def process(*entries) # rubocop:disable Lint/NestedMethodDefinition engine.async_queue_add([:run_all, entries]) end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/traps.rb
lib/guard/internals/traps.rb
# frozen_string_literal: true module Guard module Internals module Traps def self.handle(signal, &block) return unless Signal.list.key?(signal) Signal.trap(signal, &block) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/plugins.rb
lib/guard/internals/plugins.rb
# frozen_string_literal: true require "guard/plugin_util" module Guard # @private api module Internals class Plugins def initialize @plugins = [] end def add(name, options) PluginUtil.new(name).initialize_plugin(options).tap do |plugin| @plugins << plugin end end def remove(plugin) @plugins.delete(plugin) end def all(filter = nil) return @plugins unless filter matcher = matcher_for(filter) @plugins.select { |plugin| matcher.call(plugin) } end def find(filter) all(filter).first end private def matcher_for(filter) case filter when String, Symbol shortname = filter.to_s.downcase ->(plugin) { plugin.name == shortname } when Regexp ->(plugin) { plugin.name =~ filter } when Hash lambda do |plugin| filter.all? do |k, v| case k when :name plugin.name == v.to_s.downcase when :group plugin.group.name == v.to_sym end end end else fail "Invalid filter: #{filter.inspect}" end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/debugging.rb
lib/guard/internals/debugging.rb
# frozen_string_literal: true # Because it's used by Sheller require "open3" require "logger" require "guard/internals/tracing" require "guard/ui" module Guard # @private api module Internals class Debugging class << self TRACES = [ [Kernel, :system], [Kernel, :spawn], [Kernel, :`], [Open3, :popen3] ].freeze # Sets up debugging: # # * aborts on thread exceptions # * Set the logging level to `:debug` # * traces execution of Kernel.system and backtick calls def start return if @started ||= false @started = true Thread.abort_on_exception = true UI.level = Logger::DEBUG TRACES.each { |mod, meth| _trace(mod, meth, &method(:_notify)) } @traced = true end def stop return unless @started ||= false UI.level = Logger::INFO _reset end private def _notify(*args) UI.debug "Command execution: #{args.join(' ')}" end # reset singleton - called by tests def _reset @started = false return unless @traced TRACES.each { |mod, meth| _untrace(mod, meth) } @traced = false end def _trace(mod, meth, &block) Tracing.trace(mod, meth, &block) end def _untrace(mod, meth) Tracing.untrace(mod, meth) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/groups.rb
lib/guard/internals/groups.rb
# frozen_string_literal: true require "forwardable" require "guard/group" module Guard # @private api module Internals class Groups extend Forwardable DEFAULT_GROUP = :default def initialize @groups = [Group.new(DEFAULT_GROUP)] end delegate each: :all def all(filter = nil) return @groups unless filter matcher = matcher_for(filter) @groups.select { |group| matcher.call(group) } end def find(filter) all(filter).first end def add(name, options = {}) find(name) || Group.new(name, options).tap do |group| fail if name == :specs && options.empty? @groups << group end end private def matcher_for(filter) case filter when String, Symbol ->(group) { group.name == filter.to_sym } when Regexp ->(group) { group.name.to_s =~ filter } when Array, Set ->(group) { filter.map(&:to_sym).include?(group.name) } else fail "Invalid filter: #{filter.inspect}" end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/session.rb
lib/guard/internals/session.rb
# frozen_string_literal: true require "guard/options" require "guard/internals/debugging" require "guard/internals/plugins" require "guard/internals/groups" module Guard # @private api module Internals # TODO: split into a commandline class and session (plugins, groups) # TODO: swap session and metadata class Session attr_reader :plugins, :groups DEFAULT_OPTIONS = { clear: false, debug: false, no_bundler_warning: false, # User defined scopes group: [], plugin: [], # Notifier notify: true, # Interactor no_interactions: false, # Guardfile options: guardfile: nil, inline: nil, # Listener options watchdirs: Dir.pwd, latency: nil, force_polling: false, wait_for_delay: nil, listen_on: nil }.freeze # Internal class to store group and plugin scopes ScopesHash = Struct.new(:groups, :plugins) def initialize(new_options = {}) @engine = engine @options = Options.new(new_options, DEFAULT_OPTIONS) @plugins = Plugins.new @groups = Groups.new @guardfile_scopes = ScopesHash.new([], []) @cmdline_scopes = ScopesHash.new( Array(options.delete(:groups)) + Array(options.delete(:group)), Array(options.delete(:plugins)) + Array(options.delete(:plugin)) ) @interactor_scopes = ScopesHash.new([], []) @clear = @options[:clear] @debug = @options[:debug] @watchdirs = Array(@options[:watchdirs]) @notify = @options[:notify] @interactor_name = @options[:no_interactions] ? :sleep : :pry_wrapper @guardfile_ignore = [] @guardfile_ignore_bang = [] @guardfile_notifier_options = {} # NOTE: must be set before anything calls Guard::UI.debug Debugging.start if debug? end def convert_scopes(entries) scopes = { plugins: [], groups: [] } unknown = [] Array(entries).each do |entry| if plugin = plugins.find(entry) scopes[:plugins] << plugin.name.to_sym elsif group = groups.find(entry) scopes[:groups] << group.name.to_sym else unknown << entry end end [scopes, unknown] end def grouped_plugins(scopes = {}) if scopes[:plugins] _retrieve_plugins(scopes).group_by(&:group) elsif scopes[:groups] _retrieve_groups(scopes).map do |group| [group, plugins.all(group: group.name)] end.to_h else _retrieve_plugins(_scopes_hash).group_by(&:group) end end def scope_titles(entries = []) scopes, = convert_scopes(entries) if scopes[:plugins].any? objects = _retrieve_plugins(scopes) elsif scopes[:groups].any? objects = _retrieve_groups(scopes) else if _current_scope_names(:plugins).empty? && _current_scope_names(:groups).empty? return ["all"] end objects = _retrieve_plugins(_scopes_hash) end objects.map(&:title) end def guardfile_scopes=(scope) opts = scope.dup @guardfile_scopes.groups = Array(opts.delete(:groups)) + Array(opts.delete(:group)) @guardfile_scopes.plugins = Array(opts.delete(:plugins)) + Array(opts.delete(:plugin)) fail "Unknown options: #{opts.inspect}" unless opts.empty? end def interactor_scopes=(scopes) @interactor_scopes.groups = Array(scopes[:groups]) @interactor_scopes.plugins = Array(scopes[:plugins]) end attr_reader :cmdline_scopes, :guardfile_scopes, :interactor_scopes attr_reader :guardfile_ignore def guardfile_ignore=(ignores) @guardfile_ignore += Array(ignores).flatten end attr_reader :guardfile_ignore_bang def guardfile_ignore_bang=(ignores) @guardfile_ignore_bang = Array(ignores).flatten end def clearing(flag) @clear = flag end def clearing? @clear end alias :clear? :clearing? def debug? @debug end def watchdirs @watchdirs_from_guardfile ||= nil @watchdirs_from_guardfile || @watchdirs || [Dir.pwd] end # set by Engine#_instantiate def watchdirs=(dirs) return if dirs.empty? @watchdirs_from_guardfile = dirs.map { |dir| File.expand_path(dir) } end def listener_args if @options[:listen_on] [:on, @options[:listen_on]] else listener_options = {} %i(latency force_polling wait_for_delay).each do |option| listener_options[option] = @options[option] if @options[option] end expanded_watchdirs = watchdirs.map { |dir| File.expand_path dir } [:to, *expanded_watchdirs, listener_options] end end def notify_options names = @guardfile_notifier_options.keys return { notify: false } if names.include?(:off) { notify: @options[:notify], notifiers: @guardfile_notifier_options } end def guardfile_notification=(config) @guardfile_notifier_options.merge!(config) end attr_reader :interactor_name, :options def to_s "#<#{self.class}:#{object_id}>" end alias_method :inspect, :to_s private attr_reader :engine def _current_scope_names(type) [interactor_scopes[type], cmdline_scopes[type], guardfile_scopes[type]].detect do |source| !source.empty? end || [] end def _scopes_hash { plugins: _current_scope_names(:plugins), groups: _current_scope_names(:groups) }.dup.freeze end def _retrieve_plugins(scope) plugin_names = Array(scope[:plugins]) plugin_names = plugins.all.map(&:name) if plugin_names.empty? plugin_names = Set.new(plugin_names) plugin_names.map { |plugin_name| plugins.find(plugin_name) } end def _retrieve_groups(scope) group_names = Array(scope[:groups]) group_names = groups.all.map(&:name) if group_names.empty? group_names = Set.new(group_names) groups.all(group_names) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/queue.rb
lib/guard/internals/queue.rb
# frozen_string_literal: true require "forwardable" module Guard module Internals class Queue extend Forwardable delegate :<< => :queue def initialize(engine, runner) @engine = engine @runner = runner @queue = ::Queue.new end # Process the change queue, running tasks within the main Guard thread def process actions = [] changes = { modified: [], added: [], removed: [] } while pending? if (item = queue.pop).first.is_a?(Symbol) actions << item else item.each { |key, value| changes[key] += value } end end _run_actions(actions) return if changes.values.all?(&:empty?) runner.run_on_changes(*changes.values) end def pending? !queue.empty? end private attr_reader :engine, :runner, :queue def _run_actions(actions) actions.each do |action_args| args = action_args.dup action = args.shift engine.public_send(action, *args) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/helpers.rb
lib/guard/internals/helpers.rb
# frozen_string_literal: true module Guard # @private api module Internals module Helpers def _relative_pathnames(paths) paths.map { |path| _relative_pathname(path) } end def _relative_pathname(path) full_path = Pathname(path) full_path.relative_path_from(Pathname.pwd) rescue ArgumentError full_path end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/internals/tracing.rb
lib/guard/internals/tracing.rb
# frozen_string_literal: true module Guard module Internals module Tracing def self.trace(mod, meth) meta = (class << mod; self; end) original_meth = "original_#{meth}".to_sym if mod.respond_to?(original_meth) fail "ALREADY TRACED: #{mod}.#{meth}" end meta.send(:alias_method, original_meth, meth) meta.send(:define_method, meth) do |*args, &block| yield(*args) if block_given? mod.send original_meth, *args, &block end end def self.untrace(mod, meth) meta = (class << mod; self; end) original_meth = "original_#{meth}".to_sym unless mod.respond_to?(original_meth) fail "NOT TRACED: #{mod}.#{meth} (no method: #{original_meth})" end meta.send(:remove_method, meth) meta.send(:alias_method, meth, original_meth) meta.send(:undef_method, original_meth) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/cli/environments/write.rb
lib/guard/cli/environments/write.rb
# frozen_string_literal: true require "guard/cli/environments/base" require "guard/guardfile/evaluator" require "guard/guardfile/generator" require "guard/ui" module Guard module Cli module Environments class Write < Base def initialize_guardfile( plugin_names = [], evaluator: Guardfile::Evaluator.new(options), generator: Guardfile::Generator.new ) begin evaluator.evaluate rescue Guardfile::Evaluator::NoGuardfileError generator.create_guardfile end return 0 if options[:bare] # 0 - exit code begin if plugin_names.empty? generator.initialize_all_templates else plugin_names.each do |plugin_name| generator.initialize_template(plugin_name) end end rescue Guardfile::Generator::Error => e UI.error(e.message) return 1 end 0 rescue StandardError => e UI.error(e.message) 1 end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/cli/environments/base.rb
lib/guard/cli/environments/base.rb
# frozen_string_literal: true require "guard/ui" module Guard module Cli module Environments class Base # Initialize a new Guard::Cli::Environments::Base object. # # @option options [Boolean] no_bundler_warning whether to show the "Bundler should be used" warning or not # # @return [Guard::Cli::Environments::Base] a Guard::Cli::Environments::Base instance def initialize(options) @options = options.dup end private attr_reader :options def bundler_check return if options[:no_bundler_warning] return unless File.exist?("Gemfile") return if ENV["BUNDLE_GEMFILE"] || ENV["RUBYGEMS_GEMDEPS"] UI.info <<~BUNDLER_NOTICE Guard here! It looks like your project has a Gemfile, yet you are running `guard` outside of Bundler. If this is your intent, feel free to ignore this message. Otherwise, consider using `bundle exec guard` to ensure your dependencies are loaded correctly. (You can run `guard` with --no-bundler-warning to get rid of this message.) BUNDLER_NOTICE end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/cli/environments/read_only.rb
lib/guard/cli/environments/read_only.rb
# frozen_string_literal: true require "guard/cli/environments/base" require "guard/dsl" require "guard/engine" require "guard/guardfile/evaluator" require "guard/ui" module Guard module Cli module Environments class ReadOnly < Base def evaluate(evaluator: Guardfile::Evaluator.new(options)) bundler_check evaluator.evaluate rescue Dsl::Error, Guardfile::Evaluator::NoGuardfileError, Guardfile::Evaluator::NoCustomGuardfile => e UI.error(e.message) abort("") end def start(engine: Guard::Engine.new(options)) bundler_check engine.start rescue Dsl::Error, Guardfile::Evaluator::NoGuardfileError, Guardfile::Evaluator::NoCustomGuardfile => e # catch to throw message instead of call stack UI.error(e.message) abort("") end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/guardfile/result.rb
lib/guard/guardfile/result.rb
# frozen_string_literal: true require "guard/internals/groups" module Guard module Guardfile # This class is responsible for storing the result of the Guardfile evaluation. # # @see Guard::Dsl # class Result attr_accessor :clearing def plugin_names plugins.map(&:first).map(&:to_sym) end # Store notification settings as a hash: `{ off: {} }`. # # @return [Hash] # def notification @notification ||= {} end # Store interactor settings as a hash: `{ off: {} }`. # # @return [Hash] # def interactor @interactor ||= {} end # Store groups as a hash: `{ frontend: {}, backend: {} }`. # # @return [Hash] # def groups @groups ||= { Guard::Internals::Groups::DEFAULT_GROUP => {} } end # Store plugins as an array of hashes: `[{ name: "", options: {} }]`. # # @return [Array<Hash>] # def plugins @plugins ||= [] end # Store ignore regexps as an array: `[/foo/]`. # # @return [Array<Regexp>] # def ignore @ignore ||= [] end # Store ignore! regexps as an array: `[/foo/]`. # # @return [Array<Regexp>] # def ignore_bang @ignore_bang ||= [] end # Store logger settings as a hash: `{ off: {} }`. # # @return [Hash] # def logger @logger ||= {} end # Store scopes settings as a hash: `{ plugins: [:rspec] }`. # # @return [Hash] # def scopes @scopes ||= {} end # Store directories as an array: `['foo']`. # # @return [Array<String>] # def directories @directories ||= [] end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/guardfile/generator.rb
lib/guard/guardfile/generator.rb
# frozen_string_literal: true require "guard/plugin_util" require "guard/ui" module Guard module Guardfile # This class is responsible for generating the Guardfile and adding Guard' # plugins' templates into it. # # @see Guard::CLI # class Generator # @private INFO_TEMPLATE_ADDED = "%s template added to Guardfile, feel free to edit it" # @private # The Guardfile template for `guard init` GUARDFILE_TEMPLATE = File.expand_path( "../../guard/templates/Guardfile", __dir__ ) # The location of user defined templates begin HOME_TEMPLATES = Pathname.new("~/.guard/templates").expand_path rescue ArgumentError # home isn't defined. Set to the root of the drive. Trust that there # won't be user defined templates there HOME_TEMPLATES = Pathname.new("/").expand_path end # @private class Error < RuntimeError end class NoSuchPlugin < Error attr_reader :plugin_name, :class_name def initialize(plugin_name) @plugin_name = plugin_name @class_name = plugin_name.delete("-").capitalize end def message "Could not load 'guard/#{plugin_name}'"\ " or '~/.guard/templates/#{plugin_name}'"\ " or find class Guard::#{class_name}\n" end end # Creates the initial Guardfile template when it does not # already exist. # # @see Guard::CLI#init # def create_guardfile path = Pathname.new("Guardfile").expand_path if path.exist? UI.error("Guardfile already exists at #{path}") abort end UI.info("Writing new Guardfile to #{path}") FileUtils.cp(GUARDFILE_TEMPLATE, path.to_s) end # Adds the Guardfile template of a Guard plugin to an existing Guardfile. # # @see Guard::CLI#init # def initialize_template(plugin_name) guardfile = Pathname.new("Guardfile") plugin_util = PluginUtil.new(plugin_name) if plugin_util.valid? begin plugin_util.add_to_guardfile rescue Errno::ENOENT => e UI.error("Found class #{plugin_util.plugin_class} but loading its template failed.") UI.error("Error is: #{e}") return end return end template_code = (HOME_TEMPLATES + plugin_name).read guardfile.binwrite(format("\n%<template>s\n", template: template_code), open_args: ["a"]) UI.info(format(INFO_TEMPLATE_ADDED, plugin_name)) rescue Errno::ENOENT fail NoSuchPlugin, plugin_name.downcase end # Adds the templates of all installed Guard implementations to an # existing Guardfile. # # @see Guard::CLI#init # def initialize_all_templates PluginUtil.plugin_names.each { |g| initialize_template(g) } end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/guardfile/evaluator.rb
lib/guard/guardfile/evaluator.rb
# frozen_string_literal: true require "guard/dsl" require "guard/ui" module Guard module Guardfile # This class is responsible for evaluating the Guardfile. It delegates to # Guard::Dsl for the actual objects generation from the Guardfile content. # # @see Guard::Dsl # class Evaluator DEFAULT_GUARDFILES = %w( guardfile.rb Guardfile ~/.Guardfile ).freeze EVALUATOR_OPTIONS = %i[guardfile inline].freeze # @private ERROR_NO_GUARDFILE = "No Guardfile found,"\ " please create one with `guard init`." attr_reader :options, :guardfile_path # @private class Error < RuntimeError end class NoGuardfileError < Error end class NoCustomGuardfile < Error end # Initializes a new Guard::Guardfile::Evaluator object. # # @option options [String] guardfile the path to a valid Guardfile # content of a valid Guardfile # def initialize(options = {}) @guardfile_path = nil @options = Options.new(options.slice(*Guard::Guardfile::Evaluator::EVALUATOR_OPTIONS)) @dsl = Dsl.new end # Evaluates the DSL methods in the `Guardfile`. # # @return Guard::Guardfile::Result # def evaluate @evaluate ||= begin dsl.evaluate(guardfile_contents, guardfile_path || "", 1) dsl.result end end # Tests if the current `Guardfile` contains a specific Guard plugin. # # @example Programmatically test if a Guardfile contains a specific Guard # plugin # # File.read('Guardfile') # => "guard :rspec" # # Guard::Guardfile::Evaluator.new.guardfile_include?('rspec') # => true # # @param [String] plugin_name the name of the Guard # @return [Boolean] whether the Guard plugin has been declared # def guardfile_include?(plugin_name) evaluate.plugin_names.include?(plugin_name.to_sym) end def custom? !!options[:guardfile] end def inline? !!options[:inline] end def guardfile_contents @guardfile_contents ||= begin _use_inline || _use_custom || _use_default [@contents, _user_config].compact.join("\n") end end private attr_reader :dsl def _use_inline return unless inline? @contents = options[:inline] end def _use_custom return unless custom? @guardfile_path, @contents = _read(Pathname.new(options[:guardfile])) rescue Errno::ENOENT fail NoCustomGuardfile, "No Guardfile exists at #{@guardfile_path}." end def _use_default DEFAULT_GUARDFILES.each do |guardfile| @guardfile_path, @contents = _read(guardfile) break rescue Errno::ENOENT if guardfile == DEFAULT_GUARDFILES.last fail NoGuardfileError, ERROR_NO_GUARDFILE end end end def _read(path) full_path = Pathname.new(path.to_s).expand_path [full_path, full_path.read] rescue Errno::ENOENT fail rescue SystemCallError => e UI.error "Error reading file #{full_path}:" UI.error e.inspect UI.error e.backtrace abort end def _user_config @_user_config ||= begin Pathname.new("~/.guard.rb").expand_path.read rescue Errno::ENOENT nil end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/ui/logger_config.rb
lib/guard/ui/logger_config.rb
# frozen_string_literal: true require "logger" require "guard/options" module Guard module UI # @private # Specific logger config. class LoggerConfig < Guard::Options DEFAULTS = { progname: "Guard", level: :info, template: ":time - :severity - :message", time_format: "%H:%M:%S", flush_seconds: 0, # Other LumberJack device-specific options # max_size: "5M", # buffer_size: 0, # additional_lines: nil, }.freeze def initialize(options = {}) super(options, DEFAULTS) end def template=(value) self["template"] = value end def level=(value) self["level"] = value end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/ui/config.rb
lib/guard/ui/config.rb
# frozen_string_literal: true require "guard/options" require "guard/ui" module Guard module UI # @private class Config < Guard::Options DEFAULTS = { only: nil, except: nil, # nil (will be whatever $stderr is later) or LumberJack device, e.g. # $stderr or 'foo.log' device: nil, }.freeze def initialize(options = {}) opts = Guard::Options.new(options, DEFAULTS) super(opts.to_hash) end def device # Use strings to work around Thor's indifferent Hash's bug fetch("device") || $stderr end def only fetch("only") end def except fetch("except") end def [](name) name = name.to_s return device if name == "device" # let Thor's Hash handle anything else super(name.to_s) end def with_progname(name) if Guard::UI.logger.respond_to?(:set_progname) Guard::UI.logger.set_progname(name) do yield if block_given? end elsif block_given? yield end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/lib/guard/ui/colors.rb
lib/guard/ui/colors.rb
# frozen_string_literal: true module Guard module UI # @private module Colors # Brighten the color ANSI_ESCAPE_BRIGHT = "1" # Black foreground color ANSI_ESCAPE_BLACK = "30" # Red foreground color ANSI_ESCAPE_RED = "31" # Green foreground color ANSI_ESCAPE_GREEN = "32" # Yellow foreground color ANSI_ESCAPE_YELLOW = "33" # Blue foreground color ANSI_ESCAPE_BLUE = "34" # Magenta foreground color ANSI_ESCAPE_MAGENTA = "35" # Cyan foreground color ANSI_ESCAPE_CYAN = "36" # White foreground color ANSI_ESCAPE_WHITE = "37" # Black background color ANSI_ESCAPE_BGBLACK = "40" # Red background color ANSI_ESCAPE_BGRED = "41" # Green background color ANSI_ESCAPE_BGGREEN = "42" # Yellow background color ANSI_ESCAPE_BGYELLOW = "43" # Blue background color ANSI_ESCAPE_BGBLUE = "44" # Magenta background color ANSI_ESCAPE_BGMAGENTA = "45" # Cyan background color ANSI_ESCAPE_BGCYAN = "46" # White background color ANSI_ESCAPE_BGWHITE = "47" end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/spec/integration_spec.rb
spec/integration_spec.rb
# frozen_string_literal: true # ------------------------------------ # # Jazzy Integration tests # # ------------------------------------ # #-----------------------------------------------------------------------------# # The following integrations tests are based on file comparison. # # 1. For each test there is a folder with a `before` and `after` subfolders. # 2. The contents of the before folder are copied to the `TMP_DIR` folder and # then the given arguments are passed to the `JAZZY_BINARY`. # 3. After the jazzy command completes the execution the each file in the # `after` subfolder is compared to the contents of the temporary # directory. If the contents of the file do not match an error is # registered. # # Notes: # # - The output of the jazzy command is saved in the `execution_output.txt` file # which should be added to the `after` folder to test the Jazzy UI. # - To create a new test, just create a before folder with the environment to # test, copy it to the after folder and run the tested pod command inside. # Then just add the tests below this files with the name of the folder and # the arguments. # # Rationale: # # - Have a way to track precisely the evolution of the artifacts (and of the # UI) produced by jazzy (git diff of the after folders). # - Allow uses to submit pull requests with the environment necessary to # reproduce an issue. # - Have robust tests which don't depend on the programmatic interface of # Jazzy. These tests depend only the binary and its arguments an thus are # suitable for testing Jazzy regardless of the implementation (they could even # work for a Swift one) #-----------------------------------------------------------------------------# # @return [Pathname] The root of the repo. # ROOT = Pathname.new(File.expand_path('..', __dir__)) unless defined? ROOT $:.unshift((ROOT + 'spec').to_s) require 'rubygems' require 'bundler/setup' require 'pretty_bacon' require 'colored2' require 'CLIntegracon' require 'cocoapods' def configure_cocoapods Pod::Config.instance.with_changes(silent: true) do Pod::Command::Setup.invoke Pod::Command::Repo::AddCDN.invoke(%w[trunk https://cdn.cocoapods.org/]) Pod::Command::Repo::Update.invoke(%w[trunk]) end end CLIntegracon.configure do |c| c.spec_path = ROOT + 'spec/integration_specs' c.temp_path = ROOT + 'tmp' # Ignore certain OSX files c.ignores '.DS_Store' c.ignores '.git' c.ignores %r{^(?!((api-)?docs(/|\z)|execution_output.txt))} c.ignores '**/*.tgz' # Remove absolute paths from output c.transform_produced '**/undocumented.json' do |path| File.write( path, File.read(path).gsub( c.temp_path.to_s, '<TMP>', ).gsub( c.spec_path.to_s, '<SPEC>', ).gsub( '/transformed', '', ), ) end # Transform produced databases to csv c.transform_produced '**/*.dsidx' do |path| File.write("#{path}.csv", `sqlite3 -header -csv #{path} "select * from searchIndex;"`) end # Now that we're comparing the CSV, we don't care about the binary c.ignores '**/*.dsidx' c.hook_into :bacon end describe_cli 'jazzy' do subject do |s| s.executable = "ruby #{ROOT + 'bin/jazzy'}" s.environment_vars = { 'JAZZY_FAKE_DATE' => 'YYYY-MM-DD', 'JAZZY_FAKE_VERSION' => 'X.X.X', 'COCOAPODS_SKIP_UPDATE_MESSAGE' => 'TRUE', 'JAZZY_INTEGRATION_SPECS' => 'TRUE', 'JAZZY_FAKE_MODULE_VERSION' => 'Y.Y.Y', } s.default_args = [] s.replace_path ROOT.to_s, 'ROOT' s.replace_pattern /^[\d\s:.-]+ ruby\[\d+:\d+\] warning:.*$\n?/, '' # Remove version numbers from CocoaPods dependencies # to make specs resilient against dependency updates. s.replace_pattern(/(Installing \w+ )\((.*)\)/, '\1(X.Y.Z)') # Xcode 13.3 etc workaround s.replace_pattern(/202[\d.:\- ]+xcodebuild.*?\n/, '') # Xcode 14 / in-proc sourcekitd workaround s.replace_pattern(/<unknown>:0: remark.*?\n/, '') # CLIntegracon 0.8 s.replace_pattern(%r{/transformed/}, '/') # Xcode 15 workaround s.replace_pattern(/objc\[.....\]: Class _?DTX\w+ is implemented in both.*?\n/, '') # arm vs. intel workaround s.replace_pattern(%r{(?<=build/)(arm64|x86_64)(?=-apple)}, '') end require 'shellwords' realm_head = <<-HTML <link rel="icon" href="https://realm.io/img/favicon.ico"> <link rel="apple-touch-icon-precomposed" sizes="57x57" href="https://realm.io/img/favicon-57x57.png" /> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://realm.io/img/favicon-114x114.png" /> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://realm.io/img/favicon-72x72.png" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://realm.io/img/favicon-144x144.png" /> <link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://realm.io/img/favicon-120x120.png" /> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://realm.io/img/favicon-152x152.png" /> <link rel="icon" type="image/png" href="https://realm.io/img/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="https://realm.io/img/favicon-16x16.png" sizes="16x16" /> <script defer> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-50247013-1', 'realm.io'); ga('send', 'pageview'); </script> HTML realm_jazzy_yaml = <<-YAML build_tool_arguments: - "-scheme" - "RealmSwift" - "SWIFT_VERSION=4.2" - "-destination" - "platform=OS X,arch=x86_64" YAML spec_subset = ENV.fetch('JAZZY_SPEC_SUBSET', nil) # rubocop:disable Style/MultilineIfModifier describe 'jazzy objective-c' do describe 'Creates Realm Objective-C docs' do realm_version = '' relative_path = 'spec/integration_specs/document_realm_objc/before' Dir.chdir(ROOT + relative_path) do realm_version = `./build.sh get-version`.chomp # jazzy will fail if it can't find all public header files `touch Realm/RLMPlatform.h` end behaves_like cli_spec 'document_realm_objc', '--objc ' \ '--author Realm ' \ '--author_url "https://realm.io" ' \ '--source-host-url ' \ 'https://github.com/realm/realm-cocoa ' \ '--source-host-files-url https://github.com/realm/' \ "realm-cocoa/tree/v#{realm_version} " \ '--module Realm ' \ "--module-version #{realm_version} " \ '--root-url https://realm.io/docs/objc/' \ "#{realm_version}/api/ " \ '--umbrella-header Realm/Realm.h ' \ '--framework-root . ' \ "--head #{realm_head.shellescape}" end describe 'Creates docs for ObjC-Swift project with a variety of contents' do base = ROOT + 'spec/integration_specs/misc_jazzy_objc_features/before' Dir.chdir(base) do sourcekitten = ROOT + 'bin/sourcekitten' sdk = `xcrun --show-sdk-path --sdk iphonesimulator`.chomp objc_args = "#{base}/MiscJazzyObjCFeatures/MiscJazzyObjCFeatures.h " \ '-- -x objective-c ' \ "-isysroot #{sdk} " \ "-I #{base} " \ '-fmodules' `#{sourcekitten} doc --objc #{objc_args} > objc.json` `#{sourcekitten} doc -- clean build > swift.json` end behaves_like cli_spec 'misc_jazzy_objc_features', '--theme fullwidth ' \ '-s objc.json,swift.json' end end if !spec_subset || spec_subset == 'objc' describe 'jazzy swift' do describe 'Creates docs with a module name, author name, project URL, ' \ 'xcodebuild options, and github info' do behaves_like cli_spec 'document_alamofire', '--skip-undocumented ' \ '--clean ' \ '--xcodebuild-arguments ' \ "-destination,'platform=OS X'" end describe 'Creates Realm Swift docs' do realm_version = '' realm_path = ROOT + 'spec/integration_specs/document_realm_swift/before' realm_jazzy_path = realm_path + '.jazzy.yaml' Dir.chdir(realm_path) do realm_version = `./build.sh get-version`.chomp end # Xcode 16 workaround File.write(realm_jazzy_path, realm_jazzy_yaml) behaves_like cli_spec 'document_realm_swift', '--author Realm ' \ '--author_url "https://realm.io" ' \ '--source-host-url ' \ 'https://github.com/realm/realm-cocoa ' \ '--source-host-files-url https://github.com/realm/' \ "realm-cocoa/tree/v#{realm_version} " \ '--module RealmSwift ' \ "--module-version #{realm_version} " \ '--root-url https://realm.io/docs/swift/' \ "#{realm_version}/api/ " \ "--head #{realm_head.shellescape}" FileUtils.rm_rf realm_jazzy_path end describe 'Creates Siesta docs' do # Siesta already has Docs/ # Use the default Swift version rather than the specified 4.0 behaves_like cli_spec 'document_siesta', '--output api-docs ' \ '--swift-version= ' end describe 'Creates docs for Swift project with a variety of contents' do behaves_like cli_spec 'misc_jazzy_features' end describe 'Creates docs for Swift project from a .swiftmodule' do build_path = Dir.getwd + '/tmp/.build' package_path = ROOT + 'spec/integration_specs/misc_jazzy_symgraph_features/before' `swift build --package-path #{package_path} --scratch-path #{build_path}` module_path = `swift build --scratch-path #{build_path} --show-bin-path` behaves_like cli_spec 'misc_jazzy_symgraph_features', '--swift-build-tool symbolgraph ' \ '--build-tool-arguments ' \ '-emit-extension-block-symbols,-I,' \ "#{module_path.chomp}/Modules" end describe 'Creates docs for a multiple-module project' do behaves_like cli_spec 'jazzy_multi_modules' end end if !spec_subset || spec_subset == 'swift' describe 'jazzy cocoapods' do # Xcode 14.3 workaround, special podspec podspec_patch = ROOT + 'spec/Moya.podspec' podspec_used = ROOT + 'spec/integration_specs/document_moya_podspec/before/Moya.podspec' podspec_save = ROOT + 'spec/Moya.podspec.safe' FileUtils.cp_r podspec_used, podspec_save, remove_destination: true FileUtils.cp_r podspec_patch, podspec_used, remove_destination: true configure_cocoapods describe 'Creates docs for a podspec with dependencies and subspecs' do behaves_like cli_spec 'document_moya_podspec', '--podspec=Moya.podspec' end FileUtils.cp_r podspec_save, podspec_used, remove_destination: true FileUtils.rm_rf podspec_save end if !spec_subset || spec_subset == 'cocoapods' # rubocop:enable Style/MultilineIfModifier end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require 'rubygems' require 'bundler/setup' require 'bacon' require 'mocha-on-bacon' require 'pretty_bacon' require 'pathname' ROOT = Pathname.new(File.expand_path('..', __dir__)) $LOAD_PATH.unshift((ROOT + 'lib').to_s) $LOAD_PATH.unshift((ROOT + 'spec').to_s) require 'jazzy' require 'spec_helper/pre_flight' Bacon.summary_at_exit module Bacon class Context include Jazzy::Config::Mixin def temporary_directory SpecHelper.temporary_directory end end end Mocha::Configuration.prevent(:stubbing_non_existent_method) module SpecHelper def self.temporary_directory ROOT + 'tmp' end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/spec/spec_helper/pre_flight.rb
spec/spec_helper/pre_flight.rb
# frozen_string_literal: true # Restores the config to the default state before each requirement module Bacon class Context old_run_requirement = instance_method(:run_requirement) define_method(:run_requirement) do |description, spec| temporary_directory = SpecHelper.temporary_directory ::Jazzy::Config.instance = nil ::Jazzy::Config.instance.tap do |c| c.source_directory = temporary_directory end temporary_directory.rmtree if temporary_directory.exist? temporary_directory.mkpath old_run_requirement.bind(self).call(description, spec) end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy.rb
lib/jazzy.rb
# frozen_string_literal: true require 'jazzy/config' require 'jazzy/doc_builder' Encoding.default_external = Encoding::UTF_8
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/executable.rb
lib/jazzy/executable.rb
# frozen_string_literal: true module Jazzy module Executable class IO < Array def initialize(io = nil) super() @io = io end def <<(value) super ensure @io << value.to_s if @io end def to_s join("\n") end end class << self def execute_command(executable, args, raise_on_failure, env: {}) require 'shellwords' bin = `which #{executable.to_s.shellescape}`.strip raise "Unable to locate the executable `#{executable}`" if bin.empty? require 'open4' stdout = IO.new stderr = IO.new($stderr) options = { stdout: stdout, stderr: stderr, status: true } status = Open4.spawn(env, bin, *args, options) unless status.success? full_command = "#{bin.shellescape} #{args.map(&:shellescape)}" output = stdout.to_s << stderr.to_s if raise_on_failure raise "#{full_command}\n\n#{output}" else warn("[!] Failed: #{full_command}") end end [stdout.to_s, status] end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/jazzy_markdown.rb
lib/jazzy/jazzy_markdown.rb
# frozen_string_literal: true require 'redcarpet' require 'rouge' require 'rouge/plugins/redcarpet' module Jazzy module Markdown # Publish if generated HTML needs math support class << self; attr_accessor :has_math; end module Footnotes # Global unique footnote ID def self.next_footnote @next_footnote ||= 0 @next_footnote += 1 end # Per-render map from user to global ID attr_accessor :footnotes_hash def reset @footnotes_hash = {} end def map_footnote(user_num) footnotes_hash.fetch(user_num) do footnotes_hash[user_num] = Footnotes.next_footnote end end def footnote_ref(num) mapped = map_footnote(num) "<span class='footnote-ref' id=\"fnref#{mapped}\">" \ "<sup><a href=\"#fn#{mapped}\">#{num}</a></sup></span>" end # follow native redcarpet: backlink goes before the first </p> tag def footnote_def(text, num) mapped = map_footnote(num) "\n<li><div class='footnote-def' id=\"fn#{mapped}\">" + text.sub(%r{(?=</p>)}, "&nbsp;<a href=\"#fnref#{mapped}\">&#8617;</a>") + '</div></li>' end end # rubocop:disable Metrics/ClassLength class JazzyHTML < Redcarpet::Render::HTML include Redcarpet::Render::SmartyPants include Rouge::Plugins::Redcarpet include Footnotes attr_accessor :default_language def header(text, header_level) text_slug = text.gsub(/[^[[:word:]]]+/, '-') .downcase .sub(/^-/, '') .sub(/-$/, '') "<h#{header_level} id='#{text_slug}' class='heading'>" \ "#{text}" \ "</h#{header_level}>\n" end def codespan(text) case text when /^\$\$(.*)\$\$$/m o = ["</p><div class='math m-block'>", Regexp.last_match[1], '</div><p>'] Markdown.has_math = true when /^\$(.*)\$$/m o = ["<span class='math m-inline'>", Regexp.last_match[1], '</span>'] Markdown.has_math = true else o = ['<code>', text.to_s, '</code>'] end o[0] + CGI.escapeHTML(o[1]) + o[2] end # List from # https://github.com/apple/swift/blob/master/include/swift/Markup/SimpleFields.def UNIQUELY_HANDLED_CALLOUTS = %w[parameters parameter returns].freeze GENERAL_CALLOUTS = %w[attention author authors bug complexity copyright date experiment important invariant keyword mutatingvariant nonmutatingvariant note postcondition precondition recommended recommendedover remark remarks requires see seealso since todo throws version warning].freeze SPECIAL_LIST_TYPES = (UNIQUELY_HANDLED_CALLOUTS + GENERAL_CALLOUTS).freeze SPECIAL_LIST_TYPE_REGEX = %r{ \A\s* # optional leading spaces (<p>\s*)? # optional opening p tag # any one of our special list types (#{SPECIAL_LIST_TYPES.map(&Regexp.method(:escape)).join('|')}) [\s:] # followed by either a space or a colon }ix.freeze ELIDED_LI_TOKEN = '7wNVzLB0OYPL2eGlPKu8q4vITltqh0Y6DPZf659TPMAeYh49o' def list_item(text, _list_type) if text =~ SPECIAL_LIST_TYPE_REGEX type = Regexp.last_match(2) if UNIQUELY_HANDLED_CALLOUTS.include? type.downcase return ELIDED_LI_TOKEN end return render_list_aside(type, text.sub(/#{Regexp.escape(type)}:\s+/, '')) end "<li>#{text.strip}</li>\n" end def render_list_aside(type, text) "</ul>#{render_aside(type, text).chomp}<ul>\n" end def render_aside(type, text) <<-HTML <div class="aside aside-#{type.underscore.tr('_', '-')}"> <p class="aside-title">#{type.underscore.humanize}</p> #{text} </div> HTML end def list(text, list_type) elided = text.gsub!(ELIDED_LI_TOKEN, '') return if text =~ /\A\s*\Z/ && elided tag = list_type == :ordered ? 'ol' : 'ul' "\n<#{tag}>\n#{text}</#{tag}>\n" .gsub(%r{\n?<ul>\n?</ul>}, '') end # List from # https://developer.apple.com/documentation/xcode/formatting-your-documentation-content#Add-Notes-and-Other-Asides DOCC_CALLOUTS = %w[note important warning tip experiment].freeze DOCC_CALLOUT_REGEX = %r{ \A\s* # optional leading spaces (?:<p>\s*)? # optional opening p tag # any one of the callout names (#{DOCC_CALLOUTS.map(&Regexp.method(:escape)).join('|')}) : # followed directly by a colon }ix.freeze def block_quote(html) if html =~ DOCC_CALLOUT_REGEX type = Regexp.last_match[1] render_aside(type, html.sub(/#{Regexp.escape(type)}:\s*/, '')) else "\n<blockquote>\n#{html}</blockquote>\n" end end def block_code(code, language) super(code, language || default_language) end def rouge_formatter(lexer) Highlighter::Formatter.new(lexer.tag) end end # rubocop:enable Metrics/ClassLength REDCARPET_OPTIONS = { autolink: true, fenced_code_blocks: true, no_intra_emphasis: true, strikethrough: true, space_after_headers: false, tables: true, lax_spacing: true, footnotes: true, }.freeze # Spot and capture returns & param HTML for separate display. class JazzyDeclarationHTML < JazzyHTML attr_reader :returns, :parameters def reset @returns = nil @parameters = {} super end INTRO_PAT = '\A(?<intro>\s*(<p>\s*)?)' OUTRO_PAT = '(?<outro>.*)\z' RETURNS_REGEX = /#{INTRO_PAT}returns:#{OUTRO_PAT}/im.freeze IDENT_PAT = '(?<param>\S+)' # Param formats: normal swift, objc via sourcekitten, and # possibly inside 'Parameters:' PARAM_PAT1 = "(parameter +#{IDENT_PAT}\\s*:)" PARAM_PAT2 = "(parameter:\\s*#{IDENT_PAT}\\s+)" PARAM_PAT3 = "(#{IDENT_PAT}\\s*:)" PARAM_PAT = "(?:#{PARAM_PAT1}|#{PARAM_PAT2}|#{PARAM_PAT3})" PARAM_REGEX = /#{INTRO_PAT}#{PARAM_PAT}#{OUTRO_PAT}/im.freeze def list_item(text, _list_type) if text =~ RETURNS_REGEX @returns = render_param_returns(Regexp.last_match) elsif text =~ PARAM_REGEX @parameters[Regexp.last_match(:param)] = render_param_returns(Regexp.last_match) end super end def render_param_returns(matches) body = matches[:intro].strip + matches[:outro].strip body = "<p>#{body}</p>" unless body.start_with?('<p>') # call smartypants for pretty quotes etc. postprocess(body) end end def self.renderer @renderer ||= JazzyDeclarationHTML.new end def self.markdown @markdown ||= Redcarpet::Markdown.new(renderer, REDCARPET_OPTIONS) end # Produces <p>-delimited block content def self.render(markdown_text, default_language = nil) renderer.reset renderer.default_language = default_language markdown.render(markdown_text) end # Produces <span>-delimited inline content def self.render_inline(markdown_text, default_language = nil) render(markdown_text, default_language) .sub(%r{^<p>(.*)</p>$}, '<span>\1</span>') end def self.rendered_returns renderer.returns end def self.rendered_parameters renderer.parameters end class JazzyCopyright < Redcarpet::Render::HTML def link(link, _title, content) %(<a class="link" href="#{link}" target="_blank" \ rel="external noopener">#{content}</a>) end end def self.copyright_markdown @copyright_markdown ||= Redcarpet::Markdown.new( JazzyCopyright, REDCARPET_OPTIONS, ) end def self.render_copyright(markdown_text) copyright_markdown.render(markdown_text) end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/highlighter.rb
lib/jazzy/highlighter.rb
# frozen_string_literal: true require 'rouge' module Jazzy # This module helps highlight code module Highlighter SWIFT = 'swift' OBJC = 'objective_c' class Formatter < Rouge::Formatters::HTML def initialize(language) @language = language super() end def stream(tokens, &block) yield "<pre class=\"highlight #{@language}\"><code>" super yield "</code></pre>\n" end end def self.highlight_swift(source) highlight(source, SWIFT) end def self.highlight_objc(source) highlight(source, OBJC) end def self.highlight(source, language) source && Rouge.highlight(source, language, Formatter.new(language)) end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_document.rb
lib/jazzy/source_document.rb
# frozen_string_literal: true require 'pathname' require 'jazzy/jazzy_markdown' module Jazzy # Standalone markdown docs including index.html class SourceDocument < SourceDeclaration attr_accessor :overview attr_accessor :readme_path def initialize super self.children = [] self.parameters = [] self.abstract = '' self.type = SourceDeclaration::Type.markdown self.mark = SourceMark.new end def self.make_index(readme_path) SourceDocument.new.tap do |sd| sd.name = 'index' sd.url = sd.name + '.html' sd.readme_path = readme_path end end def readme? url == 'index.html' end def render_as_page? true end def omit_content_from_parent? true end def config Config.instance end def url_name name.downcase.strip.tr(' ', '-').gsub(/[^[[:word:]]-]/, '') end def content(source_module) return readme_content(source_module) if name == 'index' overview end def readme_content(source_module) config_readme || fallback_readme || generated_readme(source_module) end def config_readme readme_path.read if readme_path&.exist? end def fallback_readme %w[README.md README.markdown README.mdown README].each do |potential_name| file = config.source_directory + potential_name return file.read if file.exist? end false end def generated_readme(source_module) if podspec = config.podspec ### License # <a href="#{license[:url]}">#{license[:license]}</a> <<-README # #{podspec.name} ### #{podspec.summary} #{podspec.description} ### Installation ```ruby pod '#{podspec.name}' ``` ### Authors #{source_module.author_name} README else <<-README # #{source_module.readme_title} ### Authors #{source_module.author_name} README end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/docset_builder.rb
lib/jazzy/docset_builder.rb
# frozen_string_literal: true require 'mustache' require 'sqlite3' module Jazzy module DocBuilder # Follows the instructions found at https://kapeli.com/docsets#dashDocset. class DocsetBuilder include Config::Mixin attr_reader :output_dir attr_reader :generated_docs_dir attr_reader :source_module attr_reader :docset_dir attr_reader :documents_dir attr_reader :name def initialize(generated_docs_dir) @name = config.docset_title || config.module_names.first docset_path = config.docset_path || "docsets/#{safe_name}.docset" @docset_dir = generated_docs_dir + docset_path @generated_docs_dir = generated_docs_dir @output_dir = docset_dir.parent @documents_dir = docset_dir + 'Contents/Resources/Documents/' end def build!(all_declarations) docset_dir.rmtree if docset_dir.exist? copy_docs copy_icon if config.docset_icon write_plist create_index(all_declarations) create_archive create_xml if config.version && config.root_url end private def safe_name name.gsub(/[^a-z0-9_-]+/i, '_') end def write_plist info_plist_path = docset_dir + 'Contents/Info.plist' info_plist_path.open('w') do |plist| template = Pathname(__dir__) + 'docset_builder/info_plist.mustache' plist << Mustache.render( template.read, lowercase_name: name.downcase, lowercase_safe_name: safe_name.downcase, name: name, root_url: config.root_url, playground_url: config.docset_playground_url, ) end end def create_archive target = "#{safe_name}.tgz" source = docset_dir.basename.to_s options = { chdir: output_dir.to_s, [1, 2] => '/dev/null', # silence all output from `tar` } system('tar', "--exclude='.DS_Store'", '-cvzf', target, source, options) end def copy_docs files_to_copy = Pathname.glob(generated_docs_dir + '*') - [docset_dir, output_dir] FileUtils.mkdir_p documents_dir FileUtils.cp_r files_to_copy, documents_dir end def copy_icon FileUtils.cp config.docset_icon, docset_dir + 'icon.png' end def create_index(all_declarations) search_index_path = docset_dir + 'Contents/Resources/docSet.dsidx' SQLite3::Database.new(search_index_path.to_s) do |db| db.execute('CREATE TABLE searchIndex(' \ 'id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);') db.execute('CREATE UNIQUE INDEX anchor ON ' \ 'searchIndex (name, type, path);') all_declarations.select(&:type).each do |doc| db.execute('INSERT OR IGNORE INTO searchIndex(name, type, path) ' \ 'VALUES (?, ?, ?);', [doc.name, doc.type.dash_type, doc.filepath]) end end end def create_xml (output_dir + "#{safe_name}.xml").open('w') do |xml| url = URI.join(config.root_url, "docsets/#{safe_name}.tgz") xml << "<entry><version>#{config.version}</version><url>#{url}" \ "</url></entry>\n" end end # The web URL where the user intends to place the docset XML file. def dash_url return nil unless config.dash_url || config.root_url config.dash_url || URI.join( config.root_url, "docsets/#{safe_name}.xml", ) end public # The dash-feed:// URL that links from the Dash icon in generated # docs. This is passed to the Dash app and encodes the actual web # `dash_url` where the user has placed the XML file. # # Unfortunately for historical reasons this is *also* called the # 'dash_url' where it appears in mustache templates and so on. def dash_feed_url dash_url&.then do |url| "dash-feed://#{ERB::Util.url_encode(url.to_s)}" end end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/sourcekitten.rb
lib/jazzy/sourcekitten.rb
# frozen_string_literal: true require 'json' require 'pathname' require 'shellwords' require 'xcinvoke' require 'cgi' require 'rexml/document' require 'jazzy/config' require 'jazzy/executable' require 'jazzy/highlighter' require 'jazzy/source_declaration' require 'jazzy/source_mark' require 'jazzy/stats' require 'jazzy/grouper' require 'jazzy/doc_index' ELIDED_AUTOLINK_TOKEN = '36f8f5912051ae747ef441d6511ca4cb' def autolink_regex(middle_regex, after_highlight) start_tag_re, end_tag_re = if after_highlight [/<span class="(?:n|kt|kd|nc)">/, '</span>'] else ['<code>', '</code>'] end /(#{start_tag_re})[ \t]*(#{middle_regex})[ \t]*(#{end_tag_re})/ end class String def autolink_block(doc_url, middle_regex, after_highlight) gsub(autolink_regex(middle_regex, after_highlight)) do original = Regexp.last_match(0) start_tag, raw_name, end_tag = Regexp.last_match.captures link_target, display_name = yield(CGI.unescape_html(raw_name)) if link_target && !link_target.type.extension? && link_target.url && link_target.url != doc_url.split('#').first && # Don't link to parent link_target.url != doc_url # Don't link to self "#{start_tag}<a href=\"#{ELIDED_AUTOLINK_TOKEN}#{link_target.url}\">" \ "#{CGI.escape_html(display_name)}</a>#{end_tag}" else original end end end def unindent(count) gsub(/^#{' ' * count}/, '') end end module Jazzy # This module interacts with the sourcekitten command-line executable module SourceKitten def self.undocumented_abstract @undocumented_abstract ||= Markdown.render( Config.instance.undocumented_text, ).freeze end # # URL assignment # def self.sanitize_filename(doc) unsafe_filename = doc.docs_filename sanitzation_enabled = Config.instance.use_safe_filenames if sanitzation_enabled && !doc.type.name_controlled_manually? CGI.escape(unsafe_filename).gsub('_', '%5F').tr('%', '_') else unsafe_filename end end # rubocop:disable Metrics/MethodLength # Generate doc URL by prepending its parents' URLs # @return [Hash] input docs with URLs def self.make_doc_urls(docs) docs.each do |doc| if doc.render_as_page? doc.url = ( subdir_for_doc(doc) + [sanitize_filename(doc) + '.html'] ).map { |path| ERB::Util.url_encode(path) }.join('/') doc.children = make_doc_urls(doc.children) else # Don't create HTML page for this doc if it doesn't have children # Instead, make its link a hash-link on its parent's page if doc.typename == '<<error type>>' warn "A compile error prevented #{doc.fully_qualified_name} " \ 'from receiving a unique USR. Documentation may be ' \ 'incomplete. Please check for compile errors by running ' \ '`xcodebuild` or `swift build` with arguments ' \ "`#{Config.instance.build_tool_arguments.shelljoin}`." end id = doc.usr unless id id = doc.name || 'unknown' warn "`#{id}` has no USR. First make sure all modules used in " \ 'your project have been imported. If all used modules are ' \ 'imported, please report this problem by filing an issue at ' \ 'https://github.com/realm/jazzy/issues along with your ' \ 'Xcode project. If this token is declared in an `#if` block, ' \ 'please ignore this message.' end doc.url = "#{doc.parent_in_docs.url}#/#{id}" end end end # rubocop:enable Metrics/MethodLength # Determine the subdirectory in which a doc should be placed. # Guides in the root for back-compatibility. # Declarations under outer namespace type (Structures, Classes, etc.) def self.subdir_for_doc(doc) if Config.instance.multiple_modules? subdir_for_doc_multi_module(doc) else # Back-compatibility layout version subdir_for_doc_single_module(doc) end end # Pre-multi-module site layout, does not allow for # types with the same name. def self.subdir_for_doc_single_module(doc) # Guides + Groups in the root return [] if doc.type.markdown? || doc.type.overview? [doc.namespace_path.first.type.plural_url_name] + doc.namespace_ancestors.map(&:name) end # Multi-module site layout, separate each module that # is being documented. def self.subdir_for_doc_multi_module(doc) # Guides + Groups in the root return [] if doc.type.markdown? || doc.type.overview? root_decl = doc.namespace_path.first # Extensions need an extra dir to allow for extending # ExternalModule1.TypeName and ExternalModule2.TypeName namespace_subdir = if root_decl.type.swift_extension? ['Extensions', root_decl.module_name] else [doc.namespace_path.first.type.plural_url_name] end [root_decl.doc_module_name] + namespace_subdir + doc.namespace_ancestors.map(&:name) end # # CLI argument calculation # # returns all subdirectories of specified path def self.rec_path(path) path.children.collect do |child| if child.directory? rec_path(child) + [child] end end.select { |x| x }.flatten(1) end def self.use_spm?(module_config) module_config.swift_build_tool == :spm || (!module_config.swift_build_tool_configured && Dir['*.xcodeproj', '*.xcworkspace'].empty? && !module_config.build_tool_arguments.include?('-project') && !module_config.build_tool_arguments.include?('-workspace')) end # Builds SourceKitten arguments based on Jazzy options def self.arguments_from_options(module_config) arguments = ['doc'] if module_config.objc_mode arguments += objc_arguments_from_options(module_config) else arguments += ['--spm'] if use_spm?(module_config) unless module_config.module_name.empty? arguments += ['--module-name', module_config.module_name] end arguments += ['--'] end arguments + module_config.build_tool_arguments end def self.objc_arguments_from_options(module_config) arguments = [] if module_config.build_tool_arguments.empty? arguments += ['--objc', module_config.umbrella_header.to_s, '--', '-x', 'objective-c', '-isysroot', `xcrun --show-sdk-path --sdk #{module_config.sdk}`.chomp, '-I', module_config.framework_root.to_s, '-fmodules'] end # add additional -I arguments for each subdirectory of framework_root unless module_config.framework_root.nil? rec_path(Pathname.new(module_config.framework_root.to_s)).collect do |child| if child.directory? arguments += ['-I', child.to_s] end end end arguments end # Run sourcekitten with given arguments and return STDOUT def self.run_sourcekitten(arguments) if swift_version = Config.instance.swift_version unless xcode = XCInvoke::Xcode.find_swift_version(swift_version) raise "Unable to find an Xcode with swift version #{swift_version}." end env = xcode.as_env else env = ENV end bin_path = Pathname(__FILE__) + '../../../bin/sourcekitten' output, = Executable.execute_command(bin_path, arguments, true, env: env) output end # # SourceDeclaration generation # def self.make_default_doc_info(declaration) # @todo: Fix these declaration.abstract = '' declaration.parameters = [] declaration.children = [] end def self.attribute?(doc, attr_name) doc['key.attributes']&.find do |attribute| attribute['key.attribute'] == "source.decl.attribute.#{attr_name}" end end def self.availability_attribute?(doc) attribute?(doc, 'available') end def self.spi_attribute?(doc) attribute?(doc, '_spi') end def self.should_document?(doc) return false if doc['key.doc.comment'].to_s.include?(':nodoc:') type = SourceDeclaration::Type.new(doc['key.kind']) # Always document Objective-C declarations. return true unless type.swift_type? # Don't document Swift types if we are hiding Swift return false if Config.instance.hide_swift? # Don't document @available declarations with no USR, since it means # they're unavailable. if availability_attribute?(doc) && !doc['key.usr'] return false end # Only document @_spi declarations in some scenarios return false unless should_document_spi?(doc) # Don't document declarations excluded by the min_acl setting if type.swift_extension? should_document_swift_extension?(doc) else should_document_acl?(type, doc) end end # Check visibility: SPI def self.should_document_spi?(doc) spi_ok = @min_acl < SourceDeclaration::AccessControlLevel.public || Config.instance.include_spi_declarations || (!spi_attribute?(doc) && !doc['key.symgraph_spi']) @stats.add_spi_skipped unless spi_ok spi_ok end # Check visibility: access control def self.should_document_acl?(type, doc) # Include all enum elements for now, can't tell their ACL. return true if type.swift_enum_element? acl_ok = SourceDeclaration::AccessControlLevel.from_doc(doc) >= @min_acl unless acl_ok @stats.add_acl_skipped @inaccessible_protocols.append(doc['key.name']) if type.swift_protocol? end acl_ok end # Document extensions if they add protocol conformances, or have any # member that needs to be documented. def self.should_document_swift_extension?(doc) doc['key.inheritedtypes'] || Array(doc['key.substructure']).any? do |subdoc| subtype = SourceDeclaration::Type.new(subdoc['key.kind']) !subtype.mark? && should_document?(subdoc) end end def self.process_undocumented_token(doc, declaration) make_default_doc_info(declaration) if declaration.mark_undocumented? @stats.add_undocumented(declaration) return nil if @skip_undocumented declaration.abstract = undocumented_abstract else declaration.abstract = Markdown.render(doc['key.doc.comment'] || '', declaration.highlight_language) end declaration end def self.parameters(doc, discovered) (doc['key.doc.parameters'] || []).map do |p| name = p['name'] { name: name, discussion: discovered[name], } end.reject { |param| param[:discussion].nil? } end def self.make_doc_info(doc, declaration) return unless should_document?(doc) highlight_declaration(doc, declaration) make_deprecation_info(doc, declaration) unless doc['key.doc.full_as_xml'] return process_undocumented_token(doc, declaration) end declaration.abstract = Markdown.render(doc['key.doc.comment'] || '', declaration.highlight_language) declaration.discussion = '' declaration.return = Markdown.rendered_returns declaration.parameters = parameters(doc, Markdown.rendered_parameters) @stats.add_documented end def self.highlight_declaration(doc, declaration) if declaration.swift? declaration.declaration = Highlighter.highlight_swift(make_swift_declaration(doc, declaration)) else declaration.declaration = Highlighter.highlight_objc( make_objc_declaration(doc['key.parsed_declaration']), ) declaration.other_language_declaration = Highlighter.highlight_swift(doc['key.swift_declaration']) end end def self.make_deprecation_info(doc, declaration) if declaration.deprecated declaration.deprecation_message = Markdown.render(doc['key.deprecation_message'] || '') end if declaration.unavailable declaration.unavailable_message = Markdown.render(doc['key.unavailable_message'] || '') end end # Strip tags and convert entities def self.xml_to_text(xml) document = REXML::Document.new(xml) REXML::XPath.match(document.root, '//text()').map(&:value).join rescue StandardError '' end # Regexp to match an @attribute. Complex to handle @available(). def self.attribute_regexp(name) qstring = /"(?:[^"\\]*|\\.)*"/ %r{@#{name} # @attr name (?:\s*\( # optionally followed by spaces + parens, (?: # containing any number of either.. [^")]*| # normal characters or... #{qstring} # quoted strings. )* # (end parens content) \))? # (end optional parens) }x end # Get all attributes of some name def self.extract_attributes(declaration, name = '\w+') attrs = declaration.scan(attribute_regexp(name)) # Rouge #806 workaround, use unicode lookalike for ')' inside attributes. attrs.map { |str| str.gsub(/\)(?!\s*$)/, "\ufe5a") } end # Keep everything except instructions to us def self.extract_documented_attributes(declaration) extract_attributes(declaration).reject do |attr| attr.start_with?('@_documentation') end end def self.extract_availability(declaration) extract_attributes(declaration, 'available') end # Split leading attributes from a decl, returning both parts. def self.split_decl_attributes(declaration) declaration =~ /^((?:#{attribute_regexp('\w+')}\s*)*)(.*)$/m Regexp.last_match.captures end def self.prefer_parsed_decl?(parsed, annotated, type) return true if annotated.empty? return false unless parsed return false if type.swift_variable? # prefer { get }-style annotated.include?(' = default') || # SR-2608 (parsed.scan(/@autoclosure|@escaping/).count > annotated.scan(/@autoclosure|@escaping/).count) || # SR-6321 parsed.include?("\n") # user formatting end # Apply fixes to improve the compiler's declaration def self.fix_up_compiler_decl(annotated_decl, declaration) annotated_decl. # Replace the fully qualified name of a type with its base name gsub(declaration.fully_qualified_name_regexp, declaration.name). # Workaround for SR-9816 gsub(" {\n get\n }", ''). # Workaround for SR-12139 gsub(/mutating\s+mutating/, 'mutating') end # Find the best Swift declaration def self.make_swift_declaration(doc, declaration) # From compiler 'quick help' style annotated_decl_xml = doc['key.annotated_decl'] return nil unless annotated_decl_xml annotated_decl_attrs, annotated_decl_body = split_decl_attributes(xml_to_text(annotated_decl_xml)) # From source code parsed_decl = doc['key.parsed_declaration'] # Don't present type attributes on extensions return parsed_decl if declaration.type.extension? decl = if prefer_parsed_decl?(parsed_decl, annotated_decl_body, declaration.type) # Strip any attrs captured by parsed version inline_attrs, parsed_decl_body = split_decl_attributes(parsed_decl) parsed_decl_body.unindent(inline_attrs.length) else # Improve the compiler declaration fix_up_compiler_decl(annotated_decl_body, declaration) end # @available attrs only in compiler 'interface' style extract_availability(doc['key.doc.declaration'] || '') .concat(extract_documented_attributes(annotated_decl_attrs)) .concat(fabricate_spi_attributes(doc, annotated_decl_attrs)) .push(decl) .join("\n") end # Swift 6 workaround: @_spi attribute & SPI group missing def self.fabricate_spi_attributes(doc, attrs) return [] unless spi_attribute?(doc) return [] if attrs =~ /@_spi/ ['@_spi(<<unknown>>)'] end # Exclude non-async routines that accept async closures def self.swift_async?(fully_annotated_decl) document = REXML::Document.new(fully_annotated_decl) !document.elements['/*/syntaxtype.keyword[text()="async"]'].nil? rescue StandardError nil end # Strip default property attributes because libclang # adds them all, even if absent in the original source code. DEFAULT_ATTRIBUTES = %w[atomic readwrite assign unsafe_unretained].freeze def self.make_objc_declaration(declaration) return declaration if Config.instance.keep_property_attributes declaration =~ /\A@property\s+\((.*?)\)/ return declaration unless Regexp.last_match attrs = Regexp.last_match[1].split(',').map(&:strip) - DEFAULT_ATTRIBUTES attrs_text = attrs.empty? ? '' : " (#{attrs.join(', ')})" declaration .sub(/(?<=@property)\s+\(.*?\)/, attrs_text) .gsub(/\s+/, ' ') end def self.make_substructure(doc, declaration) return [] unless subdocs = doc['key.substructure'] make_source_declarations(subdocs, declaration, declaration.mark_for_children) end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/CyclomaticComplexity # rubocop:disable Metrics/PerceivedComplexity def self.make_source_declarations(docs, parent = nil, mark = SourceMark.new) declarations = [] current_mark = mark Array(docs).each do |doc| if doc.key?('key.diagnostic_stage') declarations += make_source_declarations( doc['key.substructure'], parent ) next end declaration = SourceDeclaration.new declaration.parent_in_code = parent declaration.type = SourceDeclaration::Type.new(doc['key.kind'], doc['key.fully_annotated_decl']) declaration.typename = doc['key.typename'] declaration.objc_name = doc['key.name'] documented_name = if Config.instance.hide_objc? && doc['key.swift_name'] doc['key.swift_name'] else declaration.objc_name end if declaration.type.task_mark?(documented_name) current_mark = SourceMark.new(documented_name) end if declaration.type.swift_enum_case? # Enum "cases" are thin wrappers around enum "elements". declarations += make_source_declarations( doc['key.substructure'], parent, current_mark ) next end next unless declaration.type.should_document? unless declaration.type.name raise 'Please file an issue at ' \ 'https://github.com/realm/jazzy/issues about adding support ' \ "for `#{declaration.type.kind}`." end unless documented_name warn 'Found a declaration without `key.name` that will be ' \ 'ignored. Documentation may be incomplete. This is probably ' \ 'caused by unresolved compiler errors: check the sourcekitten ' \ 'output for error messages.' next end declaration.file = Pathname(doc['key.filepath']) if doc['key.filepath'] declaration.usr = doc['key.usr'] declaration.type_usr = doc['key.typeusr'] declaration.module_name = if declaration.swift? # Filter out Apple sub-framework implementation names doc['key.modulename']&.sub(/\..*$/, '') else # ObjC best effort, category original module is unavailable @current_module_name end declaration.doc_module_name = @current_module_name declaration.name = documented_name declaration.mark = current_mark declaration.access_control_level = SourceDeclaration::AccessControlLevel.from_doc(doc) declaration.line = doc['key.doc.line'] || doc['key.line'] declaration.column = doc['key.doc.column'] || doc['key.column'] declaration.start_line = doc['key.parsed_scope.start'] declaration.end_line = doc['key.parsed_scope.end'] declaration.deprecated = doc['key.always_deprecated'] declaration.unavailable = doc['key.always_unavailable'] declaration.generic_requirements = find_generic_requirements(doc['key.parsed_declaration']) inherited_types = doc['key.inheritedtypes'] || [] declaration.inherited_types = inherited_types.map { |type| type['key.name'] }.compact declaration.async = doc['key.symgraph_async'] || if xml_declaration = doc['key.fully_annotated_decl'] swift_async?(xml_declaration) end next unless make_doc_info(doc, declaration) declaration.children = make_substructure(doc, declaration) next if declaration.type.extension? && declaration.children.empty? && !declaration.inherited_types? declarations << declaration end declarations end # rubocop:enable Metrics/PerceivedComplexity # rubocop:enable Metrics/CyclomaticComplexity # rubocop:enable Metrics/MethodLength def self.find_generic_requirements(parsed_declaration) parsed_declaration =~ /\bwhere\s+(.*)$/m return nil unless Regexp.last_match Regexp.last_match[1].gsub(/\s+/, ' ') end # # SourceDeclaration generation - extension management # # Expands extensions of nested types declared at the top level into # a tree so they can be deduplicated properly def self.expand_extensions(decls) decls.map do |decl| next decl unless decl.type.extension? && decl.name.include?('.') # Don't expand the Swift namespace if we're in ObjC mode. # ex: NS_SWIFT_NAME(Foo.Bar) should not create top-level Foo next decl if decl.swift_objc_extension? && !Config.instance.hide_objc? name_parts = decl.name.split('.') decl.name = name_parts.pop expand_extension(decl, name_parts, decls) end end def self.expand_extension(extension, name_parts, decls) return extension if name_parts.empty? name = name_parts.shift candidates = decls.select { |decl| decl.name == name } SourceDeclaration.new.tap do |decl| make_default_doc_info(decl) decl.name = name decl.module_name = extension.module_name decl.doc_module_name = extension.doc_module_name decl.type = extension.type decl.mark = extension.mark decl.usr = candidates.first.usr unless candidates.empty? child = expand_extension(extension, name_parts, candidates.flat_map(&:children).uniq) child.parent_in_code = decl decl.children = [child] end end # Merges multiple extensions of the same entity into a single document. # # Merges extensions into the protocol/class/struct/enum they extend, if it # occurs in the same project. # # Merges redundant declarations when documenting podspecs. def self.deduplicate_declarations(declarations) duplicate_groups = declarations .group_by { |d| deduplication_key(d, declarations) } .values duplicate_groups.flat_map do |group| # Put extended type (if present) before extensions merge_declarations(group) end.compact end # Returns true if an Objective-C declaration is mergeable. def self.mergeable_objc?(decl, root_decls) decl.type.objc_class? || (decl.type.objc_category? && (category_classname = decl.objc_category_name[0]) && root_decls.any? { |d| d.name == category_classname }) end # Returns if a Swift declaration is mergeable. # Start off merging in typealiases to help understand extensions. def self.mergeable_swift?(decl) decl.type.swift_extensible? || decl.type.swift_extension? || decl.type.swift_typealias? end # Normally merge all extensions into their types and each other. # # :none means only merge within a module -- so two extensions to # some type get merged, but an extension to a type from # another documented module does not get merged into that type # :extensions means extensions of documented modules get merged, # but if we're documenting ModA and ModB, and they both provide # extensions to Swift.String, then those two extensions still # appear separately. # # (The USR part of the dedup key means ModA.Foo and ModB.Foo do not # get merged.) def self.module_deduplication_key(decl) if (Config.instance.merge_modules == :none) || (Config.instance.merge_modules == :extensions && decl.extension_of_external_type?) decl.doc_module_name else '' end end # Two declarations get merged if they have the same deduplication key. def self.deduplication_key(decl, root_decls) mod_key = module_deduplication_key(decl) # Swift extension of objc class if decl.swift_objc_extension? [decl.swift_extension_objc_name, nil, :objc_class_and_categories, mod_key] # Swift type or Swift extension of Swift type elsif mergeable_swift?(decl) [decl.usr, nil, decl.name, mod_key] # Objc categories and classes elsif mergeable_objc?(decl, root_decls) # Using the ObjC name to match swift_objc_extension. name, _ = decl.objc_category_name || decl.objc_name [name, nil, :objc_class_and_categories, mod_key] # Non-mergable declarations (funcs, typedefs etc...) else # The typename part works around a Swift bug, jazzy#1396 [decl.usr, decl.typename, decl.name, decl.type.kind, ''] end end # rubocop:disable Metrics/MethodLength # rubocop:disable Metrics/PerceivedComplexity # Merges all of the given types and extensions into a single document. def self.merge_declarations(decls) extensions, typedecls = decls.partition { |d| d.type.extension? } if typedecls.size > 1 info = typedecls .map { |t| "#{t.type.name.downcase} #{t.name}" } .join(', ') warn 'Found conflicting type declarations with the same name, which ' \ "may indicate a build issue or a bug in Jazzy: #{info}" end typedecl = typedecls.first extensions = reject_inaccessible_extensions(typedecl, extensions) if typedecl if typedecl.type.swift_protocol? mark_and_merge_protocol_extensions(typedecl, extensions) extensions.reject! { |ext| ext.children.empty? } end merge_objc_declaration_marks(typedecl, extensions) end # Keep type-aliases separate from any extensions if typedecl&.type&.swift_typealias? [merge_type_and_extensions(typedecls, []), merge_type_and_extensions([], extensions)] else merge_type_and_extensions(typedecls, extensions) end end # rubocop:enable Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength def self.merge_type_and_extensions(typedecls, extensions) # Constrained extensions at the end constrained, regular_exts = extensions.partition(&:constrained_extension?) decls = typedecls + regular_exts + constrained return nil if decls.empty? move_merged_extension_marks(decls) merge_code_declaration(decls) decls.first.tap do |merged| merged.children = deduplicate_declarations( decls.flat_map(&:children).uniq, ) merged.children.each do |child| child.parent_in_code = merged end end end # Now we know all the public types and all the private protocols, # reject extensions that add public protocols to private types # or add private protocols to public types. def self.reject_inaccessible_extensions(typedecl, extensions) swift_exts, objc_exts = extensions.partition(&:swift?) # Reject extensions that are just conformances to private protocols unwanted_exts, wanted_exts = swift_exts.partition do |ext| ext.children.empty? && !ext.other_inherited_types?(@inaccessible_protocols) end # Given extensions of a type from this module, without the # type itself, the type must be private and the extensions # should be rejected. if !typedecl && wanted_exts.first&.type_from_doc_module? unwanted_exts += wanted_exts wanted_exts = [] end # Don't tell the user to document them or their contents remover = lambda do |decls| decls.each { |d| @stats.remove_undocumented(d) } decls.map(&:children).each { |c| remover[c] } end remover[unwanted_exts] objc_exts + wanted_exts end # Protocol extensions. # # If any of the extensions provide default implementations for methods in # the given protocol, merge those members into the protocol doc instead of # keeping them on the extension. These get a “Default implementation” # annotation in the generated docs. Default implementations added by # conditional extensions are annotated but listed separately. # # Protocol methods provided only in an extension and not in the protocol # itself are a special beast: they do not use dynamic dispatch. These get an # “Extension method” annotation in the generated docs. def self.mark_and_merge_protocol_extensions(protocol, extensions) extensions.each do |ext| ext.children = ext.children.select do |ext_member| proto_member = protocol.children.find do |p| p.default_implementation?(ext_member) end # Extension-only method, keep. unless proto_member ext_member.from_protocol_extension = true next true end # Default impl but constrained, mark and keep. if ext.constrained_extension? ext_member.default_impl_abstract = ext_member.abstract ext_member.abstract = nil next true end # Default impl for all users, merge. proto_member.default_impl_abstract = ext_member.abstract next false end end end # Mark children merged from categories with the name of category # (unless they already have a mark) def self.merge_objc_declaration_marks(typedecl, extensions) return unless typedecl.type.objc_class? extensions.each do |ext| _, category_name = ext.objc_category_name ext.children.each { |c| c.mark.name ||= category_name } end end # For each extension to be merged, move any MARK from the extension # declaration down to the extension contents so it still shows up. def self.move_merged_extension_marks(decls) return unless to_be_merged = decls[1..] to_be_merged.each do |ext| child = ext.children.first if child && child.mark.empty? child.mark.copy(ext.mark) end end end # Merge useful information added by extensions into the main # declaration: public protocol conformances and, for top-level extensions, # further conditional extensions of the same type. def self.merge_code_declaration(decls) declarations = decls[1..].select do |decl| decl.type.swift_extension? && (decl.other_inherited_types?(@inaccessible_protocols) || (decls.first.type.swift_extension? && decl.constrained_extension?)) end.prepend(decls.first) html_declaration = '' until declarations.empty? module_decls, declarations = next_doc_module_group(declarations) first = module_decls.first if need_doc_module_note?(first, html_declaration)
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
true
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/documentation_generator.rb
lib/jazzy/documentation_generator.rb
# frozen_string_literal: true require 'pathname' require 'jazzy/jazzy_markdown' require 'jazzy/source_document' module Jazzy module DocumentationGenerator extend Config::Mixin def self.source_docs documentation_entries.map do |file_path| SourceDocument.new.tap do |sd| sd.name = File.basename(file_path, '.md') sd.overview = overview Pathname(file_path) sd.usr = "documentation.#{sd.name}" end end end def self.overview(file_path) return '' unless file_path&.exist? file_path.read end def self.documentation_entries return [] unless config.documentation_glob_configured && config.documentation_glob config.documentation_glob.select { |e| File.file? e } end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/doc.rb
lib/jazzy/doc.rb
# frozen_string_literal: true require 'date' require 'pathname' require 'mustache' require 'jazzy/config' require 'jazzy/gem_version' require 'jazzy/jazzy_markdown' module Jazzy class Doc < Mustache include Config::Mixin self.template_name = 'doc' def copyright copyright = config.copyright || ( # Fake date is used to keep integration tests consistent date = ENV['JAZZY_FAKE_DATE'] || DateTime.now.strftime('%Y-%m-%d') year = date[0..3] "&copy; #{year} [#{config.author_name}](#{config.author_url}). " \ "All rights reserved. (Last updated: #{date})" ) Markdown.render_copyright(copyright).chomp end def jazzy_version # Fake version is used to keep integration tests consistent ENV['JAZZY_FAKE_VERSION'] || Jazzy::VERSION end def objc_first? config.objc_mode && config.hide_declarations != 'objc' end def language_stub objc_first? ? 'objc' : 'swift' end def module_version config.version_configured ? config.version : nil end def docs_title if config.title_configured config.title elsif config.version_configured # Fake version for integration tests version = ENV['JAZZY_FAKE_MODULE_VERSION'] || config.version "#{config.module_configs.first.module_name} #{version} Docs" else "#{config.module_configs.first.module_name} Docs" end end def enable_katex Markdown.has_math end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph.rb
lib/jazzy/symbol_graph.rb
# frozen_string_literal: true require 'set' require 'jazzy/symbol_graph/graph' require 'jazzy/symbol_graph/constraint' require 'jazzy/symbol_graph/symbol' require 'jazzy/symbol_graph/relationship' require 'jazzy/symbol_graph/sym_node' require 'jazzy/symbol_graph/ext_node' require 'jazzy/symbol_graph/ext_key' # This is the top-level symbolgraph driver that deals with # figuring out arguments, running the tool, and loading the # results. module Jazzy module SymbolGraph # Find swift symbol graph files, either having been passed # in directly, or generated by running`swift symbolgraph-extract` # with configured args. # Then parse the results, and return as JSON in SourceKit[ten] # format. def self.build(module_config) if module_config.symbolgraph_directory.nil? Dir.mktmpdir do |tmp_dir| args = arguments(module_config, tmp_dir) Executable.execute_command('swift', args.unshift('symbolgraph-extract'), true) # raise on error parse_symbols(tmp_dir) end else parse_symbols(module_config.symbolgraph_directory.to_s) end end # Figure out the args to pass to symbolgraph-extract def self.arguments(module_config, output_path) if module_config.module_name.empty? raise 'error: `--swift-build-tool symbolgraph` requires `--module`.' end user_args = module_config.build_tool_arguments.join if user_args =~ /-(?:module-name|minimum-access-level|output-dir)/ raise 'error: `--build-tool-arguments` for ' \ "`--swift-build-tool symbolgraph` can't use `-module`, " \ '`-minimum-access-level`, or `-output-dir`.' end # Default set args = [ '-module-name', module_config.module_name, '-minimum-access-level', 'private', '-output-dir', output_path, '-skip-synthesized-members' ] # Things user can override args += ['-sdk', sdk(module_config)] unless user_args =~ /-sdk/ args += ['-target', target] unless user_args =~ /-target/ args += ['-F', module_config.source_directory.to_s] unless user_args =~ /-F(?!s)/ args += ['-I', module_config.source_directory.to_s] unless user_args =~ /-I/ args + module_config.build_tool_arguments end # Parse the symbol files in the given directory def self.parse_symbols(directory) Dir[directory + '/*.symbols.json'].sort.map do |filename| # The @ part is for extensions in our module (before the @) # of types in another module (after the @). File.basename(filename) =~ /(.*?)(@(.*?))?\.symbols/ module_name = Regexp.last_match[1] ext_module_name = Regexp.last_match[3] || module_name json = File.read(filename) { filename => Graph.new(json, module_name, ext_module_name).to_sourcekit, } end.to_json end # Get the SDK path. On !darwin this just isn't needed. def self.sdk(module_config) `xcrun --show-sdk-path --sdk #{module_config.sdk}`.chomp end # Guess a default LLVM target. Feels like the tool should figure this # out from sdk + the binary somehow? def self.target `swift -version` =~ /Target: (.*?)$/ Regexp.last_match[1] || 'x86_64-apple-macosx10.15' end # This is a last-ditch fallback for when symbolgraph doesn't # provide a name - at least conforming external types to local # protocols. def self.demangle(usr) args = %w[demangle -simplified -compact].append(usr.sub(/^s:/, 's')) output, = Executable.execute_command('swift', args, true) output.chomp rescue StandardError usr end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/grouper.rb
lib/jazzy/grouper.rb
# frozen_string_literal: true module Jazzy # This module deals with arranging top-level declarations and guides into # groups automatically and/or using a custom list. module Grouper extend Config::Mixin # Group root-level docs by custom categories (if any) and type or module def self.group_docs(docs, doc_index) custom_categories, docs = group_custom_categories(docs, doc_index) unlisted_prefix = config.custom_categories_unlisted_prefix type_category_prefix = custom_categories.any? ? unlisted_prefix : '' all_categories = custom_categories + if config.merge_modules == :all group_docs_by_type(docs, type_category_prefix) else group_docs_by_module(docs, type_category_prefix) end merge_consecutive_marks(all_categories) end # Group root-level docs by type def self.group_docs_by_type(docs, type_category_prefix) type_groups = SourceDeclaration::Type.all.map do |type| children, docs = docs.partition { |doc| doc.type == type } make_type_group(children, type, type_category_prefix) end merge_categories(type_groups.compact) + docs end # Group root-level docs by module name def self.group_docs_by_module(docs, type_category_prefix) guide_categories, docs = group_guides(docs, type_category_prefix) module_categories = docs .group_by(&:doc_module_name) .map do |name, module_docs| make_group( module_docs, name, "The following declarations are provided by module #{name}.", ) end guide_categories + module_categories end def self.group_custom_categories(docs, doc_index) group = config.custom_categories.map do |category| children = category['children'].map do |selector| selected = select_docs(doc_index, selector) selected.map do |doc| unless doc.parent_in_code.nil? warn "WARNING: Declaration \"#{doc.fully_qualified_module_name}\" " \ 'specified in categories file exists but is not top-level and ' \ 'cannot be included here' next nil end docs.delete(doc) end end.flatten.compact # Category config overrides alphabetization children.each.with_index { |child, i| child.nav_order = i } make_group(children, category['name'], '') end [group.compact, docs] end def self.select_docs(doc_index, selector) if selector.is_a?(String) unless single_doc = doc_index.lookup(selector) warn 'WARNING: No documented top-level declarations match ' \ "name \"#{selector}\" specified in categories file" return [] end [single_doc] else doc_index.lookup_regex(selector['regex']) .sort_by(&:name) end end def self.group_guides(docs, prefix) guides, others = docs.partition { |doc| doc.type.markdown? } return [[], others] unless guides.any? [[make_type_group(guides, guides.first.type, prefix)], others] end def self.make_type_group(docs, type, type_category_prefix) make_group( docs, type_category_prefix + type.plural_name, "The following #{type.plural_name.downcase} are available globally.", type_category_prefix + type.plural_url_name, ) end # Join categories with the same name (eg. ObjC and Swift classes) def self.merge_categories(categories) merged = [] categories.each do |new_category| if existing = merged.find { |cat| cat.name == new_category.name } existing.children += new_category.children else merged.append(new_category) end end merged end def self.make_group(group, name, abstract, url_name = nil) group.reject! { |decl| decl.name.empty? } unless group.empty? SourceDeclaration.new.tap do |sd| sd.type = SourceDeclaration::Type.overview sd.name = name sd.url_name = url_name sd.abstract = Markdown.render(abstract) sd.children = group end end end # Merge consecutive sections with the same mark into one section # Needed because of pulling various decls into groups def self.merge_consecutive_marks(docs) prev_mark = nil docs.each do |doc| if prev_mark&.can_merge?(doc.mark) doc.mark = prev_mark end prev_mark = doc.mark merge_consecutive_marks(doc.children) end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/podspec_documenter.rb
lib/jazzy/podspec_documenter.rb
# frozen_string_literal: true require 'tmpdir' require 'json' module Jazzy # rubocop:disable Metrics/ClassLength class PodspecDocumenter attr_reader :podspec def initialize(podspec) @podspec = podspec end # Build documentation from the given options # @param [Config] options def sourcekitten_output(config) installation_root = Pathname(Dir.mktmpdir(['jazzy', podspec.name])) installation_root.rmtree if installation_root.exist? Pod::Config.instance.with_changes(installation_root: installation_root, verbose: false) do sandbox = Pod::Sandbox.new(Pod::Config.instance.sandbox_root) installer = Pod::Installer.new(sandbox, podfile(config)) installer.install! stdout = Dir.chdir(sandbox.root) do targets = installer.pod_targets .select { |pt| pt.pod_name == podspec.root.name } .map(&:label) targets.map do |t| args = %W[doc --module-name #{podspec.module_name} -- -target #{t}] SourceKitten.run_sourcekitten(args) end end stdout.reduce([]) { |a, s| a + JSON.parse(s) }.to_json end end def self.create_podspec(podspec_path) case podspec_path when Pathname, String require 'cocoapods' Pod::Specification.from_file(podspec_path) end end # rubocop:disable Metrics/MethodLength def self.apply_config_defaults(podspec, config) return unless podspec unless config.author_name_configured config.author_name = author_name(podspec) config.author_name_configured = true end unless config.module_name_known? config.module_name = podspec.module_name config.module_name_configured = true end unless config.author_url_configured config.author_url = podspec.homepage || github_file_prefix(podspec) config.author_url_configured = true end unless config.version_configured config.version = podspec.version.to_s config.version_configured = true end unless config.source_host_files_url_configured config.source_host_files_url = github_file_prefix(podspec) config.source_host_files_url_configured = true end unless config.swift_version_configured trunk_swift_build = podspec.attributes_hash['pushed_with_swift_version'] config.swift_version = trunk_swift_build if trunk_swift_build config.swift_version_configured = true end end # rubocop:enable Metrics/MethodLength private # @!group Config helper methods def self.author_name(podspec) if podspec.authors.respond_to? :to_hash podspec.authors.keys.to_sentence || '' elsif podspec.authors.respond_to? :to_ary podspec.authors.to_sentence end || podspec.authors || '' end private_class_method :author_name def self.github_file_prefix(podspec) return unless podspec.source[:url] =~ %r{github.com[:/]+(.+)/(.+)} org, repo = Regexp.last_match return unless rev = podspec.source[:tag] || podspec.source[:commit] "https://github.com/#{org}/#{repo.sub(/\.git$/, '')}/blob/#{rev}" end private_class_method :github_file_prefix # Latest valid value for SWIFT_VERSION. LATEST_SWIFT_VERSION = '6' private_constant :LATEST_SWIFT_VERSION # All valid values for SWIFT_VERSION that are longer # than a major version number. Ordered ascending. LONG_SWIFT_VERSIONS = ['4.2'].freeze private_constant :LONG_SWIFT_VERSIONS # Go from a full Swift version like 4.2.1 to # something valid for SWIFT_VERSION. def compiler_swift_version(user_version) unless user_version return podspec_swift_version || LATEST_SWIFT_VERSION end LONG_SWIFT_VERSIONS.select do |version| user_version.start_with?(version) end.last || "#{user_version[0]}.0" end def podspec_swift_version # `swift_versions` exists from CocoaPods 1.7 if podspec.respond_to?('swift_versions') podspec.swift_versions.max else podspec.swift_version end end # @!group SourceKitten output helper methods def pod_path if podspec.defined_in_file podspec.defined_in_file.parent else config.source_directory end end # rubocop:disable Metrics/MethodLength def podfile(config) swift_version = compiler_swift_version(config.swift_version) podspec = @podspec path = pod_path @podfile ||= Pod::Podfile.new do config.pod_sources.each do |src| source src end install! 'cocoapods', integrate_targets: false, deterministic_uuids: false [podspec, *podspec.recursive_subspecs].each do |ss| next if ss.test_specification ss.available_platforms.each do |p| # Travis builds take too long when building docs for all available # platforms for the Moya integration spec, so we just document OSX. # TODO: remove once jazzy is fast enough. next if ENV['JAZZY_INTEGRATION_SPECS'] && p.name != :osx target("Jazzy-#{ss.name.gsub('/', '__')}-#{p.name}") do use_frameworks! platform p.name, p.deployment_target pod ss.name, path: path.realpath.to_s current_target_definition.swift_version = swift_version end end end end end # rubocop:enable Metrics/MethodLength end # rubocop:enable Metrics/ClassLength end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/stats.rb
lib/jazzy/stats.rb
# frozen_string_literal: true module Jazzy # Collect + report metadata about a processed module class Stats include Config::Mixin attr_reader :documented, :acl_skipped, :spi_skipped, :undocumented_decls def add_documented @documented += 1 end def add_acl_skipped @acl_skipped += 1 end def add_spi_skipped @spi_skipped += 1 end def add_undocumented(decl) @undocumented_decls << decl end def remove_undocumented(decl) @undocumented_decls.delete(decl) end def acl_included documented + undocumented end def undocumented undocumented_decls.count end def initialize @documented = @acl_skipped = @spi_skipped = 0 @undocumented_decls = [] end def report puts "#{doc_coverage}% documentation coverage " \ "with #{undocumented} undocumented " \ "#{symbol_or_symbols(undocumented)}" if acl_included > 0 swift_acls = comma_list(config.min_acl.included_levels) puts "included #{acl_included} " + (config.objc_mode ? '' : "#{swift_acls} ") + symbol_or_symbols(acl_included) end if !config.objc_mode && acl_skipped > 0 puts "skipped #{acl_skipped} " \ "#{comma_list(config.min_acl.excluded_levels)} " \ "#{symbol_or_symbols(acl_skipped)} " \ '(use `--min-acl` to specify a different minimum ACL)' end if spi_skipped > 0 puts "skipped #{spi_skipped} SPI #{symbol_or_symbols(spi_skipped)} " \ '(use `--include-spi-declarations` to include these)' end end def doc_coverage return 0 if acl_included == 0 (100 * documented) / acl_included end private def comma_list(items) case items.count when 0 then '' when 1 then items[0] when 2 then "#{items[0]} or #{items[1]}" else "#{items[0..-2].join(', ')}, or #{items[-1]}" end end def symbol_or_symbols(count) count == 1 ? 'symbol' : 'symbols' end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_host.rb
lib/jazzy/source_host.rb
# frozen_string_literal: true module Jazzy # Deal with different source code repositories module SourceHost # Factory to create the right source host def self.create(options) return unless options.source_host_url || options.source_host_files_url case options.source_host when :github then GitHub.new when :gitlab then GitLab.new when :bitbucket then BitBucket.new end end # Use GitHub as the default behaviour. class GitHub include Config::Mixin # Human readable name, appears in UI def name 'GitHub' end # Jazzy extension with logo def extension name.downcase end # Logo image filename within extension def image 'gh.png' end # URL to link to from logo def url config.source_host_url end # URL to link to from a SourceDeclaration. # Compare using `realpath` because `item.file` comes out of # SourceKit/etc. def item_url(item) return unless files_url && item.file realpath = item.file.realpath return unless realpath.to_path.start_with?(local_root_realpath) path = realpath.relative_path_from(local_root_realpath) fragment = if item.start_line && (item.start_line != item.end_line) item_url_multiline_fragment(item.start_line, item.end_line) else item_url_line_fragment(item.line) end "#{files_url}/#{path}##{fragment}" end private def files_url config.source_host_files_url end def local_root_realpath @local_root_realpath ||= config.source_directory.realpath.to_path end # Source host's line numbering link scheme def item_url_line_fragment(line) "L#{line}" end def item_url_multiline_fragment(start_line, end_line) "L#{start_line}-L#{end_line}" end end # GitLab very similar to GitHub class GitLab < GitHub def name 'GitLab' end def image 'gitlab.svg' end end # BitBucket has its own line number system class BitBucket < GitHub def name 'Bitbucket' end def image 'bitbucket.svg' end def item_url_line_fragment(line) "lines-#{line}" end def item_url_multiline_fragment(start_line, end_line) "lines-#{start_line}:#{end_line}" end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/doc_builder.rb
lib/jazzy/doc_builder.rb
# frozen_string_literal: true require 'fileutils' require 'mustache' require 'pathname' require 'sassc' require 'jazzy/config' require 'jazzy/doc' require 'jazzy/docset_builder' require 'jazzy/documentation_generator' require 'jazzy/search_builder' require 'jazzy/jazzy_markdown' require 'jazzy/podspec_documenter' require 'jazzy/source_declaration' require 'jazzy/source_document' require 'jazzy/source_module' require 'jazzy/sourcekitten' require 'jazzy/symbol_graph' module Jazzy # This module handles HTML generation, file writing, asset copying, # and generally building docs given sourcekitten output module DocBuilder # mkdir -p output directory and clean if option is set def self.prepare_output_dir(output_dir, clean) FileUtils.rm_r output_dir if clean && output_dir.directory? FileUtils.mkdir_p output_dir end # Generate doc structure to be used in sidebar navigation # @return [Array] doc structure comprised of # section names & child names & URLs def self.doc_structure_for_docs(docs) docs .map do |doc| children = children_for_doc(doc) { section: doc.name, url: doc.url, children: children, } end .select do |structure| if Config.instance.hide_unlisted_documentation unlisted_prefix = Config.instance.custom_categories_unlisted_prefix structure[:section] != "#{unlisted_prefix}Guides" else true end end end def self.children_for_doc(doc) doc.children .sort_by { |c| [c.nav_order, c.name, c.usr || ''] } .flat_map do |child| # FIXME: include arbitrarily nested extensible types [{ name: child.name, url: child.url }] + Array(child.children.select do |sub_child| sub_child.type.swift_extensible? || sub_child.type.extension? end).map do |sub_child| { name: "– #{sub_child.name}", url: sub_child.url } end end end # Build documentation from the given options # @param [Config] options def self.build(options) module_jsons = options.module_configs.map do |module_config| if module_config.podspec_configured # Config#validate guarantees not multi-module here pod_documenter = PodspecDocumenter.new(options.podspec) pod_documenter.sourcekitten_output(options) elsif !module_config.sourcekitten_sourcefile.empty? "[#{module_config.sourcekitten_sourcefile.map(&:read).join(',')}]" elsif module_config.swift_build_tool == :symbolgraph SymbolGraph.build(module_config) else Dir.chdir(module_config.source_directory) do arguments = SourceKitten.arguments_from_options(module_config) SourceKitten.run_sourcekitten(arguments) end end end build_docs_for_sourcekitten_output(module_jsons, options) end # Build & write HTML docs to disk from structured docs array # @param [String] output_dir Root directory to write docs # @param [SourceModule] source_module All info to generate docs def self.build_docs(output_dir, source_module) each_doc(output_dir, source_module.docs) do |doc, path| prepare_output_dir(path.parent, false) depth = path.relative_path_from(output_dir).each_filename.count - 1 path_to_root = '../' * depth path.open('w') do |file| file.write(document(source_module, doc, path_to_root)) end end end def self.each_doc(output_dir, docs, &block) docs.each do |doc| next unless doc.render_as_page? # Filepath is relative to documentation root: path = output_dir + doc.filepath block.call(doc, path) each_doc( output_dir, doc.children, &block ) end end def self.build_site(docs, coverage, options) warn 'building site' structure = doc_structure_for_docs(docs) docs << SourceDocument.make_index(options.readme_path) output_dir = options.output docset_builder = DocsetBuilder.new(output_dir) source_module = SourceModule.new(docs, structure, coverage, docset_builder) build_docs(output_dir, source_module) unless options.disable_search warn 'building search index' SearchBuilder.build(source_module, output_dir) end copy_extensions(source_module, output_dir) copy_theme_assets(output_dir) docset_builder.build!(source_module.all_declarations) generate_badge(source_module.doc_coverage, options) friendly_path = relative_path_if_inside(output_dir, Pathname.pwd) puts "jam out ♪♫ to your fresh new docs in `#{friendly_path}`" source_module end # Build docs given sourcekitten output # @param [Array<String>] sourcekitten_output Output of sourcekitten command for each module # @param [Config] options Build options def self.build_docs_for_sourcekitten_output(sourcekitten_output, options) (docs, stats) = SourceKitten.parse( sourcekitten_output, options, DocumentationGenerator.source_docs, ) prepare_output_dir(options.output, options.clean) stats.report unless options.skip_documentation build_site(docs, stats.doc_coverage, options) end write_lint_report(stats.undocumented_decls, options) end def self.relative_path_if_inside(path, base_path) relative = path.relative_path_from(base_path) if relative.to_path =~ %r{/^..(/|$)/} path else relative end end def self.undocumented_warnings(decls) decls.map do |decl| { file: decl.file, line: decl.start_line || decl.line, symbol: decl.fully_qualified_name, symbol_kind: decl.type.kind, warning: 'undocumented', } end end def self.write_lint_report(undocumented, options) (options.output + 'undocumented.json').open('w') do |f| warnings = undocumented_warnings(undocumented) lint_report = { warnings: warnings.sort_by do |w| [w[:file] || Pathname(''), w[:line] || 0, w[:symbol], w[:symbol_kind]] end, source_directory: options.source_directory, } f.write(JSON.pretty_generate(lint_report)) end end def self.copy_theme_assets(destination) assets_directory = Config.instance.theme_directory + 'assets' FileUtils.cp_r(assets_directory.children, destination) Pathname.glob(destination + 'css/**/*.scss').each do |scss| css = SassC::Engine.new(scss.read).render css_filename = scss.sub(/\.scss$/, '') css_filename.open('w') { |f| f.write(css) } FileUtils.rm scss end end def self.copy_extensions(source_module, destination) if source_host = source_module.host&.extension copy_extension(source_host, destination) end copy_extension('katex', destination) if Markdown.has_math end def self.copy_extension(name, destination) ext_directory = Pathname(__dir__) / 'extensions' / name FileUtils.cp_r(ext_directory.children, destination) end def self.render(doc_model, markdown) html = Markdown.render(markdown) SourceKitten.autolink_document(html, doc_model) end def self.render_inline(doc_model, markdown) html = Markdown.render_inline(markdown) SourceKitten.autolink_document(html, doc_model) end # Build Mustache document - common fields between page types def self.new_document(source_module, doc_model) Doc.new.tap do |doc| doc[:custom_head] = Config.instance.custom_head doc[:disable_search] = Config.instance.disable_search doc[:doc_coverage] = source_module.doc_coverage unless Config.instance.hide_documentation_coverage doc[:structure] = source_module.doc_structure doc[:readme_title] = source_module.readme_title doc[:module_name] = doc[:readme_title] doc[:author_name] = source_module.author_name if source_host = source_module.host doc[:source_host_name] = source_host.name doc[:source_host_url] = source_host.url doc[:source_host_image] = source_host.image doc[:source_host_item_url] = source_host.item_url(doc_model) doc[:github_url] = doc[:source_host_url] doc[:github_token_url] = doc[:source_host_item_url] end doc[:dash_url] = source_module.dash_feed_url doc[:breadcrumbs] = make_breadcrumbs(doc_model) end end # Build Mustache document from a markdown source file # @param [SourceModule] module-wide settings # @param [Hash] doc_model Parsed doc. @see SourceKitten.parse # @param [String] path_to_root def self.document_markdown(source_module, doc_model, path_to_root) doc = new_document(source_module, doc_model) name = doc_model.readme? ? source_module.readme_title : doc_model.name doc[:name] = name doc[:overview] = render(doc_model, doc_model.content(source_module)) doc[:path_to_root] = path_to_root doc[:hide_name] = true doc.render.gsub(ELIDED_AUTOLINK_TOKEN, path_to_root) end # Returns the appropriate color for the provided percentage, # used for generating a badge on shields.io # @param [Number] coverage The documentation coverage percentage def self.color_for_coverage(coverage) if coverage < 10 'e05d44' # red elsif coverage < 30 'fe7d37' # orange elsif coverage < 60 'dfb317' # yellow elsif coverage < 85 'a4a61d' # yellowgreen elsif coverage < 90 '97CA00' # green else '4c1' # brightgreen end end # rubocop:disable Metrics/MethodLength # Generates an SVG similar to those from shields.io displaying the # documentation percentage # @param [Number] coverage The documentation coverage percentage # @param [Config] options Build options def self.generate_badge(coverage, options) return if options.hide_documentation_coverage coverage_length = coverage.to_s.size.succ percent_string_length = coverage_length * 80 + 10 percent_string_offset = coverage_length * 40 + 975 width = coverage_length * 8 + 104 svg = <<-SVG.gsub(/^ {8}/, '') <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{width}" height="20"> <linearGradient id="b" x2="0" y2="100%"> <stop offset="0" stop-color="#bbb" stop-opacity=".1"/> <stop offset="1" stop-opacity=".1"/> </linearGradient> <clipPath id="a"> <rect width="#{width}" height="20" rx="3" fill="#fff"/> </clipPath> <g clip-path="url(#a)"> <path fill="#555" d="M0 0h93v20H0z"/> <path fill="##{color_for_coverage(coverage)}" d="M93 0h#{percent_string_length / 10 + 10}v20H93z"/> <path fill="url(#b)" d="M0 0h#{width}v20H0z"/> </g> <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"> <text x="475" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="830"> documentation </text> <text x="475" y="140" transform="scale(.1)" textLength="830"> documentation </text> <text x="#{percent_string_offset}" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="#{percent_string_length}"> #{coverage}% </text> <text x="#{percent_string_offset}" y="140" transform="scale(.1)" textLength="#{percent_string_length}"> #{coverage}% </text> </g> </svg> SVG badge_output = options.output + 'badge.svg' File.open(badge_output, 'w') { |f| f << svg } end # rubocop:enable Metrics/MethodLength # Build mustache item for a top-level doc # @param [Hash] item Parsed doc child item # @param [Config] options Build options # rubocop:disable Metrics/MethodLength def self.render_item(item, source_module) # Combine abstract and discussion into abstract abstract = (item.abstract || '') + (item.discussion || '') source_host_item_url = source_module.host&.item_url(item) { name: item.name, name_html: item.name.gsub(':', ':<wbr>'), abstract: abstract, declaration: item.display_declaration, language: item.display_language, other_language_declaration: item.display_other_language_declaration, usr: item.usr, dash_type: item.type.dash_type, source_host_item_url: source_host_item_url, github_token_url: source_host_item_url, default_impl_abstract: item.default_impl_abstract, from_protocol_extension: item.from_protocol_extension, return: item.return, parameters: (item.parameters if item.parameters.any?), url: (item.url if item.render_as_page?), start_line: item.start_line, end_line: item.end_line, direct_link: item.omit_content_from_parent?, deprecation_message: item.deprecation_message, unavailable_message: item.unavailable_message, usage_discouraged: item.usage_discouraged?, async: item.async, declaration_note: item.declaration_note, } end # rubocop:enable Metrics/MethodLength def self.make_task(mark, uid, items, doc_model) { name: mark.name, name_html: (render_inline(doc_model, mark.name) if mark.name), uid: ERB::Util.url_encode(uid), items: items, pre_separator: mark.has_start_dash, post_separator: mark.has_end_dash, } end # Render tasks for Mustache document # @param [Config] options Build options # @param [Hash] doc_model Parsed doc. @see SourceKitten.parse def self.render_tasks(source_module, children) marks = children.map(&:mark).uniq.compact mark_names_counts = {} marks.map do |mark| mark_children = children.select { |child| child.mark == mark } items = mark_children.map { |child| render_item(child, source_module) } uid = (mark.name || 'Unnamed').to_s if mark_names_counts.key?(uid) mark_names_counts[uid] += 1 uid += mark_names_counts[uid].to_s else mark_names_counts[uid] = 1 end make_task(mark, uid, items, mark_children.first) end end # rubocop:disable Metrics/MethodLength # Build Mustache document from single parsed decl # @param [SourceModule] module-wide settings # @param [Hash] doc_model Parsed doc. @see SourceKitten.parse # @param [String] path_to_root def self.document(source_module, doc_model, path_to_root) if doc_model.type.markdown? return document_markdown(source_module, doc_model, path_to_root) end overview = (doc_model.abstract || '') + (doc_model.discussion || '') alternative_abstract = doc_model.alternative_abstract if alternative_abstract overview = render(doc_model, alternative_abstract) + overview end doc = new_document(source_module, doc_model) doc[:name] = doc_model.name doc[:kind] = doc_model.type.name doc[:dash_type] = doc_model.type.dash_type doc[:declaration] = doc_model.display_declaration doc[:language] = doc_model.display_language doc[:other_language_declaration] = doc_model.display_other_language_declaration doc[:overview] = overview doc[:parameters] = doc_model.parameters doc[:return] = doc_model.return doc[:tasks] = render_tasks(source_module, doc_model.children) doc[:path_to_root] = path_to_root doc[:deprecation_message] = doc_model.deprecation_message doc[:unavailable_message] = doc_model.unavailable_message doc[:usage_discouraged] = doc_model.usage_discouraged? doc.render.gsub(ELIDED_AUTOLINK_TOKEN, path_to_root) end # rubocop:enable Metrics/MethodLength # Breadcrumbs for a page - doesn't include the top 'readme' crumb def self.make_breadcrumbs(doc_model) return [] if doc_model.readme? docs_path = doc_model.docs_path breadcrumbs = docs_path.map do |doc| { name: doc.name, url: doc.url, last: doc == doc_model, } end return breadcrumbs if breadcrumbs.one? # Add the module name to the outer type if not clear from context if docs_path[1].ambiguous_module_name?(docs_path[0].name) breadcrumbs[1][:name] = docs_path[1].fully_qualified_module_name end breadcrumbs end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_module.rb
lib/jazzy/source_module.rb
# frozen_string_literal: true require 'uri' require 'jazzy/config' require 'jazzy/source_declaration' require 'jazzy/source_host' module Jazzy # A cache of info that is common across all page templating, gathered # from other parts of the program. class SourceModule include Config::Mixin attr_accessor :readme_title attr_accessor :docs attr_accessor :doc_coverage attr_accessor :doc_structure attr_accessor :author_name attr_accessor :author_url attr_accessor :dash_feed_url attr_accessor :host def initialize(docs, doc_structure, doc_coverage, docset_builder) self.docs = docs self.doc_structure = doc_structure self.doc_coverage = doc_coverage title = config.readme_title || config.module_names.first self.readme_title = title.empty? ? 'Index' : title self.author_name = config.author_name self.author_url = config.author_url self.host = SourceHost.create(config) self.dash_feed_url = docset_builder.dash_feed_url end def all_declarations all_declarations = [] visitor = lambda do |d| all_declarations.unshift(*d) d.map(&:children).each { |c| visitor[c] } end visitor[docs] all_declarations.reject { |doc| doc.name == 'index' } end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_mark.rb
lib/jazzy/source_mark.rb
# frozen_string_literal: true module Jazzy class SourceMark attr_accessor :name attr_accessor :has_start_dash attr_accessor :has_end_dash def initialize(mark_string = nil) return unless mark_string # Format: 'MARK: - NAME -' with dashes optional mark_content = mark_string.sub(/^MARK: /, '') if mark_content.empty? # Empty return elsif mark_content == '-' # Separator self.has_start_dash = true return end self.has_start_dash = mark_content.start_with?('- ') self.has_end_dash = mark_content.end_with?(' -') start_index = has_start_dash ? 2 : 0 end_index = has_end_dash ? -3 : -1 self.name = mark_content[start_index..end_index] end def self.new_generic_requirements(requirements) marked_up = requirements.gsub(/\b([^=:]\S*)\b/, '`\1`') text = "Available where #{marked_up}" new(text) end def empty? !name && !has_start_dash && !has_end_dash end def copy(other) self.name = other.name self.has_start_dash = other.has_start_dash self.has_end_dash = other.has_end_dash end # Can we merge the contents of another mark into our own? def can_merge?(other) other.empty? || other.name == name end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/search_builder.rb
lib/jazzy/search_builder.rb
# frozen_string_literal: true module Jazzy module SearchBuilder def self.build(source_module, output_dir) decls = source_module.all_declarations.select do |d| d.type && d.name && !d.name.empty? end index = decls.to_h do |d| [d.url, { name: d.name, abstract: d.abstract && d.abstract.split("\n").map(&:strip).first, parent_name: d.parent_in_code&.name, }.reject { |_, v| v.nil? || v.empty? }] end File.write(File.join(output_dir, 'search.json'), index.to_json) end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/doc_index.rb
lib/jazzy/doc_index.rb
# frozen_string_literal: true module Jazzy # This class stores an index of symbol names for doing name lookup # when resolving custom categories and autolinks. class DocIndex # A node in the index tree. The root has no decl; its children are # per-module indexed by module names. The second level, where each # scope is a module, also has no decl; its children are scopes, one # for each top-level decl in the module. From the third level onwards # the decl is valid. class Scope attr_reader :decl # SourceDeclaration attr_reader :children # String:Scope def initialize(decl, children) @decl = decl @children = children end def self.new_root(module_decls) new(nil, module_decls.transform_values do |decls| Scope.new_decl(nil, decls) end) end # Decl names in a scope are usually unique. The exceptions # are (1) methods and (2) typealias+extension, which historically # jazzy does not merge. The logic here and in `merge()` below # preserves the historical ambiguity-resolution of (1) and tries # to do the best for (2). def self.new_decl(decl, child_decls) child_scopes = {} child_decls.flat_map do |child_decl| child_scope = Scope.new_decl(child_decl, child_decl.children) child_decl.index_names.map do |name| if curr = child_scopes[name] curr.merge(child_scope) else child_scopes[name] = child_scope end end end new(decl, child_scopes) end def merge(new_scope) return unless type = decl&.type return unless new_type = new_scope.decl&.type if type.swift_typealias? && new_type.swift_extension? @children = new_scope.children elsif type.swift_extension? && new_type.swift_typealias? @decl = new_scope.decl end end # Lookup of a name like `Mod.Type.method(arg:)` requires passing # an array of name 'parts' eg. ['Mod', 'Type', 'method(arg:)']. def lookup(parts) return decl if parts.empty? children[parts.first]&.lookup(parts[1...]) end # Look up of a regex matching all children for current level only. def lookup_regex(regex) children.select { |name, _| name.match(regex) } .map { |_, scope| scope.decl }.compact end # Get an array of scopes matching the name parts. def lookup_path(parts) [self] + (children[parts.first]&.lookup_path(parts[1...]) || []) end end attr_reader :root_scope def initialize(all_decls) @root_scope = Scope.new_root(all_decls.group_by(&:module_name)) end # Look up a name and return the matching SourceDeclaration or nil. # # `context` is an optional SourceDeclaration indicating where the text # was found, affects name resolution - see `lookup_context()` below. def lookup(name, context = nil) lookup_name = LookupName.new(name) return lookup_fully_qualified(lookup_name) if lookup_name.fully_qualified? return lookup_guess(lookup_name) if context.nil? lookup_context(lookup_name, context) end # Look up a regex and return all matching top level SourceDeclaration. def lookup_regex(regex) root_scope.children.map { |_, scope| scope.lookup_regex(regex) }.flatten end private # Look up a fully-qualified name, ie. it starts with the module name. def lookup_fully_qualified(lookup_name) root_scope.lookup(lookup_name.parts) end # Look up a top-level name best-effort, searching for a module that # has it before trying the first name-part as a module name. def lookup_guess(lookup_name) root_scope.children.each_value do |module_scope| if result = module_scope.lookup(lookup_name.parts) return result end end lookup_fully_qualified(lookup_name) end # Look up a name from a declaration context, approximately how # Swift resolves names. # # 1 - try and resolve with a common prefix, eg. 'B' from 'T.A' # can match 'T.B', or 'R' from 'S.T.A' can match 'S.R'. # 2 - try and resolve as a top-level symbol from a different module # 3 - (affordance for docs writers) resolve as a child of the context, # eg. 'B' from 'T.A' can match 'T.A.B' *only if* (1,2) fail. # Currently disabled for Swift for back-compatibility. def lookup_context(lookup_name, context) context_scope_path = root_scope.lookup_path(context.fully_qualified_module_name_parts) context_scope = context_scope_path.pop context_scope_path.reverse.each do |scope| if decl = scope.lookup(lookup_name.parts) return decl end end lookup_guess(lookup_name) || (lookup_name.objc? && context_scope.lookup(lookup_name.parts)) end # Helper for name lookup, really a cache for information as we # try various strategies. class LookupName attr_reader :name def initialize(name) @name = name end def fully_qualified? name.start_with?('/') end def objc? name.start_with?('-', '+') end def parts @parts ||= find_parts end private # Turn a name as written into a list of components to # be matched. # Swift: Strip out odd characters and split # ObjC: Compound names look like '+[Class(Category) method:]' # and need to become ['Class(Category)', '+method:'] def find_parts if name =~ /([+-])\[(\w+(?: ?\(\w+\))?) ([\w:]+)\]/ [Regexp.last_match[2], Regexp.last_match[1] + Regexp.last_match[3]] else name .sub(%r{^[@/]}, '') # ignore custom attribute reference, fully-qualified .gsub(/<.*?>/, '') # remove generic parameters .split(%r{(?<!\.)[/.](?!\.)}) # dot or slash, but not '...' .reject(&:empty?) end end end end class SourceDeclaration # Names for a symbol. Permits function parameters to be omitted. def index_names [name, name.sub(/\(.*\)/, '(...)')].uniq end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_declaration.rb
lib/jazzy/source_declaration.rb
# frozen_string_literal: true require 'jazzy/source_declaration/access_control_level' require 'jazzy/source_declaration/type' module Jazzy # rubocop:disable Metrics/ClassLength class SourceDeclaration # kind of declaration (e.g. class, variable, function) attr_accessor :type # static type of declared element (e.g. String.Type -> ()) attr_accessor :typename # Give the item its own page or just inline into parent? def render_as_page? children.any? || (Config.instance.separate_global_declarations && type.global?) end def swift? type.swift_type? end def highlight_language swift? ? Highlighter::SWIFT : Highlighter::OBJC end # When referencing this item from its parent category, # include the content or just link to it directly? def omit_content_from_parent? Config.instance.separate_global_declarations && render_as_page? end # Element containing this declaration in the code attr_accessor :parent_in_code # Logical parent in the documentation. May differ from parent_in_code # because of top-level categories and merged extensions. attr_accessor :parent_in_docs # counterpart of parent_in_docs attr_reader :children def children=(new_children) # Freeze to ensure that parent_in_docs stays in sync @children = new_children.freeze @children.each { |c| c.parent_in_docs = self } end # Chain of parent_in_code from top level to self. (Includes self.) def namespace_path namespace_ancestors + [self] end def namespace_ancestors if parent_in_code parent_in_code.namespace_path else [] end end # 'OuterType.NestedType.method(arg:)' def fully_qualified_name namespace_path.map(&:name).join('.') end # :name doesn't include any generic type params. # This regexp matches any generic type params in parent names. def fully_qualified_name_regexp Regexp.new(namespace_path.map(&:name) .map { |n| Regexp.escape(n) } .join('(?:<.*?>)?\.')) end def fully_qualified_module_name_parts path = namespace_path path.map(&:name).prepend(path.first.module_name).compact end # 'MyModule.OuterType.NestedType.method(arg:)' def fully_qualified_module_name fully_qualified_module_name_parts.join('.') end # List of doc_parent decls, .last is self def docs_path (parent_in_docs&.docs_path || []) + [self] end # If this declaration is an objc category, returns an array with the name # of the extended objc class and the category name itself, i.e. # ["NSString", "MyMethods"], nil otherwise. def objc_category_name name.split(/[()]/) if type.objc_category? end def swift_objc_extension? type.swift_extension? && usr&.start_with?('c:objc') end def swift_extension_objc_name return unless type.swift_extension? && usr usr.split('(cs)').last end # The language in the templates for display def display_language return 'Swift' if swift? Config.instance.hide_objc? ? 'Swift' : 'Objective-C' end def display_declaration return declaration if swift? Config.instance.hide_objc? ? other_language_declaration : declaration end def display_other_language_declaration other_language_declaration unless Config.instance.hide_objc? || Config.instance.hide_swift? end attr_accessor :file attr_accessor :line attr_accessor :column attr_accessor :usr attr_accessor :type_usr attr_accessor :module_name attr_accessor :name attr_accessor :objc_name attr_accessor :declaration attr_accessor :other_language_declaration attr_accessor :abstract attr_accessor :default_impl_abstract attr_accessor :from_protocol_extension attr_accessor :discussion attr_accessor :return attr_accessor :parameters attr_accessor :url attr_accessor :mark attr_accessor :access_control_level attr_accessor :start_line attr_accessor :end_line attr_accessor :nav_order attr_accessor :url_name attr_accessor :deprecated attr_accessor :deprecation_message attr_accessor :unavailable attr_accessor :unavailable_message attr_accessor :generic_requirements attr_accessor :inherited_types attr_accessor :async # The name of the module being documented that contains this # declaration. Only different from module_name when this is # an extension of a type from another module. Nil for guides. attr_accessor :doc_module_name def usage_discouraged? unavailable || deprecated end def filepath CGI.unescape(url) end # Base filename (no extension) for the item def docs_filename result = url_name || name # Workaround functions sharing names with # different argument types (f(a:Int) vs. f(a:String)) return result unless type.swift_global_function? result + "_#{type_usr}" end def constrained_extension? type.swift_extension? && generic_requirements end def mark_for_children if constrained_extension? SourceMark.new_generic_requirements(generic_requirements) else SourceMark.new end end def inherited_types? inherited_types && !inherited_types.empty? end # Is there at least one inherited type that is not in the given list? def other_inherited_types?(unwanted) return false unless inherited_types? inherited_types.any? { |t| !unwanted.include?(t) } end # Pre-Swift 5.6: SourceKit only sets module_name for imported modules # Swift 5.6+: module_name is always set def type_from_doc_module? !type.extension? || (swift? && usr && (module_name.nil? || module_name == doc_module_name)) end # Don't ask the user to write documentation for types being extended # from other modules. Compile errors leave no docs and a `nil` USR. def mark_undocumented? !swift? || (usr && !extension_of_external_type?) end def extension_of_external_type? !module_name.nil? && !Config.instance.module_name?(module_name) end # Is it unclear from context what module the (top-level) decl is from? def ambiguous_module_name?(group_name) extension_of_external_type? || (Config.instance.multiple_modules? && !module_name.nil? && group_name != module_name) end # Does the user need help understanding how to get this declaration? def need_doc_module_note? return false unless Config.instance.multiple_modules? return false if docs_path.first.name == doc_module_name if parent_in_code.nil? # Top-level decls with no page of their own !render_as_page? else # Members added by extension parent_in_code.module_name != doc_module_name end end # Info text for contents page by collapsed item name def declaration_note notes = [ default_impl_abstract ? 'default implementation' : nil, from_protocol_extension ? 'extension method' : nil, async ? 'asynchronous' : nil, need_doc_module_note? ? "from #{doc_module_name}" : nil, ].compact notes.join(', ').upcase_first unless notes.empty? end # For matching where `Self` is equivalent without considering # constraints def simplified_typename typename&.gsub(/<Self .*?>/, '<Self>') end # Is the candidate `SourceDeclaration` probably a default # implementation of this declaration? def default_implementation?(candidate) name == candidate.name && type == candidate.type && simplified_typename == candidate.simplified_typename && async == candidate.async end def readme? false end def alternative_abstract if file = alternative_abstract_file Pathname(file).read end end def alternative_abstract_file abstract_glob.select do |f| # allow Structs.md or Structures.md [name, url_name].include?(File.basename(f).split('.').first) end.first end def abstract_glob return [] unless Config.instance.abstract_glob_configured && Config.instance.abstract_glob Config.instance.abstract_glob.select { |e| File.file? e } end end # rubocop:enable Metrics/ClassLength end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/config.rb
lib/jazzy/config.rb
# frozen_string_literal: true require 'optparse' require 'pathname' require 'uri' require 'jazzy/podspec_documenter' require 'jazzy/source_declaration/access_control_level' module Jazzy # rubocop:disable Metrics/ClassLength class Config # rubocop:disable Naming/AccessorMethodName class Attribute attr_reader :name, :description, :command_line, :config_file_key, :default, :parse, :per_module def initialize(name, description: nil, command_line: nil, default: nil, parse: ->(x) { x }, per_module: false) @name = name.to_s @description = Array(description) @command_line = Array(command_line) @default = default @parse = parse @config_file_key = full_command_line_name || @name @per_module = per_module end def get(config) config.method(name).call end def set_raw(config, val) config.method("#{name}=").call(val) end def set(config, val, mark_configured: true) set_raw(config, config.instance_exec(val, &parse)) config.method("#{name}_configured=").call(true) if mark_configured end def set_to_default(config) set(config, default, mark_configured: false) if default end def set_if_unconfigured(config, val) set(config, val) unless configured?(config) end def configured?(config) config.method("#{name}_configured").call end def attach_to_option_parser(config, opt) return if command_line.empty? opt.on(*command_line, *description) do |val| set(config, val) end end private def full_command_line_name long_option_names = command_line.map do |opt| Regexp.last_match(1) if opt.to_s =~ %r{ ^-- # starts with double dash (?:\[no-\])? # optional prefix for booleans ([^\s]+) # long option name }x end if long_option_name = long_option_names.compact.first long_option_name.tr('-', '_') end end end # rubocop:enable Naming/AccessorMethodName def self.config_attr(name, **opts) attr_accessor name attr_accessor "#{name}_configured" @all_config_attrs ||= [] @all_config_attrs << Attribute.new(name, **opts) end def self.alias_config_attr(name, forward, **opts) alias_method name.to_s, forward.to_s alias_method "#{name}=", "#{forward}=" alias_method "#{name}_configured", "#{forward}_configured" alias_method "#{name}_configured=", "#{forward}_configured=" @all_config_attrs << Attribute.new(name, **opts) end class << self attr_reader :all_config_attrs end attr_accessor :base_path def expand_glob_path(path) Pathname(path).expand_path(base_path) # nil means Pathname.pwd end def expand_path(path) abs_path = expand_glob_path(path) Pathname(Dir[abs_path][0] || abs_path) # Use existing filesystem spelling end def hide_swift? hide_declarations == 'swift' end def hide_objc? hide_declarations == 'objc' end # ──────── Build ──────── # rubocop:disable Layout/ArgumentAlignment config_attr :output, description: 'Folder to output the HTML docs to', command_line: ['-o', '--output FOLDER'], default: 'docs', parse: ->(o) { expand_path(o) } config_attr :clean, command_line: ['-c', '--[no-]clean'], description: ['Delete contents of output directory before running. ', 'WARNING: If --output is set to ~/Desktop, this will ' \ 'delete the ~/Desktop directory.'], default: false config_attr :objc_mode, command_line: '--[no-]objc', description: 'Generate docs for Objective-C.', default: false, per_module: true config_attr :umbrella_header, command_line: '--umbrella-header PATH', description: 'Umbrella header for your Objective-C framework.', parse: ->(uh) { expand_path(uh) }, per_module: true config_attr :framework_root, command_line: '--framework-root PATH', description: 'The root path to your Objective-C framework.', parse: ->(fr) { expand_path(fr) }, per_module: true config_attr :sdk, command_line: '--sdk [iphone|watch|appletv][os|simulator]|macosx', description: 'The SDK for which your code should be built.', default: 'macosx', per_module: true config_attr :hide_declarations, command_line: '--hide-declarations [objc|swift] ', description: 'Hide declarations in the specified language. Given that ' \ 'generating Swift docs only generates Swift declarations, ' \ 'this is useful for hiding a specific interface for ' \ 'either Objective-C or mixed Objective-C and Swift ' \ 'projects.', default: '' config_attr :keep_property_attributes, command_line: '--[no-]keep-property-attributes', description: 'Include the default Objective-C property attributes.', default: false config_attr :config_file, command_line: '--config PATH', description: ['Configuration file (.yaml or .json)', 'Default: .jazzy.yaml in source directory or ancestor'], parse: ->(cf) { expand_path(cf) } config_attr :build_tool_arguments, command_line: ['-b', '--build-tool-arguments arg1,arg2,…argN', Array], description: 'Arguments to forward to xcodebuild, swift build, or ' \ 'sourcekitten.', default: [], per_module: true config_attr :modules, command_line: ['--modules Mod1,Mod2,…ModN', Array], description: 'List of modules to document. Use the config file to set per-module ' \ "build flags, see 'Documenting multiple modules' in the README.", default: [] alias_config_attr :xcodebuild_arguments, :build_tool_arguments, command_line: ['-x', '--xcodebuild-arguments arg1,arg2,…argN', Array], description: 'Back-compatibility alias for build_tool_arguments.' config_attr :sourcekitten_sourcefile, command_line: ['-s', '--sourcekitten-sourcefile filepath1,…filepathN', Array], description: 'File(s) generated from sourcekitten output to parse', parse: ->(paths) { [paths].flatten.map { |path| expand_path(path) } }, default: [], per_module: true config_attr :source_directory, command_line: '--source-directory DIRPATH', description: 'The directory that contains the source to be documented', default: Pathname.pwd, parse: ->(sd) { expand_path(sd) }, per_module: true config_attr :symbolgraph_directory, command_line: '--symbolgraph-directory DIRPATH', description: 'A directory containing a set of Swift Symbolgraph files ' \ 'representing the module to be documented', parse: ->(sd) { expand_path(sd) }, per_module: true config_attr :excluded_files, command_line: ['-e', '--exclude filepath1,filepath2,…filepathN', Array], description: 'Source file pathnames to be excluded from documentation. ' \ 'Supports wildcards.', default: [], parse: ->(files) do Array(files).map { |f| expand_glob_path(f).to_s } end config_attr :included_files, command_line: ['-i', '--include filepath1,filepath2,…filepathN', Array], description: 'Source file pathnames to be included in documentation. ' \ 'Supports wildcards.', default: [], parse: ->(files) do Array(files).map { |f| expand_glob_path(f).to_s } end config_attr :swift_version, command_line: '--swift-version VERSION', default: nil, parse: ->(v) do if v.to_s.empty? nil elsif v.to_f < 2 raise 'jazzy only supports Swift 2.0 or later.' else v end end SWIFT_BUILD_TOOLS = %w[spm xcodebuild symbolgraph].freeze config_attr :swift_build_tool, command_line: "--swift-build-tool #{SWIFT_BUILD_TOOLS.join(' | ')}", description: 'Control whether Jazzy uses Swift Package Manager, ' \ 'xcodebuild, or swift-symbolgraph to build the module ' \ 'to be documented. By default it uses xcodebuild if ' \ 'there is a .xcodeproj file in the source directory.', parse: ->(tool) do return tool.to_sym if SWIFT_BUILD_TOOLS.include?(tool) raise "Unsupported swift_build_tool #{tool}, " \ "supported values: #{SWIFT_BUILD_TOOLS.join(', ')}" end # ──────── Metadata ──────── config_attr :author_name, command_line: ['-a', '--author AUTHOR_NAME'], description: 'Name of author to attribute in docs (e.g. Realm)', default: '' config_attr :author_url, command_line: ['-u', '--author_url URL'], description: 'Author URL of this project (e.g. https://realm.io)', default: '', parse: ->(u) { URI(u) } config_attr :module_name, command_line: ['-m', '--module MODULE_NAME'], description: 'Name of module being documented. (e.g. RealmSwift)', default: '', per_module: true config_attr :version, command_line: '--module-version VERSION', description: 'Version string to use as part of the default docs ' \ 'title and inside the docset.', default: '1.0' config_attr :title, command_line: '--title TITLE', description: 'Title to display at the top of each page, overriding the ' \ 'default generated from module name and version.', default: '' config_attr :copyright, command_line: '--copyright COPYRIGHT_MARKDOWN', description: 'copyright markdown rendered at the bottom of the docs pages' config_attr :readme_path, command_line: '--readme FILEPATH', description: 'The path to a markdown README file', parse: ->(rp) { expand_path(rp) } config_attr :readme_title, command_line: '--readme-title TITLE', description: 'The title for the README in the generated documentation' config_attr :documentation_glob, command_line: '--documentation GLOB', description: 'Glob that matches available documentation', parse: ->(dg) { Pathname.glob(dg) } config_attr :abstract_glob, command_line: '--abstract GLOB', description: 'Glob that matches available abstracts for categories', parse: ->(ag) { Pathname.glob(ag) } config_attr :podspec, command_line: '--podspec FILEPATH', description: 'A CocoaPods Podspec that describes the Swift library to ' \ 'document', parse: ->(ps) { PodspecDocumenter.create_podspec(Pathname(ps)) if ps }, default: Dir['*.podspec{,.json}'].first config_attr :pod_sources, command_line: ['--pod-sources url1,url2,…urlN', Array], description: 'A list of sources to find pod dependencies. Used only ' \ 'with --podspec when the podspec contains references to ' \ 'privately hosted pods. You must include the default pod ' \ 'source if public pods are also used.', default: [] config_attr :docset_icon, command_line: '--docset-icon FILEPATH', parse: ->(di) { expand_path(di) } config_attr :docset_path, command_line: '--docset-path DIRPATH', description: 'The relative path for the generated docset' config_attr :docset_title, command_line: '--docset-title TITLE', description: 'The title of the generated docset. A simplified version ' \ 'is used for the filenames associated with the docset. If the ' \ 'option is not set then the name of the module being documented is ' \ 'used as the docset title.' # ──────── URLs ──────── config_attr :root_url, command_line: ['-r', '--root-url URL'], description: 'Absolute URL root where these docs will be stored', # ensure trailing slash for correct URI.join() parse: ->(r) { URI(r.sub(%r{/?$}, '/')) } config_attr :dash_url, command_line: ['-d', '--dash_url URL'], description: 'Location of the dash XML feed ' \ 'e.g. https://realm.io/docsets/realm.xml)', parse: ->(d) { URI(d) } SOURCE_HOSTS = %w[github gitlab bitbucket].freeze config_attr :source_host, command_line: "--source-host #{SOURCE_HOSTS.join(' | ')}", description: ['The source-code hosting site to be linked from documentation.', 'This setting affects the logo image and link format.', "Default: 'github'"], default: 'github', parse: ->(host) do return host.to_sym if SOURCE_HOSTS.include?(host) raise "Unsupported source_host '#{host}', " \ "supported values: #{SOURCE_HOSTS.join(', ')}" end config_attr :source_host_url, command_line: ['--source-host-url URL'], description: ["URL to link from the source host's logo.", 'For example https://github.com/realm/realm-cocoa'], parse: ->(g) { URI(g) } alias_config_attr :github_url, :source_host_url, command_line: ['-g', '--github_url URL'], description: 'Back-compatibility alias for source_host_url.' config_attr :source_host_files_url, command_line: '--source-host-files-url PREFIX', description: [ "The base URL on the source host of the project's files, to link " \ 'from individual declarations.', 'For example https://github.com/realm/realm-cocoa/tree/v0.87.1', ] alias_config_attr :github_file_prefix, :source_host_files_url, command_line: '--github-file-prefix PREFIX', description: 'Back-compatibility alias for source_host_files_url' config_attr :docset_playground_url, command_line: '--docset-playground-url URL', description: 'URL of an interactive playground to demonstrate the ' \ 'framework, linked to from the docset.' # ──────── Doc generation options ──────── config_attr :disable_search, command_line: '--disable-search', description: 'Avoid generating a search index. ' \ 'Search is available in some themes.', default: false config_attr :skip_documentation, command_line: '--skip-documentation', description: 'Will skip the documentation generation phase.', default: false config_attr :min_acl, command_line: '--min-acl [private | fileprivate | internal | package | public | open]', description: 'minimum access control level to document', default: 'public', parse: ->(acl) do SourceDeclaration::AccessControlLevel.from_human_string(acl) end config_attr :skip_undocumented, command_line: '--[no-]skip-undocumented', description: "Don't document declarations that have no documentation " \ 'comments.', default: false config_attr :hide_documentation_coverage, command_line: '--[no-]hide-documentation-coverage', description: 'Hide "(X% documented)" from the generated documents', default: false config_attr :custom_categories, description: 'Custom navigation categories to replace the standard ' \ "'Classes', 'Protocols', etc. Types not explicitly named " \ 'in a custom category appear in generic groups at the ' \ 'end. Example: https://git.io/v4Bcp', default: [] config_attr :custom_categories_unlisted_prefix, description: "Prefix for navigation section names that aren't " \ 'explicitly listed in `custom_categories`.', default: 'Other ' config_attr :hide_unlisted_documentation, command_line: '--[no-]hide-unlisted-documentation', description: "Don't include documentation in the sidebar from the " \ "`documentation` config value that aren't explicitly " \ 'listed in `custom_categories`.', default: false config_attr :custom_head, command_line: '--head HTML', description: 'Custom HTML to inject into <head></head>.', default: '' BUILTIN_THEME_DIR = Pathname(__dir__) + 'themes' BUILTIN_THEMES = BUILTIN_THEME_DIR.children(false).map(&:to_s) config_attr :theme_directory, command_line: "--theme [#{BUILTIN_THEMES.join(' | ')} | DIRPATH]", description: "Which theme to use. Specify either 'apple' (default), " \ 'one of the other built-in theme names, or the path to ' \ 'your mustache templates and other assets for a custom ' \ 'theme.', default: 'apple', parse: ->(t) do if BUILTIN_THEMES.include?(t) BUILTIN_THEME_DIR + t else expand_path(t) end end config_attr :use_safe_filenames, command_line: '--use-safe-filenames', description: 'Replace unsafe characters in filenames with an encoded ' \ 'representation. This will reduce human readability of ' \ 'some URLs, but may be necessary for projects that ' \ 'expose filename-unfriendly functions such as /(_:_:)', default: false config_attr :template_directory, command_line: ['-t', '--template-directory DIRPATH'], description: 'DEPRECATED: Use --theme instead.', parse: ->(_) do raise '--template-directory (-t) is deprecated: use --theme instead.' end config_attr :assets_directory, command_line: '--assets-directory DIRPATH', description: 'DEPRECATED: Use --theme instead.', parse: ->(_) do raise '--assets-directory is deprecated: use --theme instead.' end config_attr :undocumented_text, command_line: '--undocumented-text UNDOCUMENTED_TEXT', description: 'Default text for undocumented symbols. The default ' \ 'is "Undocumented", put "" if no text is required', default: 'Undocumented' config_attr :separate_global_declarations, command_line: '--[no-]separate-global-declarations', description: 'Create separate pages for all global declarations ' \ "(classes, structures, enums etc.) even if they don't " \ 'have children.', default: false config_attr :include_spi_declarations, command_line: '--[no-]include-spi-declarations', description: 'Include Swift declarations marked `@_spi` even if ' \ '--min-acl is set to `public` or `open`.', default: false MERGE_MODULES = %w[all extensions none].freeze config_attr :merge_modules, command_line: "--merge-modules #{MERGE_MODULES.join(' | ')}", description: 'Control how to display declarations from multiple ' \ 'modules. `all`, the default, places all declarations of the ' \ "same kind together. `none` keeps each module's declarations " \ 'separate. `extensions` is like `none` but merges ' \ 'cross-module extensions into their extended type.', default: 'all', parse: ->(merge) do return merge.to_sym if MERGE_MODULES.include?(merge) raise "Unsupported merge_modules #{merge}, " \ "supported values: #{MERGE_MODULES.join(', ')}" end # rubocop:enable Layout/ArgumentAlignment def initialize self.class.all_config_attrs.each do |attr| attr.set_to_default(self) end end def theme_directory=(theme_directory) @theme_directory = theme_directory Doc.template_path = theme_directory + 'templates' end def self.parse! config = new config.parse_command_line config.parse_config_file PodspecDocumenter.apply_config_defaults(config.podspec, config) config.set_module_configs config.validate config end def warning(message) warn "WARNING: #{message}" end # rubocop:disable Metrics/MethodLength def parse_command_line OptionParser.new do |opt| opt.banner = 'Usage: jazzy' opt.separator '' opt.separator 'Options' self.class.all_config_attrs.each do |attr| attr.attach_to_option_parser(self, opt) end opt.on('-v', '--version', 'Print version number') do puts "jazzy version: #{Jazzy::VERSION}" exit end opt.on('-h', '--help [TOPIC]', 'Available topics:', ' usage Command line options (this help message)', ' config Configuration file options', '...or an option keyword, e.g. "dash"') do |topic| case topic when 'usage', nil puts opt when 'config' print_config_file_help else print_option_help(topic) end exit end end.parse! unless ARGV.empty? warning "Leftover unused command-line text: #{ARGV}" end end def parse_config_file config_path = locate_config_file return unless config_path self.base_path = config_path.parent puts "Using config file #{config_path}" config_file = read_config_file(config_path) attrs_by_conf_key, attrs_by_name = grouped_attributes parse_config_hash(config_file, attrs_by_conf_key, attrs_by_name) end def parse_config_hash(hash, attrs_by_conf_key, attrs_by_name, override: false) hash.each do |key, value| unless attr = attrs_by_conf_key[key] message = "Unknown config file attribute #{key.inspect}" if matching_name = attrs_by_name[key] message += " (Did you mean #{matching_name.first.config_file_key.inspect}?)" end warning message next end setter = override ? :set : :set_if_unconfigured attr.first.method(setter).call(self, value) end end # Find keyed versions of the attributes, by config file key and then name-in-code # Optional block allows filtering/overriding of attribute list. def grouped_attributes attrs = self.class.all_config_attrs attrs = yield attrs if block_given? %i[config_file_key name].map do |property| attrs.group_by(&property) end end def validate if source_host_configured && source_host_url.nil? && source_host_files_url.nil? warning 'Option `source_host` is set but has no effect without either ' \ '`source_host_url` or `source_host_files_url`.' end if modules_configured && module_name_configured raise 'Options `modules` and `module` are both set which is not supported. ' \ 'To document multiple modules, use just `modules`.' end if modules_configured && podspec_configured raise 'Options `modules` and `podspec` are both set which is not supported.' end module_configs.each(&:validate_module) end def validate_module if objc_mode && build_tool_arguments_configured && (framework_root_configured || umbrella_header_configured) warning 'Option `build_tool_arguments` is set: values passed to ' \ '`framework_root` or `umbrella_header` may be ignored.' end end # rubocop:enable Metrics/MethodLength # Module Configs # # The user can enter module information in three different ways. This # consolidates them into one view for the rest of the code. # # 1) Single module, back-compatible # --module Foo etc etc (or not given at all) # # 2) Multiple modules, simple, sharing build params # --modules Foo,Bar,Baz --source-directory Xyz # # 3) Multiple modules, custom, different build params but # inheriting others from the top level. # This is config-file only. # - modules # - module: Foo # source_directory: Xyz # build_tool_arguments: [a, b, c] # # After this we're left with `config.module_configs` that is an # array of `Config` objects. attr_reader :module_configs attr_reader :module_names def set_module_configs @module_configs = parse_module_configs @module_names = module_configs.map(&:module_name) @module_names_set = Set.new(module_names) end def module_name?(name) @module_names_set.include?(name) end def multiple_modules? @module_names.count > 1 end def parse_module_configs return [self] unless modules_configured raise 'Config file key `modules` must be an array' unless modules.is_a?(Array) if modules.first.is_a?(String) # Massage format (2) into (3) self.modules = modules.map { |mod| { 'module' => mod } } end # Allow per-module overrides of only some config options attrs_by_conf_key, attrs_by_name = grouped_attributes { |attr| attr.select(&:per_module) } modules.map do |module_hash| mod_name = module_hash['module'] || '' raise 'Missing `modules.module` config key' if mod_name.empty? dup.tap do |module_config| module_config.parse_config_hash( module_hash, attrs_by_conf_key, attrs_by_name, override: true ) end end end # For podspec query def module_name_known? module_name_configured || modules_configured end def locate_config_file return config_file if config_file source_directory.ascend do |dir| candidate = dir.join('.jazzy.yaml') return candidate if candidate.exist? end nil end def read_config_file(file) case File.extname(file) when '.json' JSON.parse(File.read(file)) when '.yaml', '.yml' YAML.safe_load(File.read(file)) else raise "Config file must be .yaml or .json, but got #{file.inspect}" end end def print_config_file_help puts <<-_EOS_ By default, jazzy looks for a file named ".jazzy.yaml" in the source directory and its ancestors. You can override the config file location with --config. (The source directory is the current working directory by default. You can override that with --source-directory.) The config file can be in YAML or JSON format. Available options are: _EOS_ .gsub(/^ +/, '') print_option_help end def print_option_help(topic = '') found = false self.class.all_config_attrs.each do |attr| match = ([attr.name] + attr.command_line).any? do |opt| opt.to_s.include?(topic) end if match found = true puts puts attr.name.to_s.tr('_', ' ').upcase puts puts " Config file: #{attr.config_file_key}" cmd_line_forms = attr.command_line.select { |opt| opt.is_a?(String) } if cmd_line_forms.any? puts " Command line: #{cmd_line_forms.join(', ')}" end puts print_attr_description(attr) end end warn "Unknown help topic #{topic.inspect}" unless found end def print_attr_description(attr) attr.description.each { |line| puts " #{line}" } if attr.default && attr.default != '' puts " Default: #{attr.default}" end end #-------------------------------------------------------------------------# # @!group Singleton # @return [Config] the current config instance creating one if needed. # def self.instance @instance ||= new end # Sets the current config instance. If set to nil the config will be # recreated when needed. # # @param [Config, Nil] the instance. # # @return [void] # class << self attr_writer :instance end # Provides support for accessing the configuration instance in other # scopes. # module Mixin def config Config.instance end end end # rubocop:enable Metrics/ClassLength end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/gem_version.rb
lib/jazzy/gem_version.rb
# frozen_string_literal: true module Jazzy VERSION = '0.15.4' unless defined? Jazzy::VERSION end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_declaration/access_control_level.rb
lib/jazzy/source_declaration/access_control_level.rb
# frozen_string_literal: true module Jazzy class SourceDeclaration class AccessControlLevel include Comparable # Order matters LEVELS = %i[private fileprivate internal package public open].freeze LEVELS_INDEX = LEVELS.to_h { |i| [i, LEVELS.index(i)] }.freeze attr_reader :level def initialize(level) @level = level end # From a SourceKit accessibility string def self.from_accessibility(accessibility) return nil if accessibility.nil? if accessibility =~ /^source\.lang\.swift\.accessibility\.(.*)$/ && (matched = Regexp.last_match(1).to_sym) && !LEVELS_INDEX[matched].nil? return new(matched) end raise "cannot initialize AccessControlLevel with '#{accessibility}'" end # From a SourceKit declaration hash def self.from_doc(doc) return AccessControlLevel.internal if implicit_deinit?(doc) from_documentation_attribute(doc) || from_accessibility(doc['key.accessibility']) || from_doc_explicit_declaration(doc) || AccessControlLevel.internal # fallback on internal ACL end # Workaround `deinit` being always technically public def self.implicit_deinit?(doc) doc['key.name'] == 'deinit' && from_doc_explicit_declaration(doc).nil? end # From a Swift declaration def self.from_doc_explicit_declaration(doc) declaration = doc['key.parsed_declaration'] LEVELS.each do |level| if declaration =~ /\b#{level}\b/ return send(level) end end nil end # From a config instruction def self.from_human_string(string) normalized = string.to_s.downcase.to_sym if LEVELS_INDEX[normalized].nil? raise "cannot initialize AccessControlLevel with '#{string}'" end send(normalized) end # From a @_documentation(visibility:) attribute def self.from_documentation_attribute(doc) if doc['key.annotated_decl'] =~ /@_documentation\(\s*visibility\s*:\s*(\w+)/ from_human_string(Regexp.last_match[1]) end end # Define `AccessControlLevel.public` etc. LEVELS.each do |level| define_singleton_method(level) do new(level) end end # Comparing access levels def <=>(other) LEVELS_INDEX[level] <=> LEVELS_INDEX[other.level] end def included_levels LEVELS_INDEX.select { |_, v| v >= LEVELS_INDEX[level] }.keys end def excluded_levels LEVELS_INDEX.select { |_, v| v < LEVELS_INDEX[level] }.keys end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/source_declaration/type.rb
lib/jazzy/source_declaration/type.rb
# frozen_string_literal: true require 'logger' require 'active_support' require 'active_support/inflector' module Jazzy class SourceDeclaration # rubocop:disable Metrics/ClassLength class Type def self.all TYPES.keys.map { |k| new(k) }.reject { |t| t.name.nil? } end attr_reader :kind def initialize(kind, declaration = nil) kind = fixup_kind(kind, declaration) if declaration @kind = kind @type = TYPES[kind] end # Improve kind from full declaration def fixup_kind(kind, declaration) if kind == 'source.lang.swift.decl.class' && declaration.include?( '<syntaxtype.keyword>actor</syntaxtype.keyword>', ) 'source.lang.swift.decl.actor' else kind end end def dash_type @type && @type[:dash] end def name @type && @type[:jazzy] end # kinds that are 'global' and should get their own pages # with --separate-global-declarations def global? @type && @type[:global] end # name to use for type subdirectory in URLs for back-compatibility def url_name @type && (@type[:url] || @type[:jazzy]) end def name_controlled_manually? !kind.start_with?('source') # "'source'.lang..." for Swift # or "'source'kitten.source..." for Objective-C # but not "Overview" for navigation groups. end def plural_name name.pluralize end def plural_url_name url_name.pluralize end def objc_mark? kind == 'sourcekitten.source.lang.objc.mark' end # covers MARK: TODO: FIXME: comments def swift_mark? kind == 'source.lang.swift.syntaxtype.comment.mark' end def mark? objc_mark? || swift_mark? end # mark that should start a new task section def task_mark?(name) objc_mark? || (swift_mark? && name.start_with?('MARK: ')) end def objc_enum? kind == 'sourcekitten.source.lang.objc.decl.enum' end def objc_typedef? kind == 'sourcekitten.source.lang.objc.decl.typedef' end def objc_category? kind == 'sourcekitten.source.lang.objc.decl.category' end def objc_class? kind == 'sourcekitten.source.lang.objc.decl.class' end def swift_type? kind.include? 'swift' end def swift_enum_case? kind == 'source.lang.swift.decl.enumcase' end def swift_enum_element? kind == 'source.lang.swift.decl.enumelement' end def should_document? declaration? && !param? && !generic_type_param? end def declaration? kind.start_with?('source.lang.swift.decl', 'sourcekitten.source.lang.objc.decl') end def extension? swift_extension? || objc_category? end def swift_extension? kind =~ /^source\.lang\.swift\.decl\.extension.*/ end def swift_extensible? kind =~ /^source\.lang\.swift\.decl\.(class|struct|protocol|enum|actor)$/ end def swift_protocol? kind == 'source.lang.swift.decl.protocol' end def swift_typealias? kind == 'source.lang.swift.decl.typealias' end def swift_global_function? kind == 'source.lang.swift.decl.function.free' end def param? # SourceKit strangely categorizes initializer parameters as local # variables, so both kinds represent a parameter in jazzy. ['source.lang.swift.decl.var.parameter', 'source.lang.swift.decl.var.local'].include?(kind) end def generic_type_param? kind == 'source.lang.swift.decl.generic_type_param' end def swift_variable? kind.start_with?('source.lang.swift.decl.var') end def objc_unexposed? kind == 'sourcekitten.source.lang.objc.decl.unexposed' end OVERVIEW_KIND = 'Overview' def self.overview Type.new(OVERVIEW_KIND) end def overview? kind == OVERVIEW_KIND end MARKDOWN_KIND = 'document.markdown' def self.markdown Type.new(MARKDOWN_KIND) end def markdown? kind == MARKDOWN_KIND end def hash kind.hash end alias equals == def ==(other) other && kind == other.kind end TYPES = { # Markdown MARKDOWN_KIND => { jazzy: 'Guide', dash: 'Guide', }.freeze, # Group/Overview OVERVIEW_KIND => { jazzy: nil, dash: 'Section', }.freeze, # Objective-C 'sourcekitten.source.lang.objc.decl.unexposed' => { jazzy: 'Unexposed', dash: 'Unexposed', }.freeze, 'sourcekitten.source.lang.objc.decl.category' => { jazzy: 'Category', dash: 'Extension', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.class' => { jazzy: 'Class', dash: 'Class', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.constant' => { jazzy: 'Constant', dash: 'Constant', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.enum' => { jazzy: 'Enumeration', url: 'Enum', dash: 'Enum', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.enumcase' => { jazzy: 'Enumeration Case', dash: 'Case', }.freeze, 'sourcekitten.source.lang.objc.decl.initializer' => { jazzy: 'Initializer', dash: 'Initializer', }.freeze, 'sourcekitten.source.lang.objc.decl.method.class' => { jazzy: 'Class Method', dash: 'Method', }.freeze, 'sourcekitten.source.lang.objc.decl.method.instance' => { jazzy: 'Instance Method', dash: 'Method', }.freeze, 'sourcekitten.source.lang.objc.decl.property' => { jazzy: 'Property', dash: 'Property', }.freeze, 'sourcekitten.source.lang.objc.decl.protocol' => { jazzy: 'Protocol', dash: 'Protocol', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.typedef' => { jazzy: 'Type Definition', dash: 'Type', global: true, }.freeze, 'sourcekitten.source.lang.objc.mark' => { jazzy: 'Mark', dash: 'Mark', }.freeze, 'sourcekitten.source.lang.objc.decl.function' => { jazzy: 'Function', dash: 'Function', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.struct' => { jazzy: 'Structure', url: 'Struct', dash: 'Struct', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.union' => { jazzy: 'Union', dash: 'Union', global: true, }.freeze, 'sourcekitten.source.lang.objc.decl.field' => { jazzy: 'Field', dash: 'Field', }.freeze, 'sourcekitten.source.lang.objc.decl.ivar' => { jazzy: 'Instance Variable', dash: 'Ivar', }.freeze, 'sourcekitten.source.lang.objc.module.import' => { jazzy: 'Module', dash: 'Module', }.freeze, # Swift 'source.lang.swift.decl.actor' => { jazzy: 'Actor', dash: 'Actor', global: true, }.freeze, 'source.lang.swift.decl.function.accessor.address' => { jazzy: 'Addressor', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.accessor.didset' => { jazzy: 'didSet Observer', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.accessor.getter' => { jazzy: 'Getter', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.accessor.mutableaddress' => { jazzy: 'Mutable Addressor', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.accessor.setter' => { jazzy: 'Setter', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.accessor.willset' => { jazzy: 'willSet Observer', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.operator' => { jazzy: 'Operator', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.operator.infix' => { jazzy: 'Infix Operator', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.operator.postfix' => { jazzy: 'Postfix Operator', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.operator.prefix' => { jazzy: 'Prefix Operator', dash: 'Function', }.freeze, 'source.lang.swift.decl.function.method.class' => { jazzy: 'Class Method', dash: 'Method', }.freeze, 'source.lang.swift.decl.var.class' => { jazzy: 'Class Variable', dash: 'Variable', }.freeze, 'source.lang.swift.decl.class' => { jazzy: 'Class', dash: 'Class', global: true, }.freeze, 'source.lang.swift.decl.function.constructor' => { jazzy: 'Initializer', dash: 'Constructor', }.freeze, 'source.lang.swift.decl.function.destructor' => { jazzy: 'Deinitializer', dash: 'Method', }.freeze, 'source.lang.swift.decl.var.global' => { jazzy: 'Global Variable', dash: 'Global', global: true, }.freeze, 'source.lang.swift.decl.enumcase' => { jazzy: 'Enumeration Case', dash: 'Case', }.freeze, 'source.lang.swift.decl.enumelement' => { jazzy: 'Enumeration Element', dash: 'Element', }.freeze, 'source.lang.swift.decl.enum' => { jazzy: 'Enumeration', url: 'Enum', dash: 'Enum', global: true, }.freeze, 'source.lang.swift.decl.extension' => { jazzy: 'Extension', dash: 'Extension', global: true, }.freeze, 'source.lang.swift.decl.extension.class' => { jazzy: 'Class Extension', dash: 'Extension', global: true, }.freeze, 'source.lang.swift.decl.extension.enum' => { jazzy: 'Enumeration Extension', dash: 'Extension', global: true, }.freeze, 'source.lang.swift.decl.extension.protocol' => { jazzy: 'Protocol Extension', dash: 'Extension', global: true, }.freeze, 'source.lang.swift.decl.extension.struct' => { jazzy: 'Structure Extension', dash: 'Extension', global: true, }.freeze, 'source.lang.swift.decl.function.free' => { jazzy: 'Function', dash: 'Function', global: true, }.freeze, 'source.lang.swift.decl.function.method.instance' => { jazzy: 'Instance Method', dash: 'Method', }.freeze, 'source.lang.swift.decl.var.instance' => { jazzy: 'Instance Variable', dash: 'Property', }.freeze, 'source.lang.swift.decl.var.local' => { jazzy: 'Local Variable', dash: 'Variable', }.freeze, 'source.lang.swift.decl.var.parameter' => { jazzy: 'Parameter', dash: 'Parameter', }.freeze, 'source.lang.swift.decl.protocol' => { jazzy: 'Protocol', dash: 'Protocol', global: true, }.freeze, 'source.lang.swift.decl.function.method.static' => { jazzy: 'Static Method', dash: 'Method', }.freeze, 'source.lang.swift.decl.var.static' => { jazzy: 'Static Variable', dash: 'Variable', }.freeze, 'source.lang.swift.decl.struct' => { jazzy: 'Structure', url: 'Struct', dash: 'Struct', global: true, }.freeze, 'source.lang.swift.decl.function.subscript' => { jazzy: 'Subscript', dash: 'Method', }.freeze, 'source.lang.swift.decl.typealias' => { jazzy: 'Type Alias', url: 'Typealias', dash: 'Alias', global: true, }.freeze, 'source.lang.swift.decl.generic_type_param' => { jazzy: 'Generic Type Parameter', dash: 'Parameter', }.freeze, 'source.lang.swift.decl.associatedtype' => { jazzy: 'Associated Type', dash: 'Alias', }.freeze, 'source.lang.swift.decl.macro' => { jazzy: 'Macro', dash: 'Macro', }.freeze, }.freeze end # rubocop:enable Metrics/ClassLength end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/graph.rb
lib/jazzy/symbol_graph/graph.rb
# frozen_string_literal: true # rubocop:disable Metrics/ClassLength module Jazzy module SymbolGraph # A Graph is the coordinator to import a symbolgraph json file. # Deserialize it to Symbols and Relationships, then rebuild # the AST shape using SymNodes and ExtNodes and extract SourceKit json. class Graph attr_accessor :module_name # Our module attr_accessor :ext_module_name # Module being extended attr_accessor :symbol_nodes # usr -> SymNode attr_accessor :relationships # [Relationship] attr_accessor :ext_nodes # (usr, constraints) -> ExtNode # Parse the JSON into flat tables of data def initialize(json, module_name, ext_module_name) self.module_name = module_name self.ext_module_name = ext_module_name graph = JSON.parse(json, symbolize_names: true) self.symbol_nodes = {} self.ext_nodes = {} graph[:symbols].each do |hash| symbol = Symbol.new(hash) if symbol.extension? node = ExtSymNode.new(symbol) ext_nodes[node.ext_key] = node else symbol_nodes[symbol.usr] = SymNode.new(symbol) end end self.relationships = graph[:relationships].map { |hash| Relationship.new(hash) } end # ExtNode index. ExtKey (type USR, extension constraints) -> ExtNode. # This minimizes the number of extensions def add_ext_member(type_usr, member_node, constraints) key = ExtKey.new(type_usr, constraints.ext) if ext_node = ext_nodes[key] ext_node.add_child(member_node) else ext_nodes[key] = ExtNode.new_for_member(type_usr, member_node, constraints) end end def add_ext_conformance(type_usr, type_name, protocol, constraints) key = ExtKey.new(type_usr, constraints.ext) if ext_node = ext_nodes[key] ext_node.add_conformance(protocol) else ext_nodes[key] = ExtNode.new_for_conformance(type_usr, type_name, protocol, constraints) end end # Increasingly desparate ways to find the name of the symbol # at the target end of a relationship def rel_target_name(rel, target_node) target_node&.symbol&.name || rel.target_fallback || Jazzy::SymbolGraph.demangle(rel.target_usr) end # Same for the source end. Less help from the tool here def rel_source_name(rel, source_node) source_node&.qualified_name || Jazzy::SymbolGraph.demangle(rel.source_usr) end # Protocol conformance is redundant if it's unconditional # and already expressed in the type's declaration. # # Skip implementation-detail conformances. def redundant_conformance?(rel, type, protocol) return false unless type (rel.constraints.empty? && type.conformance?(protocol)) || (type.actor? && rel.actor_protocol?) end # source is a member/protocol requirement of target def rebuild_member(rel, source, target) return unless source source.protocol_requirement = rel.protocol_requirement? constraints = ExtConstraints.new(target&.constraints, source.unique_context_constraints(target)) # Add to its parent or invent an extension unless target&.add_child?(source, constraints.ext) add_ext_member(rel.target_usr, source, constraints) end end # "source : target" either from type decl or ext decl def rebuild_conformance(rel, source, target) protocol_name = rel_target_name(rel, target) return if redundant_conformance?(rel, source, protocol_name) type_constraints = source&.constraints || [] constraints = ExtConstraints.new(type_constraints, rel.constraints - type_constraints) # Create an extension or enhance an existing one add_ext_conformance(rel.source_usr, rel_source_name(rel, source), protocol_name, constraints) end # "source is a default implementation of protocol requirement target" def rebuild_default_implementation(_rel, source, target) return unless source unless target && (target_parent = target.parent) && target_parent.is_a?(SymNode) # Could probably figure this out with demangle, but... warn "Can't resolve membership of default implementation " \ "#{source.symbol.usr}." source.unlisted = true return end constraints = ExtConstraints.new(target_parent.constraints, source.unique_context_constraints(target_parent)) add_ext_member(target_parent.symbol.usr, source, constraints) end # "source is a class that inherits from target" def rebuild_inherits(_rel, source, target) if source && target source.superclass_name = target.symbol.name end end # "References to fake_usr should be real_usr" def unalias_extensions(fake_usr, real_usr) ext_nodes.each_pair do |key, ext| if key.usr == fake_usr ext.real_usr = real_usr end end end # Process a structural relationship to link nodes def rebuild_rel(rel) source = symbol_nodes[rel.source_usr] target = symbol_nodes[rel.target_usr] case rel.kind when :memberOf, :optionalRequirementOf, :requirementOf rebuild_member(rel, source, target) when :conformsTo rebuild_conformance(rel, source, target) when :defaultImplementationOf rebuild_default_implementation(rel, source, target) when :inheritsFrom rebuild_inherits(rel, source, target) when :extensionTo unalias_extensions(rel.source_usr, rel.target_usr) end # don't seem to care about: # - overrides: not bothered, also unimplemented for protocols end # Rebuild the AST structure and convert to SourceKit def to_sourcekit relationships.sort.each { |r| rebuild_rel(r) } root_symbol_nodes = symbol_nodes.values .select(&:top_level_decl?) .sort .map { |n| n.to_sourcekit(module_name) } root_ext_nodes = ext_nodes.values .sort .map { |n| n.to_sourcekit(module_name, ext_module_name) } { 'key.diagnostic_stage' => 'parse', 'key.substructure' => root_symbol_nodes + root_ext_nodes, } end end end end # rubocop:enable Metrics/ClassLength
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/relationship.rb
lib/jazzy/symbol_graph/relationship.rb
# frozen_string_literal: true module Jazzy module SymbolGraph # A Relationship is a tidied-up SymbolGraph JSON object class Relationship attr_accessor :kind attr_accessor :source_usr attr_accessor :target_usr attr_accessor :target_fallback # can be nil attr_accessor :constraints # array, can be empty # Order matters: defaultImplementationOf after the protocols # have been defined; extensionTo after all the extensions have # been discovered. KINDS = %w[memberOf conformsTo overrides inheritsFrom requirementOf optionalRequirementOf defaultImplementationOf extensionTo].freeze KINDS_INDEX = KINDS.to_h { |i| [i.to_sym, KINDS.index(i)] }.freeze def protocol_requirement? %i[requirementOf optionalRequirementOf].include? kind end def default_implementation? kind == :defaultImplementationOf end def extension_to? kind == :extensionTo end # Protocol conformances added by compiler to actor decls that # users aren't interested in. def actor_protocol? %w[Actor AnyActor Sendable].include?(target_fallback) end def initialize(hash) kind = hash[:kind] unless KINDS.include?(kind) raise "Unknown relationship kind '#{kind}'" end self.kind = kind.to_sym self.source_usr = hash[:source] self.target_usr = hash[:target] if fallback = hash[:targetFallback] # Strip the leading module name self.target_fallback = fallback.sub(/^.*?\./, '') end self.constraints = Constraint.new_list(hash[:swiftConstraints] || []) end # Sort order include Comparable def <=>(other) return 0 if kind == other.kind KINDS_INDEX[kind] <=> KINDS_INDEX[other.kind] end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/sym_node.rb
lib/jazzy/symbol_graph/sym_node.rb
# frozen_string_literal: true module Jazzy module SymbolGraph # The rebuilt syntax tree is made of nodes that either match # symbols or that we fabricate for extensions. This is the common # treeishness. class BaseNode attr_accessor :children # array, can be empty attr_accessor :parent # can be nil def initialize self.children = [] end def add_child(child) child.parent = self children.append(child) end def add_children_to_sourcekit(hash, module_name) unless children.empty? hash['key.substructure'] = children.sort.map { |c| c.to_sourcekit(module_name) } end end end # A SymNode is a node of the reconstructed syntax tree holding a symbol. # It can turn itself into SourceKit and helps decode extensions. class SymNode < BaseNode attr_accessor :symbol attr_writer :override attr_writer :protocol_requirement attr_writer :unlisted attr_accessor :superclass_name def override? @override end def protocol_requirement? @protocol_requirement end def top_level_decl? !@unlisted && parent.nil? end def initialize(symbol) self.symbol = symbol super() end def qualified_name symbol.path_components.join('.') end def parent_qualified_name symbol.path_components[0...-1].join('.') end def protocol? symbol.kind.end_with?('protocol') end def actor? symbol.kind.end_with?('actor') end def constraints symbol.constraints end # Add another SymNode as a member if possible. # It must go in an extension if either: # - it has different generic constraints to us; or # - we're a protocol and it's a default impl / ext method def add_child?(node, unique_context_constraints) unless unique_context_constraints.empty? && (!protocol? || node.protocol_requirement?) return false end add_child(node) true end # The `Constraint`s on this decl that are both: # 1. Unique, ie. not just inherited from its context; and # 2. Constraining the *context's* gen params rather than our own. def unique_context_constraints(context) return symbol.constraints unless context new_generic_type_params = symbol.generic_type_params - context.symbol.generic_type_params (symbol.constraints - context.symbol.constraints) .select { |con| con.type_names.disjoint?(new_generic_type_params) } end # Messy check whether we need to fabricate an extension for a protocol # conformance: don't bother if it's already in the type declaration. def conformance?(protocol) return false unless symbol.declaration =~ /(?<=:).*?(?=(where|$))/ Regexp.last_match[0] =~ /\b#{protocol}\b/ end # Generate the 'where' clause for the declaration def where_clause parent_constraints = parent&.constraints || [] (constraints - parent_constraints).to_where_clause end def inherits_clause return '' unless superclass_name " : #{superclass_name}" end # approximately... def async? symbol.declaration =~ /\basync\b[^)]*$/ end def full_declaration symbol.attributes .append(symbol.declaration + inherits_clause + where_clause) .join("\n") end def to_sourcekit(module_name) declaration = full_declaration xml_declaration = "<swift>#{CGI.escapeHTML(declaration)}</swift>" hash = { 'key.kind' => symbol.kind, 'key.usr' => symbol.usr, 'key.name' => symbol.name, 'key.modulename' => module_name, 'key.parsed_declaration' => declaration, 'key.annotated_decl' => xml_declaration, 'key.symgraph_async' => async?, } if params = symbol.parameter_names hash['key.doc.parameters'] = params.map { |name| { 'name' => name } } end hash['key.symgraph_spi'] = true if symbol.spi add_children_to_sourcekit(hash, module_name) symbol.add_to_sourcekit(hash) end # Sort order - by symbol include Comparable def <=>(other) symbol <=> other.symbol end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/constraint.rb
lib/jazzy/symbol_graph/constraint.rb
# frozen_string_literal: true module Jazzy module SymbolGraph # Constraint is a tidied-up JSON object, used by both Symbol and # Relationship, and key to reconstructing extensions. class Constraint attr_accessor :kind attr_accessor :lhs attr_accessor :rhs private def initialize(kind, lhs, rhs) self.kind = kind # "==" or ":" self.lhs = lhs self.rhs = rhs end KIND_MAP = { 'conformance' => ':', 'superclass' => ':', 'sameType' => '==', }.freeze private_constant :KIND_MAP public # Init from a JSON hash def self.new_hash(hash) kind = KIND_MAP[hash[:kind]] raise "Unknown constraint kind '#{kind}'" unless kind lhs = hash[:lhs].sub(/^Self\./, '') rhs = hash[:rhs].sub(/^Self\./, '') new(kind, lhs, rhs) end # Init from a Swift declaration fragment eg. 'A : B' def self.new_declaration(decl) decl =~ /^(.*?)\s*([:<=]+)\s*(.*)$/ new(Regexp.last_match[2], Regexp.last_match[1], Regexp.last_match[3]) end def to_swift "#{lhs} #{kind} #{rhs}" end # The first component of types in the constraint def type_names Set.new([lhs, rhs].map { |n| n.sub(/\..*$/, '') }) end def self.new_list(hash_list) hash_list.map { |h| Constraint.new_hash(h) }.sort.uniq end # Swift protocols and reqs have an implementation/hidden conformance # to their own protocol: we don't want to think about this in docs. def self.new_list_for_symbol(hash_list, path_components) hash_list.map do |hash| if hash[:lhs] == 'Self' && hash[:kind] == 'conformance' && path_components.include?(hash[:rhs]) next nil end Constraint.new_hash(hash) end.compact end # Workaround Swift 5.3 bug with missing constraint rels, eg. # extension P { # func f<C>(a: C) where C: P {} # } def self.new_list_from_declaration(decl) return [] if decl.include?('(') decl.split(/\s*,\s*/).map { |cons| Constraint.new_declaration(cons) } end # Sort order - by Swift text include Comparable def <=>(other) to_swift <=> other.to_swift end alias eql? == def hash to_swift.hash end end end end class Array def to_where_clause empty? ? '' : " where #{map(&:to_swift).join(', ')}" end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false
realm/jazzy
https://github.com/realm/jazzy/blob/8852cdba0fd95acab32bb121fc495abe2fbe5fc8/lib/jazzy/symbol_graph/ext_node.rb
lib/jazzy/symbol_graph/ext_node.rb
# frozen_string_literal: true require 'set' module Jazzy module SymbolGraph # For extensions we need to track constraints of the extended type # and the constraints introduced by the extension. class ExtConstraints attr_accessor :type # array attr_accessor :ext # array # all constraints inherited by members of the extension def merged (type + ext).sort end def initialize(type_constraints, ext_constraints) self.type = type_constraints || [] self.ext = ext_constraints || [] end end # An ExtNode is a node of the reconstructed syntax tree representing # an extension that we fabricate to resolve certain relationships. class ExtNode < BaseNode attr_accessor :usr attr_accessor :real_usr attr_accessor :name attr_accessor :all_constraints # ExtConstraints attr_accessor :conformances # set, can be empty # Deduce an extension from a member of an unknown type or # of known type with additional constraints def self.new_for_member(type_usr, member, constraints) new(type_usr, member.parent_qualified_name, constraints).tap { |o| o.add_child(member) } end # Deduce an extension from a protocol conformance for some type def self.new_for_conformance(type_usr, type_name, protocol, constraints) new(type_usr, type_name, constraints).tap do |o| o.add_conformance(protocol) end end private def initialize(usr, name, constraints) self.usr = usr self.name = name self.all_constraints = constraints self.conformances = Set.new super() end public def constraints all_constraints.merged end def add_conformance(protocol) conformances.add(protocol) end def full_declaration decl = "extension #{name}" unless conformances.empty? decl += " : #{conformances.sort.join(', ')}" end decl + all_constraints.ext.to_where_clause end def to_sourcekit(module_name, ext_module_name) declaration = full_declaration xml_declaration = "<swift>#{CGI.escapeHTML(declaration)}</swift>" hash = { 'key.kind' => 'source.lang.swift.decl.extension', 'key.usr' => real_usr || usr, 'key.name' => name, 'key.modulename' => ext_module_name, 'key.parsed_declaration' => declaration, 'key.annotated_decl' => xml_declaration, } unless conformances.empty? hash['key.inheritedtypes'] = conformances.sort.map do |conformance| { 'key.name' => conformance } end end add_children_to_sourcekit(hash, module_name) hash end # Sort order - by type name then constraint then conformances # Conformance check needed for stable order with Swift 5.9 # extension symbols that can't merge as well as previously. include Comparable def sort_key name + constraints.map(&:to_swift).join + conformances.sort.join end def <=>(other) sort_key <=> other.sort_key end end # An ExtSymNode is an extension generated from a Swift 5.9 extension # symbol, for extensions of types from other modules only. class ExtSymNode < ExtNode attr_accessor :symbol def initialize(symbol) self.symbol = symbol super(symbol.usr, symbol.full_name, # sadly can't tell what constraints are inherited vs added ExtConstraints.new([], symbol.constraints)) end def to_sourcekit(module_name, ext_module_name) hash = super symbol.add_to_sourcekit(hash) end end end end
ruby
MIT
8852cdba0fd95acab32bb121fc495abe2fbe5fc8
2026-01-04T15:39:34.502623Z
false