diff --git a/README.adoc b/README.adoc index 63026e9..74b9203 100644 --- a/README.adoc +++ b/README.adoc @@ -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[] @@ -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[] diff --git a/lib/asciidoctor-git-include.rb b/lib/asciidoctor-git-include.rb index b603a91..0e855e8 100644 --- a/lib/asciidoctor-git-include.rb +++ b/lib/asciidoctor-git-include.rb @@ -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 diff --git a/test/extension_test.rb b/test/extension_test.rb index a779871..7de0789 100644 --- a/test/extension_test.rb +++ b/test/extension_test.rb @@ -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)