Skip to content

Commit

Permalink
Add support for the lines attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
jakzal committed May 31, 2023
1 parent e938400 commit d64d85e
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Then, inside your AsciiDoc file, use an `include` statement like normal, pointin

* `repository` - path to the Git repository (default: `.`)
* `revision` - repository revision to use (default: `HEAD`)
* `lines` - specify the lines to include (i.e. `lines=2..5;10;12`)

// tag::examples[]

Expand Down Expand Up @@ -74,4 +75,10 @@ Paths within the repository work as usual:
\include::git@path/within/repo/file.rb[]
----

=== Specifying lines to include

----
\include::git@README.adoc[lines=2..5;10;12]
----

// end::examples[]
24 changes: 24 additions & 0 deletions lib/asciidoctor-git-include.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,37 @@ def process doc, reader, target, attributes
target.slice! "git@"
repository = attributes.fetch('repository', '.')
revision = attributes.fetch('revision', 'HEAD')
lines = attributes.fetch('lines', '')

cmd = %(git -C #{repository} show #{revision}:#{target})
content = %x(#{cmd})

content = process_line_selection(content, lines) unless lines == ""

reader.push_include content, target, target, 1, attributes
reader
end

# inspired by https://github.com/tkfu/asciidoctor-github-include/blob/410e0079b2300596ca2b16c94c23c63459e6d0f8/lib/asciidoctor-github-include.rb#LL79C7-L79C29
def process_line_selection content, lines
snipped_content = []
selected_lines = []
text = content.split(/\n/)

lines.split(/[,;]/).each do |linedef|
if linedef.include?('..')
from, to = linedef.split('..', 2).map {|it| it.to_i }
to = text.length if to == -1
selected_lines.concat ::Range.new(from, to).to_a
else
selected_lines << linedef.to_i
end
end
selected_lines.sort.uniq.each do |i|
snipped_content << text[i-1]
end
snipped_content
end
end

Asciidoctor::Extensions.register do
Expand Down
15 changes: 15 additions & 0 deletions test/extension_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ class ExtensionTest < Minitest::Test

assert_match(/Other repo\./, output)
end

test 'it includes selected lines from a file in the git repository' do
input = <<-EOS
include::git@test/fixtures/multiline.adoc[lines=2..3;5]
EOS

output = render_embedded_string input

refute_match(/Line 1\./, output)
assert_match(/Line 2\./, output)
assert_match(/Line 3\./, output)
refute_match(/Line 4\./, output)
assert_match(/Line 5\./, output)
refute_match(/Line 6\./, output)
end
end

def given_file_committed_to_fresh_repo(file_name)
Expand Down

0 comments on commit d64d85e

Please sign in to comment.