Skip to content

Commit

Permalink
enhance: render line-wrapped code files instead
Browse files Browse the repository at this point in the history
Run fold on provided files and compare the output with diff. If the file
doesn't contain any lines that are over the configured threshold, it
will be identical to the original. In this case we replace the temp file
with a symlink for easy identification in the template.
  • Loading branch information
ublefo committed Apr 19, 2024
1 parent 634b129 commit 8215793
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
16 changes: 14 additions & 2 deletions app/helpers/file_helper.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require 'English'
require 'zip'
require 'tmpdir'
require 'open3'
Expand Down Expand Up @@ -535,9 +536,20 @@ def line_wrap(path, width: 200)
basename = File.basename(path)
output = File.join(dir, "WRAPPED-#{basename}")
begin
fold_cmd = "fold --width #{width} #{path.shellescape} > #{output}"
logger.debug "Running fold on #{path} to limit line width to #{width}"
system_try_within 5, "Failed running fold on #{path} to limit line width to #{width}", fold_cmd
system("fold --width #{width} #{path.shellescape} > #{output}", exception: true)
# compare input and output files, replace the output with a symlink if they are identical
system "diff #{path.shellescape} #{output}"
case $CHILD_STATUS.exitstatus
when 0
logger.debug "File #{path} does not contain lines longer than #{width}"
File.unlink(output)
File.symlink(path, output)
when 1
logger.debug "File #{path} contains lines longer than #{width}, line wrapping will be applied"
else
raise "Error comparing original and line-wrapped files!"
end
rescue => e
logger.error "Failed to run fold on #{path} to limit line width to #{width}. Rescued with error:\n\t#{e.message}"
end
Expand Down
9 changes: 8 additions & 1 deletion app/views/task/task_pdf.pdf.erb
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,15 @@ No Tutor % Supervisor's Name
<%
if file[:type] == 'code'
if (File.extname(file[:path])[1..-1]) != 'ipynb'
# for code files (except Jupyter Notebook), always use files with a WRAPPED- prefix in the filename
# Jupyter Notebooks are not processed with line wraps
dir = File.dirname(file[:path])
name = File.basename(file[:path])
pygments_lang = Task.pygments_lang(File.extname(file[:path])[1..-1])
wrapped_file = File.join(dir, "WRAPPED-" + name)
# [TODO] add notice about line-wrapped files, files that aren't line-wrapped will be a symlink
%>
\inputminted[breaklines,linenos,breakanywhere,tabsize=4]{<%= Task.pygments_lang(File.extname(file[:path])[1..-1]) %>}{<%= file[:path] %>}
\inputminted[breaklines,linenos,breakanywhere,tabsize=4]{<%= pygments_lang %>}{<%= wrapped_file %>}
<% else %>
\jupynotex{<%= file[:path] %>}
<%
Expand Down

0 comments on commit 8215793

Please sign in to comment.