Class: Jekyll::Tags::IncludeAbsoluteTag

Inherits:
Liquid::Tag
  • Object
show all
Defined in:
flexible_include.rb

Constant Summary collapse

VALID_SYNTAX =
%r!
  ([\w-]+)\s*=\s*
  (?:"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|([\w\.-]+))
!x
VARIABLE_SYNTAX =
%r!
  (?<variable>[^{]*(\{\{\s*[\w\-\.]+\s*(\|.*)?\}\}[^\s{}]*)+)
  (?<params>.*)
!mx
FULL_VALID_SYNTAX =
%r!\A\s*(?:#{VALID_SYNTAX}(?=\s|\z)\s*)*\z!
VALID_FILENAME_CHARS =
%r!^[\w/\.-]+$!

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, markup, tokens) ⇒ IncludeAbsoluteTag

Returns a new instance of IncludeAbsoluteTag.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'flexible_include.rb', line 34

def initialize(tag_name, markup, tokens)
  super
  matched = markup.strip.match(VARIABLE_SYNTAX)
  if matched
    @file = matched["variable"].strip
    @params = matched["params"].strip
  else
    # Split by spaces but only if the text following contains an even number of '
    # Based on https://stackoverflow.com/a/11566264
    @file, @params = markup.strip.split(%r!\s(?=(?:[^']|'[^']*')*$)!, 2)
  end
  validate_params if @params
  @tag_name = tag_name
end

Instance Method Details

#expand_env(str) ⇒ Object



119
120
121
122
# File 'flexible_include.rb', line 119

def expand_env(str)
  # Expands environment variable references in str
  str.gsub(/\$([a-zA-Z_][a-zA-Z0-9_]*)|\${\g<1>}|%\g<1>%/) { ENV[$1] }
end

#file_read_opts(context) ⇒ Object

Grab file read opts in the context



104
105
106
# File 'flexible_include.rb', line 104

def file_read_opts(context)
  context.registers[:site].file_read_opts
end

#outside_site_source?(path, dir, safe) ⇒ Boolean

Returns:

  • (Boolean)


183
184
185
# File 'flexible_include.rb', line 183

def outside_site_source?(path, dir, safe)
  safe && !realpath_prefixed_with?(path, dir)
end

#parse_params(context) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'flexible_include.rb', line 53

def parse_params(context)
  params = {}
  markup = @params

  while (match = VALID_SYNTAX.match(markup))
    markup = markup[match.end(0)..-1]

    value = if match[2]
              match[2].gsub(%r!\\"!, '"')
            elsif match[3]
              match[3].gsub(%r!\\'!, "'")
            elsif match[4]
              context[match[4]]
            end

    params[match[1]] = value
  end
  params
end

#read_file(file, context) ⇒ Object

This method allows to modify the file content by inheriting from the class.



194
195
196
# File 'flexible_include.rb', line 194

def read_file(file, context)
  File.read(file, **file_read_opts(context))
end

#realpath_prefixed_with?(path, dir) ⇒ Boolean

Returns:

  • (Boolean)


187
188
189
190
191
# File 'flexible_include.rb', line 187

def realpath_prefixed_with?(path, dir)
  File.exist?(path) && File.realpath(path).start_with?(dir)
rescue StandardError
  false
end

#render(context) ⇒ Object



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'flexible_include.rb', line 124

def render(context)
  site = context.registers[:site]

  file = render_variable(context) || @file
  file = file.gsub(/\A'|'\Z/, '')  # Strip leading and trailing quotes
  file = expand_env(file)    # Expand environment variable references
  #validate_file_name(file)  # TODO uncomment and fix validate_file_name
  path = file
  if /^\//.match(file)  # Is the file absolute?
    #puts "********** render path=#{path}, file=#{file} *************"
  elsif /~/.match(file)  # Is the file relative to user's home directory?
    #puts "********** render original file=#{file}, path=#{path} *************"
    file.slice! "~/"
    path = File.join(ENV['HOME'], file)    #puts "********** render path=#{path}, file=#{file} *************"

  elsif /\!/.match(file)  # Is the file on the PATH?
    #puts "********** render original file=#{file}, path=#{path} *************"
    file.slice! "!"
    path = File.which(file)    #puts "********** render path=#{path}, file=#{file} *************"

  else  # The file is relative
    source = File.expand_path(context.registers[:site].config['source']).freeze # website root directory
    path = File.join(source, file)  # Fully qualified path of include file
    #puts "********** render file=#{file}, path=#{path}, source=#{source} *************"
  end
  return unless path

  context.stack do
    do_not_escape = false
    if @params
      context["include"] = parse_params(context)      # puts "context['include']['do_not_escape'] = #{context['include']['do_not_escape']}"

      do_not_escape = context['include'].fetch('do_not_escape', 'false')      # puts "do_not_escape=#{do_not_escape}"
      # puts "do_not_escape=='false' = #{do_not_escape=='false'}"

    end

    begin
      contents = read_file(path, context)
      escaped_contents = do_not_escape=='false' ? contents.gsub("{", "&#123;").gsub("}", "&#125;").gsub("<", "&lt;") : contents
      partial = Liquid::Template.parse(escaped_contents)
    rescue StandardError => e
      abort "flexible_include.rb: #{e.message}"
    end

    begin
      partial.render!(context)
    rescue Liquid::Error => e
      e.template_name = path
      e.markup_context = "included " if e.markup_context.nil?
      raise e
    end
  end
end

#render_variable(context) ⇒ Object

Render the variable if required



109
110
111
112
113
114
115
116
117
# File 'flexible_include.rb', line 109

def render_variable(context)
  if @file =~ VARIABLE_SYNTAX
    partial = context.registers[:site]
      .liquid_renderer
      .file("(variable)")
      .parse(@file)
    partial.render!(context)
  end
end

#syntax_exampleObject



49
50
51
# File 'flexible_include.rb', line 49

def syntax_example
  "{% #{@tag_name} 'file.ext' do_not_escape='true' %}"
end

#valid_include_file?(path, dir, safe) ⇒ Boolean

Returns:

  • (Boolean)


179
180
181
# File 'flexible_include.rb', line 179

def valid_include_file?(path, dir, safe)
  !outside_site_source?(path, dir, safe) && File.file?(path)
end

#validate_file_name(file) ⇒ Object

TODO allow filenames relative to home directory



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'flexible_include.rb', line 73

def validate_file_name(file)  # TODO allow filenames relative to home directory
  if file !~ VALID_FILENAME_CHARS
    raise ArgumentError, <<-MSG
Invalid syntax for the flexible_ include tag. The included file contains invalid characters or sequences:

  #{file}

Valid syntax:

  #{syntax_example}

MSG
  end
end

#validate_paramsObject



88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'flexible_include.rb', line 88

def validate_params
  unless @params =~ FULL_VALID_SYNTAX
    raise ArgumentError, <<-MSG
Invalid syntax for the flexible_include tag:

  #{@params}

Valid syntax:

  #{syntax_example}

MSG
  end
end