Class: Asciidoctor::Foodogsquared::Extensions::SWHIncludeProcessor

Inherits:
Extensions::IncludeProcessor
  • Object
show all
Defined in:
lib/asciidoctor/foodogsquared/extensions/swhid-include-processor.rb

Instance Method Summary collapse

Instance Method Details

#handles?(target) ⇒ Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/asciidoctor/foodogsquared/extensions/swhid-include-processor.rb', line 9

def handles?(target)
  target.start_with? 'swh:'
end

#process(doc, reader, target, attributes) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/asciidoctor/foodogsquared/extensions/swhid-include-processor.rb', line 13

def process(doc, reader, target, attributes)
  swhid = target
  swhid_core_identifier = swhid.split(';').at(0)
  swhid_object_type = (swhid_core_identifier.split ':').at 2

  unless (doc.safe <= Asciidoctor::SafeMode::SERVER) && (doc.attr? 'allow-uri-read')
    raise %('swh:' include cannot be used in safe mode level > SERVER and without attribute 'allow-uri-read')
  end

  # We're already going to throw out anything that is not content object type
  # just to make the later pipelines easier to construct.
  if swhid_object_type != 'cnt'
    warn %(SWHID '#{swhid_core_identifier}' is not of 'cnt' type; ignoring)
    return reader
  end

  version = '1'

  content = begin
    uri = URI.parse %(https://archive.softwareheritage.org/api/#{version}/resolve/#{target}/)

    headers = {
      'Accept' => 'application/json'
    }

    headers['Authorization'] = "Bearer #{ENV['SWH_API_BEARER_TOKEN']}" if ENV['SWH_API_BEARER_TOKEN']

     = OpenURI.open_uri(uri, headers) { |f| JSON.parse(f.read) }
    object_hash = ['object_id']

    uri = URI.parse %(https://archive.softwareheritage.org/api/#{version}/content/sha1_git:#{object_hash}/raw/)
    OpenURI.open_uri(uri, headers, &:read)
  rescue OpenURI::HTTPError => e
    warning = %(error while getting '#{swhid_core_identifier}': #{e})
    warn warning
    warning
  end

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