Commit 47eabfe4 authored by Douwe Maan's avatar Douwe Maan

Refactor rich blob viewers and add Source|Rendered switch

parent 0748960b
...@@ -31,7 +31,7 @@ export default () => { ...@@ -31,7 +31,7 @@ export default () => {
}, },
}, },
template: ` template: `
<div class="container-fluid md prepend-top-default append-bottom-default"> <div class="js-pdf-viewer container-fluid md prepend-top-default append-bottom-default">
<div <div
class="text-center loading" class="text-center loading"
v-if="loading && !error"> v-if="loading && !error">
......
/* eslint-disable no-new */
/* global Flash */
export default class BlobViewer {
constructor() {
this.switcher = document.querySelector('.js-blob-viewer-switcher');
this.switcherBtns = document.querySelectorAll('.js-blob-viewer-switch-btn');
this.copySourceBtn = document.querySelector('.js-copy-blob-source-btn');
this.simpleViewer = document.querySelector('.blob-viewer[data-type="simple"]');
this.richViewer = document.querySelector('.blob-viewer[data-type="rich"]');
this.$blobContentHolder = $('#blob-content-holder');
let initialViewerName = document.querySelector('.blob-viewer:not(.hidden)').getAttribute('data-type');
this.initBindings();
if (this.switcher && location.hash.indexOf('#L') === 0) {
initialViewerName = 'simple';
}
this.switchToViewer(initialViewerName);
}
initBindings() {
if (this.switcherBtns.length) {
Array.from(this.switcherBtns)
.forEach((el) => {
el.addEventListener('click', this.switchViewHandler.bind(this));
});
}
if (this.copySourceBtn) {
this.copySourceBtn.addEventListener('click', () => {
if (this.copySourceBtn.classList.contains('disabled')) return;
this.switchToViewer('simple');
});
}
}
switchViewHandler(e) {
const target = e.currentTarget;
e.preventDefault();
this.switchToViewer(target.getAttribute('data-viewer'));
}
toggleCopyButtonState() {
if (!this.copySourceBtn) return;
if (this.simpleViewer.getAttribute('data-loaded')) {
this.copySourceBtn.setAttribute('title', 'Copy source to clipboard');
this.copySourceBtn.classList.remove('disabled');
} else if (this.activeViewer === this.simpleViewer) {
this.copySourceBtn.setAttribute('title', 'Wait for the source to load to copy it to the clipboard');
this.copySourceBtn.classList.add('disabled');
} else {
this.copySourceBtn.setAttribute('title', 'Switch to the source to copy it to the clipboard');
this.copySourceBtn.classList.add('disabled');
}
$(this.copySourceBtn).tooltip('fixTitle');
}
loadViewer(viewerParam) {
const viewer = viewerParam;
const url = viewer.getAttribute('data-url');
if (!url || viewer.getAttribute('data-loaded') || viewer.getAttribute('data-loading')) {
return;
}
viewer.setAttribute('data-loading', 'true');
$.ajax({
url,
dataType: 'JSON',
})
.done((data) => {
viewer.innerHTML = data.html;
$(viewer).syntaxHighlight();
viewer.setAttribute('data-loaded', 'true');
this.$blobContentHolder.trigger('highlight:line');
this.toggleCopyButtonState();
});
}
switchToViewer(name) {
const newViewer = document.querySelector(`.blob-viewer[data-type='${name}']`);
if (this.activeViewer === newViewer) return;
const oldButton = document.querySelector('.js-blob-viewer-switch-btn.active');
const newButton = document.querySelector(`.js-blob-viewer-switch-btn[data-viewer='${name}']`);
const oldViewer = document.querySelector(`.blob-viewer:not([data-type='${name}'])`);
if (oldButton) {
oldButton.classList.remove('active');
}
if (newButton) {
newButton.classList.add('active');
newButton.blur();
}
if (oldViewer) {
oldViewer.classList.add('hidden');
}
newViewer.classList.remove('hidden');
this.activeViewer = newViewer;
this.toggleCopyButtonState();
this.loadViewer(newViewer);
}
}
...@@ -51,6 +51,7 @@ import BlobForkSuggestion from './blob/blob_fork_suggestion'; ...@@ -51,6 +51,7 @@ import BlobForkSuggestion from './blob/blob_fork_suggestion';
import UserCallout from './user_callout'; import UserCallout from './user_callout';
import { ProtectedTagCreate, ProtectedTagEditList } from './protected_tags'; import { ProtectedTagCreate, ProtectedTagEditList } from './protected_tags';
import ShortcutsWiki from './shortcuts_wiki'; import ShortcutsWiki from './shortcuts_wiki';
import BlobViewer from './blob/viewer/index';
import GeoNodes from './geo_nodes'; import GeoNodes from './geo_nodes';
import ServiceDeskRoot from './projects/settings_service_desk/service_desk_root'; import ServiceDeskRoot from './projects/settings_service_desk/service_desk_root';
...@@ -313,6 +314,7 @@ const ShortcutsBlob = require('./shortcuts_blob'); ...@@ -313,6 +314,7 @@ const ShortcutsBlob = require('./shortcuts_blob');
gl.TargetBranchDropDown.bootstrap(); gl.TargetBranchDropDown.bootstrap();
break; break;
case 'projects:blob:show': case 'projects:blob:show':
new BlobViewer();
gl.TargetBranchDropDown.bootstrap(); gl.TargetBranchDropDown.bootstrap();
initBlob(); initBlob();
break; break;
......
...@@ -41,7 +41,6 @@ require('vendor/jquery.scrollTo'); ...@@ -41,7 +41,6 @@ require('vendor/jquery.scrollTo');
LineHighlighter.prototype._hash = ''; LineHighlighter.prototype._hash = '';
function LineHighlighter(hash) { function LineHighlighter(hash) {
var range;
if (hash == null) { if (hash == null) {
// Initialize a LineHighlighter object // Initialize a LineHighlighter object
// //
...@@ -51,10 +50,21 @@ require('vendor/jquery.scrollTo'); ...@@ -51,10 +50,21 @@ require('vendor/jquery.scrollTo');
this.setHash = bind(this.setHash, this); this.setHash = bind(this.setHash, this);
this.highlightLine = bind(this.highlightLine, this); this.highlightLine = bind(this.highlightLine, this);
this.clickHandler = bind(this.clickHandler, this); this.clickHandler = bind(this.clickHandler, this);
this.highlightHash = this.highlightHash.bind(this);
this._hash = hash; this._hash = hash;
this.bindEvents(); this.bindEvents();
if (hash !== '') { this.highlightHash();
range = this.hashToRange(hash); }
LineHighlighter.prototype.bindEvents = function() {
$('#blob-content-holder').on('click', 'a[data-line-number]', this.clickHandler);
$('#blob-content-holder').on('highlight:line', this.highlightHash);
};
LineHighlighter.prototype.highlightHash = function() {
var range;
if (this._hash !== '') {
range = this.hashToRange(this._hash);
if (range[0]) { if (range[0]) {
this.highlightRange(range); this.highlightRange(range);
$.scrollTo("#L" + range[0], { $.scrollTo("#L" + range[0], {
...@@ -64,10 +74,6 @@ require('vendor/jquery.scrollTo'); ...@@ -64,10 +74,6 @@ require('vendor/jquery.scrollTo');
}); });
} }
} }
}
LineHighlighter.prototype.bindEvents = function() {
$('#blob-content-holder').on('click', 'a[data-line-number]', this.clickHandler);
}; };
LineHighlighter.prototype.clickHandler = function(event) { LineHighlighter.prototype.clickHandler = function(event) {
......
module RendersBlob
extend ActiveSupport::Concern
def render_blob_json(blob)
viewer =
if params[:viewer] == 'rich'
blob.rich_viewer
else
blob.simple_viewer
end
return render_404 unless viewer
render json: {
html: view_to_html_string("projects/blob/_viewer", viewer: viewer, load_asynchronously: false)
}
end
end
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
class Projects::BlobController < Projects::ApplicationController class Projects::BlobController < Projects::ApplicationController
include ExtractsPath include ExtractsPath
include CreatesCommit include CreatesCommit
include RendersBlob
include ActionView::Helpers::SanitizeHelper include ActionView::Helpers::SanitizeHelper
# Raised when given an invalid file path # Raised when given an invalid file path
...@@ -34,8 +35,20 @@ class Projects::BlobController < Projects::ApplicationController ...@@ -34,8 +35,20 @@ class Projects::BlobController < Projects::ApplicationController
end end
def show def show
@blob.override_max_size! if params[:override_max_size] == 'true'
respond_to do |format|
format.html do
environment_params = @repository.branch_exists?(@ref) ? { ref: @ref } : { commit: @commit } environment_params = @repository.branch_exists?(@ref) ? { ref: @ref } : { commit: @commit }
@environment = EnvironmentsFinder.new(@project, current_user, environment_params).execute.last @environment = EnvironmentsFinder.new(@project, current_user, environment_params).execute.last
render 'show'
end
format.json do
render_blob_json(@blob)
end
end
end end
def edit def edit
...@@ -96,7 +109,7 @@ class Projects::BlobController < Projects::ApplicationController ...@@ -96,7 +109,7 @@ class Projects::BlobController < Projects::ApplicationController
private private
def blob def blob
@blob ||= Blob.decorate(@repository.blob_at(@commit.id, @path)) @blob ||= Blob.decorate(@repository.blob_at(@commit.id, @path), @project)
if @blob if @blob
@blob @blob
......
...@@ -15,7 +15,7 @@ class Projects::RawController < Projects::ApplicationController ...@@ -15,7 +15,7 @@ class Projects::RawController < Projects::ApplicationController
return if cached_blob? return if cached_blob?
if @blob.lfs_pointer? && project.lfs_enabled? if @blob.valid_lfs_pointer?
send_lfs_object send_lfs_object
else else
send_git_blob @repository, @blob send_git_blob @repository, @blob
......
...@@ -52,7 +52,7 @@ module BlobHelper ...@@ -52,7 +52,7 @@ module BlobHelper
if !on_top_of_branch?(project, ref) if !on_top_of_branch?(project, ref)
button_tag label, class: "#{common_classes} disabled has-tooltip", title: "You can only #{action} files when you are on a branch", data: { container: 'body' } button_tag label, class: "#{common_classes} disabled has-tooltip", title: "You can only #{action} files when you are on a branch", data: { container: 'body' }
elsif blob.lfs_pointer? elsif blob.valid_lfs_pointer?
button_tag label, class: "#{common_classes} disabled has-tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: { container: 'body' } button_tag label, class: "#{common_classes} disabled has-tooltip", title: "It is not possible to #{action} files that are stored in LFS using the web interface", data: { container: 'body' }
elsif can_modify_blob?(blob, project, ref) elsif can_modify_blob?(blob, project, ref)
button_tag label, class: "#{common_classes}", 'data-target' => "#modal-#{modal_type}-blob", 'data-toggle' => 'modal' button_tag label, class: "#{common_classes}", 'data-target' => "#modal-#{modal_type}-blob", 'data-toggle' => 'modal'
...@@ -95,7 +95,7 @@ module BlobHelper ...@@ -95,7 +95,7 @@ module BlobHelper
end end
def can_modify_blob?(blob, project = @project, ref = @ref) def can_modify_blob?(blob, project = @project, ref = @ref)
!blob.lfs_pointer? && can_edit_tree?(project, ref) !blob.valid_lfs_pointer? && can_edit_tree?(project, ref)
end end
def leave_edit_message def leave_edit_message
...@@ -118,28 +118,15 @@ module BlobHelper ...@@ -118,28 +118,15 @@ module BlobHelper
icon("#{file_type_icon_class('file', mode, name)} fw") icon("#{file_type_icon_class('file', mode, name)} fw")
end end
def blob_text_viewable?(blob) def blob_raw_url
blob && blob.text? && !blob.lfs_pointer? && !blob.only_display_raw? namespace_project_raw_path(@project.namespace, @project, @id)
end
def blob_rendered_as_text?(blob)
blob_text_viewable?(blob) && blob.to_partial_path(@project) == 'text'
end
def blob_size(blob)
if blob.lfs_pointer?
blob.lfs_size
else
blob.size
end
end end
# SVGs can contain malicious JavaScript; only include whitelisted # SVGs can contain malicious JavaScript; only include whitelisted
# elements and attributes. Note that this whitelist is by no means complete # elements and attributes. Note that this whitelist is by no means complete
# and may omit some elements. # and may omit some elements.
def sanitize_svg(blob) def sanitize_svg_data(data)
blob.data = Gitlab::Sanitizers::SVG.clean(blob.data) Gitlab::Sanitizers::SVG.clean(data)
blob
end end
# If we blindly set the 'real' content type when serving a Git blob we # If we blindly set the 'real' content type when serving a Git blob we
...@@ -221,13 +208,42 @@ module BlobHelper ...@@ -221,13 +208,42 @@ module BlobHelper
clipboard_button(text: file_path, gfm: "`#{file_path}`", class: 'btn-clipboard btn-transparent prepend-left-5', title: 'Copy file path to clipboard') clipboard_button(text: file_path, gfm: "`#{file_path}`", class: 'btn-clipboard btn-transparent prepend-left-5', title: 'Copy file path to clipboard')
end end
def copy_blob_content_button(blob) def copy_blob_source_button(blob)
return if markup?(blob.name) clipboard_button(target: ".blob-content[data-blob-id='#{blob.id}']", class: "btn btn-sm js-copy-blob-source-btn", title: "Copy source to clipboard")
clipboard_button(target: ".blob-content[data-blob-id='#{blob.id}']", class: "btn btn-sm", title: "Copy content to clipboard")
end end
def open_raw_file_button(path) def open_raw_file_button(path)
link_to icon('file-code-o'), path, class: 'btn btn-sm has-tooltip', target: '_blank', rel: 'noopener noreferrer', title: 'Open raw', data: { container: 'body' } link_to icon('file-code-o'), path, class: 'btn btn-sm has-tooltip', target: '_blank', rel: 'noopener noreferrer', title: 'Open raw', data: { container: 'body' }
end end
def blob_render_error_reason(viewer, error)
case error
when :too_large
max_size =
if viewer.absolutely_too_large?
viewer.absolute_max_size
elsif viewer.too_large?
viewer.max_size
end
"it is larger than #{number_to_human_size(max_size)}"
when :server_side_but_stored_in_lfs
"it is stored in LFS"
end
end
def blob_render_error_options(viewer, error)
options = []
if error == :too_large && viewer.can_override_max_size?
options << link_to('load it anyway', url_for(params.merge(viewer: viewer.type, override_max_size: true, format: nil)))
end
if viewer.rich? && viewer.blob.rendered_as_text?
options << link_to('view the source', '#', class: 'js-blob-viewer-switch-btn', data: { viewer: 'simple' })
end
options << link_to('download it', blob_raw_url, target: '_blank', rel: 'noopener noreferrer')
options
end
end end
...@@ -3,8 +3,20 @@ class Blob < SimpleDelegator ...@@ -3,8 +3,20 @@ class Blob < SimpleDelegator
CACHE_TIME = 60 # Cache raw blobs referred to by a (mutable) ref for 1 minute CACHE_TIME = 60 # Cache raw blobs referred to by a (mutable) ref for 1 minute
CACHE_TIME_IMMUTABLE = 3600 # Cache blobs referred to by an immutable reference for 1 hour CACHE_TIME_IMMUTABLE = 3600 # Cache blobs referred to by an immutable reference for 1 hour
# The maximum size of an SVG that can be displayed. MAXIMUM_TEXT_HIGHLIGHT_SIZE = 1.megabyte
MAXIMUM_SVG_SIZE = 2.megabytes
RICH_VIEWERS = [
BlobViewer::Image,
BlobViewer::PDF,
BlobViewer::Sketch,
BlobViewer::BinarySTL,
BlobViewer::TextSTL,
BlobViewer::Notebook,
BlobViewer::SVG,
BlobViewer::Markup,
].freeze
attr_reader :project
# Wrap a Gitlab::Git::Blob object, or return nil when given nil # Wrap a Gitlab::Git::Blob object, or return nil when given nil
# #
...@@ -16,10 +28,16 @@ class Blob < SimpleDelegator ...@@ -16,10 +28,16 @@ class Blob < SimpleDelegator
# #
# blob = Blob.decorate(nil) # blob = Blob.decorate(nil)
# puts "truthy" if blob # No output # puts "truthy" if blob # No output
def self.decorate(blob) def self.decorate(blob, project = nil)
return if blob.nil? return if blob.nil?
new(blob) new(blob, project)
end
def initialize(blob, project = nil)
@project = project
super(blob)
end end
# Returns the data of the blob. # Returns the data of the blob.
...@@ -35,82 +53,107 @@ class Blob < SimpleDelegator ...@@ -35,82 +53,107 @@ class Blob < SimpleDelegator
end end
def no_highlighting? def no_highlighting?
size && size > 1.megabyte size && size > MAXIMUM_TEXT_HIGHLIGHT_SIZE
end end
def only_display_raw? def too_large?
size && truncated? size && truncated?
end end
# Returns the size of the file that this blob represents. If this blob is an
# LFS pointer, this is the size of the file stored in LFS. Otherwise, this is
# the size of the blob itself.
def raw_size
if valid_lfs_pointer?
lfs_size
else
size
end
end
# Returns whether the file that this blob represents is binary. If this blob is
# an LFS pointer, we assume the file stored in LFS is binary, unless a
# text-based rich blob viewer matched on the file's extension. Otherwise, this
# depends on the type of the blob itself.
def raw_binary?
if valid_lfs_pointer?
if rich_viewer
rich_viewer.binary?
else
true
end
else
binary?
end
end
def extension def extension
extname.downcase.delete('.') @extension ||= extname.downcase.delete('.')
end end
def svg? def video?
text? && language && language.name == 'SVG' UploaderHelper::VIDEO_EXT.include?(extension)
end end
def pdf? def readable_text?
extension == 'pdf' text? && !valid_lfs_pointer? && !too_large?
end end
def ipython_notebook? def valid_lfs_pointer?
text? && language&.name == 'Jupyter Notebook' lfs_pointer? && project&.lfs_enabled?
end end
def sketch? def invalid_lfs_pointer?
binary? && extension == 'sketch' lfs_pointer? && !project&.lfs_enabled?
end end
def stl? def simple_viewer
extension == 'stl' @simple_viewer ||= simple_viewer_class.new(self)
end end
def markup? def rich_viewer
text? && Gitlab::MarkupHelper.markup?(name) return @rich_viewer if defined?(@rich_viewer)
@rich_viewer = rich_viewer_class&.new(self)
end end
def size_within_svg_limits? def rendered_as_text?(ignore_errors: true)
size <= MAXIMUM_SVG_SIZE simple_viewer.text? && (ignore_errors || simple_viewer.render_error.nil?)
end end
def video? def show_viewer_switcher?
UploaderHelper::VIDEO_EXT.include?(extname.downcase.delete('.')) rendered_as_text? && rich_viewer
end end
def to_partial_path(project) def override_max_size!
if lfs_pointer? simple_viewer&.override_max_size = true
if project.lfs_enabled? rich_viewer&.override_max_size = true
'download'
else
'text'
end
elsif image?
'image'
elsif svg?
'svg'
elsif pdf?
'pdf'
elsif ipython_notebook?
'notebook'
elsif sketch?
'sketch'
elsif stl?
'stl'
elsif markup?
if only_display_raw?
'too_large'
else
'markup'
end end
elsif text?
if only_display_raw? private
'too_large'
else def simple_viewer_class
'text' if empty?
BlobViewer::Empty
elsif raw_binary?
BlobViewer::Download
else # text
BlobViewer::Text
end end
else
'download'
end end
def rich_viewer_class
return if invalid_lfs_pointer? || empty?
classes =
if valid_lfs_pointer?
RICH_VIEWERS
elsif binary?
RICH_VIEWERS.select(&:binary?)
else # text
RICH_VIEWERS.select(&:text?)
end
classes.find { |viewer_class| viewer_class.can_render?(self) }
end end
end end
module BlobViewer
class Base
class_attribute :partial_name, :type, :extensions, :client_side, :binary, :switcher_icon, :switcher_title, :max_size, :absolute_max_size
delegate :partial_path, :rich?, :simple?, :client_side?, :server_side?, :text?, :binary?, to: :class
attr_reader :blob
attr_accessor :override_max_size
def initialize(blob)
@blob = blob
end
def self.partial_path
"projects/blob/viewers/#{partial_name}"
end
def self.rich?
type == :rich
end
def self.simple?
type == :simple
end
def self.client_side?
client_side
end
def self.server_side?
!client_side?
end
def self.binary?
binary
end
def self.text?
!binary?
end
def self.can_render?(blob)
!extensions || extensions.include?(blob.extension)
end
def too_large?
blob.raw_size > max_size
end
def absolutely_too_large?
blob.raw_size > absolute_max_size
end
def can_override_max_size?
too_large? && !absolutely_too_large?
end
def render_error
if server_side_but_stored_in_lfs?
:server_side_but_stored_in_lfs
elsif override_max_size ? absolutely_too_large? : too_large?
:too_large
end
end
def prepare!
if server_side? && blob.project
blob.load_all_data!(blob.project.repository)
end
end
private
def server_side_but_stored_in_lfs?
server_side? && blob.valid_lfs_pointer?
end
end
end
module BlobViewer
class BinarySTL < Base
include Rich
include ClientSide
self.partial_name = 'stl'
self.extensions = %w(stl)
self.binary = true
end
end
module BlobViewer
module ClientSide
extend ActiveSupport::Concern
included do
self.client_side = true
self.max_size = 10.megabytes
self.absolute_max_size = 50.megabytes
end
end
end
module BlobViewer
class Download < Base
include Simple
# We treat the Download viewer as if it renders the content client-side,
# so that it doesn't attempt to load the entire blob contents and is
# rendered synchronously instead of loaded asynchronously.
include ClientSide
self.partial_name = 'download'
self.binary = true
def render_error
nil
end
end
end
module BlobViewer
class Empty < Base
include Simple
include ServerSide
self.partial_name = 'empty'
self.binary = true
end
end
module BlobViewer
class Image < Base
include Rich
include ClientSide
self.partial_name = 'image'
self.extensions = UploaderHelper::IMAGE_EXT
self.binary = true
self.switcher_icon = 'picture-o'
self.switcher_title = 'image'
end
end
module BlobViewer
class Markup < Base
include Rich
include ServerSide
self.partial_name = 'markup'
self.extensions = Gitlab::MarkupHelper::EXTENSIONS
self.binary = false
end
end
module BlobViewer
class Notebook < Base
include Rich
include ClientSide
self.partial_name = 'notebook'
self.extensions = %w(ipynb)
self.binary = false
self.switcher_icon = 'file-text-o'
self.switcher_title = 'notebook'
end
end
module BlobViewer
class PDF < Base
include Rich
include ClientSide
self.partial_name = 'pdf'
self.extensions = %w(pdf)
self.binary = true
self.switcher_icon = 'file-pdf-o'
self.switcher_title = 'PDF'
end
end
module BlobViewer
module Rich
extend ActiveSupport::Concern
included do
self.type = :rich
self.switcher_icon = 'file-text-o'
self.switcher_title = 'rendered file'
end
end
end
module BlobViewer
module ServerSide
extend ActiveSupport::Concern
included do
self.client_side = false
self.max_size = 2.megabytes
self.absolute_max_size = 5.megabytes
end
end
end
module BlobViewer
module Simple
extend ActiveSupport::Concern
included do
self.type = :simple
self.switcher_icon = 'code'
self.switcher_title = 'source'
end
end
end
module BlobViewer
class Sketch < Base
include Rich
include ClientSide
self.partial_name = 'sketch'
self.extensions = %w(sketch)
self.binary = true
self.switcher_icon = 'file-image-o'
self.switcher_title = 'preview'
end
end
module BlobViewer
class SVG < Base
include Rich
include ServerSide
self.partial_name = 'svg'
self.extensions = %w(svg)
self.binary = false
self.switcher_icon = 'picture-o'
self.switcher_title = 'image'
end
end
module BlobViewer
class Text < Base
include Simple
include ServerSide
self.partial_name = 'text'
self.binary = false
self.max_size = 1.megabyte
self.absolute_max_size = 10.megabytes
end
end
module BlobViewer
class TextSTL < Base
include Rich
include ClientSide
self.partial_name = 'stl'
self.extensions = %w(stl)
self.binary = false
end
end
...@@ -316,7 +316,7 @@ class Commit ...@@ -316,7 +316,7 @@ class Commit
def uri_type(path) def uri_type(path)
entry = @raw.tree.path(path) entry = @raw.tree.path(path)
if entry[:type] == :blob if entry[:type] == :blob
blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name])) blob = ::Blob.decorate(Gitlab::Git::Blob.new(name: entry[:name]), @project)
blob.image? || blob.video? ? :raw : :blob blob.image? || blob.video? ? :raw : :blob
else else
entry[:type] entry[:type]
......
...@@ -457,7 +457,7 @@ class Repository ...@@ -457,7 +457,7 @@ class Repository
def blob_at(sha, path) def blob_at(sha, path)
unless Gitlab::Git.blank_ref?(sha) unless Gitlab::Git.blank_ref?(sha)
Blob.decorate(Gitlab::Git::Blob.find(self, sha, path)) Blob.decorate(Gitlab::Git::Blob.find(self, sha, path), project)
end end
rescue Gitlab::Git::Repository::NoRepository rescue Gitlab::Git::Repository::NoRepository
nil nil
......
...@@ -74,7 +74,7 @@ ...@@ -74,7 +74,7 @@
- else - else
%hr %hr
- blob = diff_file.blob - blob = diff_file.blob
- if blob && blob.respond_to?(:text?) && blob_text_viewable?(blob) - if blob && blob.readable_text?
%table.code.white %table.code.white
= render partial: "projects/diffs/line", collection: diff_file.highlighted_diff_lines, as: :line, locals: { diff_file: diff_file, plain: true, email: true } = render partial: "projects/diffs/line", collection: diff_file.highlighted_diff_lines, as: :line, locals: { diff_file: diff_file, plain: true, email: true }
- else - else
......
...@@ -27,9 +27,4 @@ ...@@ -27,9 +27,4 @@
%article.file-holder %article.file-holder
= render "projects/blob/header", blob: blob = render "projects/blob/header", blob: blob
- if blob.empty? = render 'projects/blob/content', blob: blob
.file-content.code
.nothing-here-block
Empty file
- else
= render blob.to_partial_path(@project), blob: blob
- simple_viewer = blob.simple_viewer
- rich_viewer = blob.rich_viewer
- rich_viewer_active = rich_viewer && params[:viewer] != 'simple'
= render 'projects/blob/viewer', viewer: simple_viewer, hidden: rich_viewer_active
- if rich_viewer
= render 'projects/blob/viewer', viewer: rich_viewer, hidden: !rich_viewer_active
...@@ -9,17 +9,19 @@ ...@@ -9,17 +9,19 @@
= copy_file_path_button(blob.path) = copy_file_path_button(blob.path)
%small %small
= number_to_human_size(blob_size(blob)) = number_to_human_size(blob.raw_size)
.file-actions.hidden-xs .file-actions.hidden-xs
= render 'projects/blob/viewer_switcher', blob: blob unless blame
.btn-group{ role: "group" }< .btn-group{ role: "group" }<
= copy_blob_content_button(blob) if !blame && blob_rendered_as_text?(blob) = copy_blob_source_button(blob) if !blame && blob.rendered_as_text?(ignore_errors: false)
= open_raw_file_button(namespace_project_raw_path(@project.namespace, @project, @id)) = open_raw_file_button(namespace_project_raw_path(@project.namespace, @project, @id))
= view_on_environment_button(@commit.sha, @path, @environment) if @environment = view_on_environment_button(@commit.sha, @path, @environment) if @environment
.btn-group{ role: "group" }< .btn-group{ role: "group" }<
-# only show normal/blame view links for text files -# only show normal/blame view links for text files
- if blob_text_viewable?(blob) - if blob.readable_text?
- if blame - if blame
= link_to 'Normal view', namespace_project_blob_path(@project.namespace, @project, @id), = link_to 'Normal view', namespace_project_blob_path(@project.namespace, @project, @id),
class: 'btn btn-sm' class: 'btn btn-sm'
...@@ -36,7 +38,8 @@ ...@@ -36,7 +38,8 @@
.btn-group{ role: "group" }< .btn-group{ role: "group" }<
- if current_user - if current_user
= lock_file_link(html_options: {class: 'btn btn-sm path-lock'}) = lock_file_link(html_options: {class: 'btn btn-sm path-lock'})
= edit_blob_link if blob_text_viewable?(blob)
= edit_blob_link if blob.readable_text?
- if current_user - if current_user
= replace_blob_link = replace_blob_link
= delete_blob_link = delete_blob_link
......
.file-content.image_file
%img{ src: namespace_project_raw_path(@project.namespace, @project, @id), alt: blob.name }
.file-content.code
.nothing-here-block
The #{viewer.switcher_title} could not be displayed because #{blob_render_error_reason(viewer, error)}.
You can
= blob_render_error_options(viewer, error).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ').html_safe
instead.
- if blob.size_within_svg_limits?
-# We need to scrub SVG but we cannot do so in the RawController: it would
-# be wrong/strange if RawController modified the data.
- blob.load_all_data!(@repository)
- blob = sanitize_svg(blob)
.file-content.image_file
%img{ src: "data:#{blob.mime_type};base64,#{Base64.encode64(blob.data)}", alt: blob.name }
- else
= render 'too_large'
- blob.load_all_data!(@repository)
= render 'shared/file_highlight', blob: blob, repository: @repository
.file-content.code
.nothing-here-block
The file could not be displayed as it is too large, you can
#{link_to('view the raw file', namespace_project_raw_path(@project.namespace, @project, @id), target: '_blank', rel: 'noopener noreferrer')}
instead.
- hidden = local_assigns.fetch(:hidden, false)
- render_error = viewer.render_error
- load_asynchronously = local_assigns.fetch(:load_asynchronously, viewer.server_side?) && render_error.nil?
- url = url_for(params.merge(viewer: viewer.type, format: :json)) if load_asynchronously
.blob-viewer{ data: { type: viewer.type, url: url }, class: ('hidden' if hidden) }
- if load_asynchronously
.text-center.prepend-top-default.append-bottom-default
= icon('spinner spin 2x', 'aria-hidden' => 'true', 'aria-label' => 'Loading content')
- elsif render_error
= render 'projects/blob/render_error', viewer: viewer, error: render_error
- else
- viewer.prepare!
= render viewer.partial_path, viewer: viewer
- if blob.show_viewer_switcher?
- simple_viewer = blob.simple_viewer
- rich_viewer = blob.rich_viewer
.btn-group.js-blob-viewer-switcher{ role: "group" }
- simple_label = "Display #{simple_viewer.switcher_title}"
%button.btn.btn-default.btn-sm.js-blob-viewer-switch-btn.has-tooltip{ 'aria-label' => simple_label, title: simple_label, data: { viewer: 'simple', container: 'body' } }>
= icon(simple_viewer.switcher_icon)
- rich_label = "Display #{rich_viewer.switcher_title}"
%button.btn.btn-default.btn-sm.js-blob-viewer-switch-btn.has-tooltip{ 'aria-label' => rich_label, title: rich_label, data: { viewer: 'rich', container: 'body' } }>
= icon(rich_viewer.switcher_icon)
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
- page_title @blob.path, @ref - page_title @blob.path, @ref
= render "projects/commits/head" = render "projects/commits/head"
- content_for :page_specific_javascripts do
= page_specific_javascript_bundle_tag('blob')
%div{ class: container_class } %div{ class: container_class }
= render 'projects/last_push' = render 'projects/last_push'
......
.file-content.blob_file.blob-no-preview .file-content.blob_file.blob-no-preview
.center .center
= link_to namespace_project_raw_path(@project.namespace, @project, @id) do = link_to blob_raw_url do
%h1.light %h1.light
%i.fa.fa-download = icon('download')
%h4 %h4
Download (#{number_to_human_size blob_size(blob)}) Download (#{number_to_human_size(viewer.blob.raw_size)})
.file-content.code
.nothing-here-block
Empty file
.file-content.image_file
%img{ src: blob_raw_url, alt: viewer.blob.name }
- blob = viewer.blob
.file-content.wiki
= render_markup(blob.name, blob.data)
...@@ -2,4 +2,4 @@ ...@@ -2,4 +2,4 @@
= page_specific_javascript_bundle_tag('common_vue') = page_specific_javascript_bundle_tag('common_vue')
= page_specific_javascript_bundle_tag('notebook_viewer') = page_specific_javascript_bundle_tag('notebook_viewer')
.file-content#js-notebook-viewer{ data: { endpoint: namespace_project_raw_path(@project.namespace, @project, @id) } } .file-content#js-notebook-viewer{ data: { endpoint: blob_raw_url } }
...@@ -2,4 +2,4 @@ ...@@ -2,4 +2,4 @@
= page_specific_javascript_bundle_tag('common_vue') = page_specific_javascript_bundle_tag('common_vue')
= page_specific_javascript_bundle_tag('pdf_viewer') = page_specific_javascript_bundle_tag('pdf_viewer')
.file-content#js-pdf-viewer{ data: { endpoint: namespace_project_raw_path(@project.namespace, @project, @id) } } .file-content#js-pdf-viewer{ data: { endpoint: blob_raw_url } }
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
= page_specific_javascript_bundle_tag('common_vue') = page_specific_javascript_bundle_tag('common_vue')
= page_specific_javascript_bundle_tag('sketch_viewer') = page_specific_javascript_bundle_tag('sketch_viewer')
.file-content#js-sketch-viewer{ data: { endpoint: namespace_project_raw_path(@project.namespace, @project, @id) } } .file-content#js-sketch-viewer{ data: { endpoint: blob_raw_url } }
.js-loading-icon.text-center.prepend-top-default.append-bottom-default.js-loading-icon{ 'aria-label' => 'Loading Sketch preview' } .js-loading-icon.text-center.prepend-top-default.append-bottom-default.js-loading-icon{ 'aria-label' => 'Loading Sketch preview' }
= icon('spinner spin 2x', 'aria-hidden' => 'true'); = icon('spinner spin 2x', 'aria-hidden' => 'true');
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
= page_specific_javascript_bundle_tag('stl_viewer') = page_specific_javascript_bundle_tag('stl_viewer')
.file-content.is-stl-loading .file-content.is-stl-loading
.text-center#js-stl-viewer{ data: { endpoint: namespace_project_raw_path(@project.namespace, @project, @id) } } .text-center#js-stl-viewer{ data: { endpoint: blob_raw_url } }
= icon('spinner spin 2x', class: 'prepend-top-default append-bottom-default', 'aria-hidden' => 'true', 'aria-label' => 'Loading') = icon('spinner spin 2x', class: 'prepend-top-default append-bottom-default', 'aria-hidden' => 'true', 'aria-label' => 'Loading')
.text-center.prepend-top-default.append-bottom-default.stl-controls .text-center.prepend-top-default.append-bottom-default.stl-controls
.btn-group .btn-group
......
- blob = viewer.blob
- data = sanitize_svg_data(blob.data)
.file-content.image_file
%img{ src: "data:#{blob.mime_type};base64,#{Base64.encode64(data)}", alt: blob.name }
= render 'shared/file_highlight', blob: viewer.blob, repository: @repository
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
- return unless blob.respond_to?(:text?) - return unless blob.respond_to?(:text?)
- if diff_file.too_large? - if diff_file.too_large?
.nothing-here-block This diff could not be displayed because it is too large. .nothing-here-block This diff could not be displayed because it is too large.
- elsif blob.only_display_raw? - elsif blob.too_large?
.nothing-here-block The file could not be displayed because it is too large. .nothing-here-block The file could not be displayed because it is too large.
- elsif blob_text_viewable?(blob) - elsif blob.readable_text?
- if !project.repository.diffable?(blob) - if !project.repository.diffable?(blob)
.nothing-here-block This diff was suppressed by a .gitattributes entry. .nothing-here-block This diff was suppressed by a .gitattributes entry.
- elsif diff_file.collapsed? - elsif diff_file.collapsed?
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
- diff_commit = commit_for_diff(diff_file) - diff_commit = commit_for_diff(diff_file)
- blob = diff_file.blob(diff_commit) - blob = diff_file.blob(diff_commit)
- next unless blob - next unless blob
- blob.load_all_data!(diffs.project.repository) unless blob.only_display_raw? - blob.load_all_data!(diffs.project.repository) unless blob.too_large?
- file_hash = hexdigest(diff_file.file_path) - file_hash = hexdigest(diff_file.file_path)
= render 'projects/diffs/file', file_hash: file_hash, project: diffs.project, = render 'projects/diffs/file', file_hash: file_hash, project: diffs.project,
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
- unless diff_file.submodule? - unless diff_file.submodule?
.file-actions.hidden-xs .file-actions.hidden-xs
- if blob_text_viewable?(blob) - if blob.readable_text?
= link_to '#', class: 'js-toggle-diff-comments btn active has-tooltip', title: "Toggle comments for this file", disabled: @diff_notes_disabled do = link_to '#', class: 'js-toggle-diff-comments btn active has-tooltip', title: "Toggle comments for this file", disabled: @diff_notes_disabled do
= icon('comment') = icon('comment')
\ \
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
.file-actions.hidden-xs .file-actions.hidden-xs
.btn-group{ role: "group" }< .btn-group{ role: "group" }<
= copy_blob_content_button(@snippet) = copy_blob_source_button(@snippet)
= open_raw_file_button(raw_path) = open_raw_file_button(raw_path)
- if defined?(download_path) && download_path - if defined?(download_path) && download_path
......
---
title: Add Source/Rendered switch to blobs for SVG, Markdown, Asciidoc and other text
files that can be rendered
merge_request:
author:
...@@ -11,6 +11,7 @@ Feature: Project Source Browse Files ...@@ -11,6 +11,7 @@ Feature: Project Source Browse Files
Given I visit project source page for "6d39438" Given I visit project source page for "6d39438"
Then I should see files from repository for "6d39438" Then I should see files from repository for "6d39438"
@javascript
Scenario: I browse file content Scenario: I browse file content
Given I click on ".gitignore" file in repo Given I click on ".gitignore" file in repo
Then I should see its content Then I should see its content
......
...@@ -6,11 +6,13 @@ Feature: Project Source Markdown Render ...@@ -6,11 +6,13 @@ Feature: Project Source Markdown Render
# Tree README # Tree README
@javascript
Scenario: Tree view should have correct links in README Scenario: Tree view should have correct links in README
Given I go directory which contains README file Given I go directory which contains README file
And I click on a relative link in README And I click on a relative link in README
Then I should see the correct markdown Then I should see the correct markdown
@javascript
Scenario: I browse files from markdown branch Scenario: I browse files from markdown branch
Then I should see files from repository in markdown Then I should see files from repository in markdown
And I should see rendered README which contains correct links And I should see rendered README which contains correct links
...@@ -29,36 +31,42 @@ Feature: Project Source Markdown Render ...@@ -29,36 +31,42 @@ Feature: Project Source Markdown Render
And I click on GitLab API doc directory in README And I click on GitLab API doc directory in README
Then I should see correct doc/api directory rendered Then I should see correct doc/api directory rendered
@javascript
Scenario: I view README in markdown branch to see reference links to file Scenario: I view README in markdown branch to see reference links to file
Then I should see files from repository in markdown Then I should see files from repository in markdown
And I should see rendered README which contains correct links And I should see rendered README which contains correct links
And I click on Maintenance in README And I click on Maintenance in README
Then I should see correct maintenance file rendered Then I should see correct maintenance file rendered
@javascript
Scenario: README headers should have header links Scenario: README headers should have header links
Then I should see rendered README which contains correct links Then I should see rendered README which contains correct links
And Header "Application details" should have correct id and link And Header "Application details" should have correct id and link
# Blob # Blob
@javascript
Scenario: I navigate to doc directory to view documentation in markdown Scenario: I navigate to doc directory to view documentation in markdown
And I navigate to the doc/api/README And I navigate to the doc/api/README
And I see correct file rendered And I see correct file rendered
And I click on users in doc/api/README And I click on users in doc/api/README
Then I should see the correct document file Then I should see the correct document file
@javascript
Scenario: I navigate to doc directory to view user doc in markdown Scenario: I navigate to doc directory to view user doc in markdown
And I navigate to the doc/api/README And I navigate to the doc/api/README
And I see correct file rendered And I see correct file rendered
And I click on raketasks in doc/api/README And I click on raketasks in doc/api/README
Then I should see correct directory rendered Then I should see correct directory rendered
@javascript
Scenario: I navigate to doc directory to view user doc in markdown Scenario: I navigate to doc directory to view user doc in markdown
And I navigate to the doc/api/README And I navigate to the doc/api/README
And Header "GitLab API" should have correct id and link And Header "GitLab API" should have correct id and link
# Markdown branch # Markdown branch
@javascript
Scenario: I browse files from markdown branch Scenario: I browse files from markdown branch
When I visit markdown branch When I visit markdown branch
Then I should see files from repository in markdown branch Then I should see files from repository in markdown branch
...@@ -73,6 +81,7 @@ Feature: Project Source Markdown Render ...@@ -73,6 +81,7 @@ Feature: Project Source Markdown Render
And I click on Rake tasks in README And I click on Rake tasks in README
Then I should see correct directory rendered for markdown branch Then I should see correct directory rendered for markdown branch
@javascript
Scenario: I navigate to doc directory to view documentation in markdown branch Scenario: I navigate to doc directory to view documentation in markdown branch
When I visit markdown branch When I visit markdown branch
And I navigate to the doc/api/README And I navigate to the doc/api/README
...@@ -80,6 +89,7 @@ Feature: Project Source Markdown Render ...@@ -80,6 +89,7 @@ Feature: Project Source Markdown Render
And I click on users in doc/api/README And I click on users in doc/api/README
Then I should see the users document file in markdown branch Then I should see the users document file in markdown branch
@javascript
Scenario: I navigate to doc directory to view user doc in markdown branch Scenario: I navigate to doc directory to view user doc in markdown branch
When I visit markdown branch When I visit markdown branch
And I navigate to the doc/api/README And I navigate to the doc/api/README
...@@ -87,6 +97,7 @@ Feature: Project Source Markdown Render ...@@ -87,6 +97,7 @@ Feature: Project Source Markdown Render
And I click on raketasks in doc/api/README And I click on raketasks in doc/api/README
Then I should see correct directory rendered for markdown branch Then I should see correct directory rendered for markdown branch
@javascript
Scenario: Tree markdown links view empty urls should have correct urls Scenario: Tree markdown links view empty urls should have correct urls
When I visit markdown branch When I visit markdown branch
Then The link with text "empty" should have url "tree/markdown" Then The link with text "empty" should have url "tree/markdown"
...@@ -99,6 +110,7 @@ Feature: Project Source Markdown Render ...@@ -99,6 +110,7 @@ Feature: Project Source Markdown Render
# "ID" means "#id" on the tests below, because we are unable to escape the hash sign. # "ID" means "#id" on the tests below, because we are unable to escape the hash sign.
# which Spinach interprets as the start of a comment. # which Spinach interprets as the start of a comment.
@javascript
Scenario: All markdown links with ids should have correct urls Scenario: All markdown links with ids should have correct urls
When I visit markdown branch When I visit markdown branch
Then The link with text "ID" should have url "tree/markdownID" Then The link with text "ID" should have url "tree/markdownID"
......
...@@ -4,6 +4,7 @@ class Spinach::Features::ProjectSourceBrowseFiles < Spinach::FeatureSteps ...@@ -4,6 +4,7 @@ class Spinach::Features::ProjectSourceBrowseFiles < Spinach::FeatureSteps
include SharedProject include SharedProject
include SharedPaths include SharedPaths
include RepoHelpers include RepoHelpers
include WaitForAjax
step "I don't have write access" do step "I don't have write access" do
@project = create(:project, :repository, name: "Other Project", path: "other-project") @project = create(:project, :repository, name: "Other Project", path: "other-project")
...@@ -36,10 +37,12 @@ class Spinach::Features::ProjectSourceBrowseFiles < Spinach::FeatureSteps ...@@ -36,10 +37,12 @@ class Spinach::Features::ProjectSourceBrowseFiles < Spinach::FeatureSteps
end end
step 'I should see its content' do step 'I should see its content' do
wait_for_ajax
expect(page).to have_content old_gitignore_content expect(page).to have_content old_gitignore_content
end end
step 'I should see its new content' do step 'I should see its new content' do
wait_for_ajax
expect(page).to have_content new_gitignore_content expect(page).to have_content new_gitignore_content
end end
......
...@@ -5,6 +5,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -5,6 +5,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
include SharedAuthentication include SharedAuthentication
include SharedPaths include SharedPaths
include SharedMarkdown include SharedMarkdown
include WaitForAjax
step 'I own project "Delta"' do step 'I own project "Delta"' do
@project = ::Project.find_by(name: "Delta") @project = ::Project.find_by(name: "Delta")
...@@ -34,6 +35,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -34,6 +35,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I should see correct document rendered' do step 'I should see correct document rendered' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md")
wait_for_ajax
expect(page).to have_content "All API requests require authentication" expect(page).to have_content "All API requests require authentication"
end end
...@@ -63,6 +65,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -63,6 +65,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I should see correct maintenance file rendered' do step 'I should see correct maintenance file rendered' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/raketasks/maintenance.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/raketasks/maintenance.md")
wait_for_ajax
expect(page).to have_content "bundle exec rake gitlab:env:info RAILS_ENV=production" expect(page).to have_content "bundle exec rake gitlab:env:info RAILS_ENV=production"
end end
...@@ -94,6 +97,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -94,6 +97,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I see correct file rendered' do step 'I see correct file rendered' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md")
wait_for_ajax
expect(page).to have_content "Contents" expect(page).to have_content "Contents"
expect(page).to have_link "Users" expect(page).to have_link "Users"
expect(page).to have_link "Rake tasks" expect(page).to have_link "Rake tasks"
...@@ -138,6 +142,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -138,6 +142,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I see correct file rendered in markdown branch' do step 'I see correct file rendered in markdown branch' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md")
wait_for_ajax
expect(page).to have_content "Contents" expect(page).to have_content "Contents"
expect(page).to have_link "Users" expect(page).to have_link "Users"
expect(page).to have_link "Rake tasks" expect(page).to have_link "Rake tasks"
...@@ -145,6 +150,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -145,6 +150,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I should see correct document rendered for markdown branch' do step 'I should see correct document rendered for markdown branch' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/README.md")
wait_for_ajax
expect(page).to have_content "All API requests require authentication" expect(page).to have_content "All API requests require authentication"
end end
...@@ -162,6 +168,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -162,6 +168,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
# Expected link contents # Expected link contents
step 'The link with text "empty" should have url "tree/markdown"' do step 'The link with text "empty" should have url "tree/markdown"' do
wait_for_ajax
find('a', text: /^empty$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown") find('a', text: /^empty$/)['href'] == current_host + namespace_project_tree_path(@project.namespace, @project, "markdown")
end end
...@@ -197,6 +204,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -197,6 +204,7 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
end end
step 'The link with text "ID" should have url "blob/markdown/README.mdID"' do step 'The link with text "ID" should have url "blob/markdown/README.mdID"' do
wait_for_ajax
find('a', text: /^#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") + '#id' find('a', text: /^#id$/)['href'] == current_host + namespace_project_blob_path(@project.namespace, @project, "markdown/README.md") + '#id'
end end
...@@ -291,10 +299,12 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps ...@@ -291,10 +299,12 @@ class Spinach::Features::ProjectSourceMarkdownRender < Spinach::FeatureSteps
step 'I should see the correct markdown' do step 'I should see the correct markdown' do
expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/users.md") expect(current_path).to eq namespace_project_blob_path(@project.namespace, @project, "markdown/doc/api/users.md")
wait_for_ajax
expect(page).to have_content "List users" expect(page).to have_content "List users"
end end
step 'Header "Application details" should have correct id and link' do step 'Header "Application details" should have correct id and link' do
wait_for_ajax
header_should_have_correct_id_and_link(2, 'Application details', 'application-details') header_should_have_correct_id_and_link(2, 'Application details', 'application-details')
end end
......
...@@ -3,7 +3,7 @@ module SharedMarkdown ...@@ -3,7 +3,7 @@ module SharedMarkdown
def header_should_have_correct_id_and_link(level, text, id, parent = ".wiki") def header_should_have_correct_id_and_link(level, text, id, parent = ".wiki")
node = find("#{parent} h#{level} a#user-content-#{id}") node = find("#{parent} h#{level} a#user-content-#{id}")
expect(node[:href]).to eq "##{id}" expect(node[:href]).to end_with "##{id}"
# Work around a weird Capybara behavior where calling `parent` on a node # Work around a weird Capybara behavior where calling `parent` on a node
# returns the whole document, not the node's actual parent element # returns the whole document, not the node's actual parent element
......
...@@ -109,10 +109,6 @@ module Gitlab ...@@ -109,10 +109,6 @@ module Gitlab
@binary.nil? ? super : @binary == true @binary.nil? ? super : @binary == true
end end
def empty?
!data || data == ''
end
def data def data
encode! @data encode! @data
end end
......
require 'spec_helper' require 'spec_helper'
feature 'File blob', feature: true do feature 'File blob', :js, feature: true do
include TreeHelper include TreeHelper
include WaitForAjax
let(:project) { create(:project, :public, :test_repo) } let(:project) { create(:project, :public) }
let(:merge_request) { create(:merge_request, source_project: project, source_branch: 'feature', target_branch: 'master') }
let(:branch) { 'master' }
let(:file_path) { project.repository.ls_files(project.repository.root_ref)[1] }
context 'anonymous' do def visit_blob(path, fragment = nil)
context 'from blob file path' do visit namespace_project_blob_path(project.namespace, project, tree_join('master', path), anchor: fragment)
end
context 'Ruby file' do
before do
visit_blob('files/ruby/popen.rb')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# shows highlighted Ruby code
expect(page).to have_content("require 'fileutils'")
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
end
context 'Markdown file' do
context 'visiting directly' do
before do
visit_blob('files/markdown/ruby-style-guide.md')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the simple viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]', visible: false)
expect(page).to have_selector('.blob-viewer[data-type="rich"]')
# shows rendered Markdown
expect(page).to have_link("PEP-8")
# shows a viewer switcher
expect(page).to have_selector('.js-blob-viewer-switcher')
# shows a disabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn.disabled')
end
end
context 'switching to the simple viewer' do
before do
find('.js-blob-viewer-switch-btn[data-viewer=simple]').click
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the rich viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]')
expect(page).to have_selector('.blob-viewer[data-type="rich"]', visible: false)
# shows highlighted Markdown code
expect(page).to have_content("[PEP-8](http://www.python.org/dev/peps/pep-0008/)")
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
context 'switching to the rich viewer again' do
before do
find('.js-blob-viewer-switch-btn[data-viewer=rich]').click
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the simple viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]', visible: false)
expect(page).to have_selector('.blob-viewer[data-type="rich"]')
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
end
end
end
context 'visiting with a line number anchor' do
before do
visit_blob('files/markdown/ruby-style-guide.md', 'L1')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the rich viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]')
expect(page).to have_selector('.blob-viewer[data-type="rich"]', visible: false)
# highlights the line in question
expect(page).to have_selector('#LC1.hll')
# shows highlighted Markdown code
expect(page).to have_content("[PEP-8](http://www.python.org/dev/peps/pep-0008/)")
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
end
end
context 'Markdown file (stored in LFS)' do
before do
project.add_master(project.creator)
Files::CreateService.new(
project,
project.creator,
start_branch: 'master',
branch_name: 'master',
commit_message: "Add Markdown in LFS",
file_path: 'files/lfs/file.md',
file_content: project.repository.blob_at('master', 'files/lfs/lfs_object.iso').data
).execute
end
context 'when LFS is enabled on the project' do
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
project.update_attribute(:lfs_enabled, true)
visit_blob('files/lfs/file.md')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the simple viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]', visible: false)
expect(page).to have_selector('.blob-viewer[data-type="rich"]')
# shows an error message
expect(page).to have_content('The rendered file could not be displayed because it is stored in LFS. You can view the source or download it instead.')
# shows a viewer switcher
expect(page).to have_selector('.js-blob-viewer-switcher')
# does not show a copy button
expect(page).not_to have_selector('.js-copy-blob-source-btn')
end
end
context 'switching to the simple viewer' do
before do
find('.js-blob-viewer-switcher .js-blob-viewer-switch-btn[data-viewer=simple]').click
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# hides the rich viewer
expect(page).to have_selector('.blob-viewer[data-type="simple"]')
expect(page).to have_selector('.blob-viewer[data-type="rich"]', visible: false)
# shows an error message
expect(page).to have_content('The source could not be displayed because it is stored in LFS. You can download it instead.')
# does not show a copy button
expect(page).not_to have_selector('.js-copy-blob-source-btn')
end
end
end
end
context 'when LFS is disabled on the project' do
before do
visit_blob('files/lfs/file.md')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# shows text
expect(page).to have_content('size 1575078')
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
end
end
context 'PDF file' do
before do
project.add_master(project.creator)
Files::CreateService.new(
project,
project.creator,
start_branch: 'master',
branch_name: 'master',
commit_message: "Add PDF",
file_path: 'files/test.pdf',
file_content: File.read(Rails.root.join('spec/javascripts/blob/pdf/test.pdf'))
).execute
visit_blob('files/test.pdf')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# shows rendered PDF
expect(page).to have_selector('.js-pdf-viewer')
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# does not show a copy button
expect(page).not_to have_selector('.js-copy-blob-source-btn')
end
end
end
context 'ISO file (stored in LFS)' do
context 'when LFS is enabled on the project' do
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
project.update_attribute(:lfs_enabled, true)
visit_blob('files/lfs/lfs_object.iso')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# shows a download link
expect(page).to have_link('Download (1.5 MB)')
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# does not show a copy button
expect(page).not_to have_selector('.js-copy-blob-source-btn')
end
end
end
context 'when LFS is disabled on the project' do
before do
visit_blob('files/lfs/lfs_object.iso')
wait_for_ajax
end
it 'displays the blob' do
aggregate_failures do
# shows text
expect(page).to have_content('size 1575078')
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# shows an enabled copy button
expect(page).to have_selector('.js-copy-blob-source-btn:not(.disabled)')
end
end
end
end
context 'ZIP file' do
before do before do
visit namespace_project_blob_path(project.namespace, project, tree_join(branch, file_path)) visit_blob('Gemfile.zip')
wait_for_ajax
end end
it 'updates content' do it 'displays the blob' do
expect(page).to have_link 'Edit' aggregate_failures do
# shows a download link
expect(page).to have_link('Download (2.11 KB)')
# does not show a viewer switcher
expect(page).not_to have_selector('.js-blob-viewer-switcher')
# does not show a copy button
expect(page).not_to have_selector('.js-copy-blob-source-btn')
end end
end end
end end
......
require 'spec_helper' require 'spec_helper'
feature 'user browses project', feature: true do feature 'user browses project', feature: true, js: true do
let(:project) { create(:project) } let(:project) { create(:project) }
let(:user) { create(:user) } let(:user) { create(:user) }
...@@ -24,6 +24,7 @@ feature 'user browses project', feature: true do ...@@ -24,6 +24,7 @@ feature 'user browses project', feature: true do
click_link 'files' click_link 'files'
click_link 'lfs' click_link 'lfs'
click_link 'lfs_object.iso' click_link 'lfs_object.iso'
wait_for_ajax
expect(page).not_to have_content 'Download (1.5 MB)' expect(page).not_to have_content 'Download (1.5 MB)'
expect(page).to have_content 'version https://git-lfs.github.com/spec/v1' expect(page).to have_content 'version https://git-lfs.github.com/spec/v1'
......
...@@ -56,15 +56,14 @@ describe BlobHelper do ...@@ -56,15 +56,14 @@ describe BlobHelper do
end end
end end
describe "#sanitize_svg" do describe "#sanitize_svg_data" do
let(:input_svg_path) { File.join(Rails.root, 'spec', 'fixtures', 'unsanitized.svg') } let(:input_svg_path) { File.join(Rails.root, 'spec', 'fixtures', 'unsanitized.svg') }
let(:data) { open(input_svg_path).read } let(:data) { open(input_svg_path).read }
let(:expected_svg_path) { File.join(Rails.root, 'spec', 'fixtures', 'sanitized.svg') } let(:expected_svg_path) { File.join(Rails.root, 'spec', 'fixtures', 'sanitized.svg') }
let(:expected) { open(expected_svg_path).read } let(:expected) { open(expected_svg_path).read }
it 'retains essential elements' do it 'retains essential elements' do
blob = OpenStruct.new(data: data) expect(sanitize_svg_data(data)).to eq(expected)
expect(sanitize_svg(blob).data).to eq(expected)
end end
end end
...@@ -105,4 +104,113 @@ describe BlobHelper do ...@@ -105,4 +104,113 @@ describe BlobHelper do
expect(Capybara.string(link).find_link('Edit')[:href]).to eq('/gitlab/gitlabhq/edit/master/README.md?mr_id=10') expect(Capybara.string(link).find_link('Edit')[:href]).to eq('/gitlab/gitlabhq/edit/master/README.md?mr_id=10')
end end
end end
context 'viewer related' do
include FakeBlobHelpers
let(:project) { build(:empty_project) }
let(:viewer_class) do
Class.new(BlobViewer::Base) do
self.max_size = 1.megabyte
self.absolute_max_size = 5.megabytes
self.type = :rich
self.client_side = false
end
end
let(:viewer) { viewer_class.new(blob) }
let(:blob) { fake_blob }
before do
assign(:project, project)
assign(:id, File.join('master', blob.path))
controller.params[:controller] = 'projects/blob'
controller.params[:action] = 'show'
controller.params[:namespace_id] = project.namespace.to_param
controller.params[:project_id] = project.to_param
controller.params[:id] = File.join('master', blob.path)
end
describe '#blob_render_error_reason' do
context 'for error :too_large' do
context 'when the blob size is larger than the absolute max size' do
let(:blob) { fake_blob(size: 10.megabytes) }
it 'returns an error message' do
expect(helper.blob_render_error_reason(viewer, :too_large)).to eq('it is larger than 5 MB')
end
end
context 'when the blob size is larger than the max size' do
let(:blob) { fake_blob(size: 2.megabytes) }
it 'returns an error message' do
expect(helper.blob_render_error_reason(viewer, :too_large)).to eq('it is larger than 1 MB')
end
end
end
context 'for error :server_side_but_stored_in_lfs' do
it 'returns an error message' do
expect(helper.blob_render_error_reason(viewer, :server_side_but_stored_in_lfs)).to eq('it is stored in LFS')
end
end
end
describe '#blob_render_error_options' do
context 'for error :too_large' do
context 'when the max size can be overridden' do
let(:blob) { fake_blob(size: 2.megabytes) }
it 'includes a "load it anyway" link' do
expect(helper.blob_render_error_options(viewer, :too_large)).to include(/load it anyway/)
end
end
context 'when the max size cannot be overridden' do
let(:blob) { fake_blob(size: 10.megabytes) }
it 'does not include a "load it anyway" link' do
expect(helper.blob_render_error_options(viewer, :too_large)).not_to include(/load it anyway/)
end
end
end
context 'when the viewer is rich' do
context 'the blob is rendered as text' do
let(:blob) { fake_blob(path: 'file.md') }
it 'includes a "view the source" link' do
expect(helper.blob_render_error_options(viewer, :server_side_but_stored_in_lfs)).to include(/view the source/)
end
end
context 'the blob is not rendered as text' do
let(:blob) { fake_blob(path: 'file.pdf', binary: true) }
it 'does not include a "view the source" link' do
expect(helper.blob_render_error_options(viewer, :server_side_but_stored_in_lfs)).not_to include(/view the source/)
end
end
end
context 'when the viewer is not rich' do
before do
viewer_class.type = :simple
end
let(:blob) { fake_blob(path: 'file.md') }
it 'does not include a "view the source" link' do
expect(helper.blob_render_error_options(viewer, :server_side_but_stored_in_lfs)).not_to include(/view the source/)
end
end
it 'includes a "download it" link' do
expect(helper.blob_render_error_options(viewer, :server_side_but_stored_in_lfs)).to include(/download it/)
end
end
end
end end
/* eslint-disable no-new */
import BlobViewer from '~/blob/viewer/index';
describe('Blob viewer', () => {
preloadFixtures('blob/show.html.raw');
beforeEach(() => {
loadFixtures('blob/show.html.raw');
$('#modal-upload-blob').remove();
new BlobViewer();
spyOn($, 'ajax').and.callFake(() => {
const d = $.Deferred();
d.resolve({
html: '<div>testing</div>',
});
return d.promise();
});
});
afterEach(() => {
location.hash = '';
});
it('loads source file after switching views', (done) => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect($.ajax).toHaveBeenCalled();
expect(
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
.classList.contains('hidden'),
).toBeFalsy();
done();
});
});
it('loads source file when line number is in hash', (done) => {
location.hash = '#L1';
new BlobViewer();
setTimeout(() => {
expect($.ajax).toHaveBeenCalled();
expect(
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]')
.classList.contains('hidden'),
).toBeFalsy();
done();
});
});
it('doesnt reload file if already loaded', (done) => {
const asyncClick = () => new Promise((resolve) => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(resolve);
});
asyncClick()
.then(() => {
expect($.ajax).toHaveBeenCalled();
return asyncClick();
})
.then(() => {
expect($.ajax.calls.count()).toBe(1);
expect(
document.querySelector('.blob-viewer[data-type="simple"]').getAttribute('data-loaded'),
).toBe('true');
done();
});
});
describe('copy blob button', () => {
it('disabled on load', () => {
expect(
document.querySelector('.js-copy-blob-source-btn').classList.contains('disabled'),
).toBeTruthy();
});
it('has tooltip when disabled', () => {
expect(
document.querySelector('.js-copy-blob-source-btn').getAttribute('data-original-title'),
).toBe('Switch to the source view to copy the source to the clipboard');
});
it('enables after switching to simple view', (done) => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect($.ajax).toHaveBeenCalled();
expect(
document.querySelector('.js-copy-blob-source-btn').classList.contains('disabled'),
).toBeFalsy();
done();
});
});
it('updates tooltip after switching to simple view', (done) => {
document.querySelector('.js-blob-viewer-switch-btn[data-viewer="simple"]').click();
setTimeout(() => {
expect($.ajax).toHaveBeenCalled();
expect(
document.querySelector('.js-copy-blob-source-btn').getAttribute('data-original-title'),
).toBe('Copy to clipboard');
done();
});
});
});
});
require 'spec_helper'
describe Projects::BlobController, '(JavaScript fixtures)', type: :controller do
include JavaScriptFixturesHelpers
let(:admin) { create(:admin) }
let(:namespace) { create(:namespace, name: 'frontend-fixtures' )}
let(:project) { create(:project, :repository, namespace: namespace, path: 'branches-project') }
render_views
before(:all) do
clean_frontend_fixtures('blob/')
end
before(:each) do
sign_in(admin)
end
it 'blob/show.html.raw' do |example|
get(:show,
namespace_id: project.namespace,
project_id: project,
id: 'add-ipython-files/files/ipython/basic.ipynb')
expect(response).to be_success
store_frontend_fixture(response, example.description)
end
end
...@@ -2,6 +2,14 @@ ...@@ -2,6 +2,14 @@
require 'rails_helper' require 'rails_helper'
describe Blob do describe Blob do
include FakeBlobHelpers
let(:project) { build(:empty_project, lfs_enabled: true) }
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
end
describe '.decorate' do describe '.decorate' do
it 'returns NilClass when given nil' do it 'returns NilClass when given nil' do
expect(described_class.decorate(nil)).to be_nil expect(described_class.decorate(nil)).to be_nil
...@@ -12,7 +20,7 @@ describe Blob do ...@@ -12,7 +20,7 @@ describe Blob do
context 'using a binary blob' do context 'using a binary blob' do
it 'returns the data as-is' do it 'returns the data as-is' do
data = "\n\xFF\xB9\xC3" data = "\n\xFF\xB9\xC3"
blob = described_class.new(double(binary?: true, data: data)) blob = fake_blob(binary: true, data: data)
expect(blob.data).to eq(data) expect(blob.data).to eq(data)
end end
...@@ -20,202 +28,176 @@ describe Blob do ...@@ -20,202 +28,176 @@ describe Blob do
context 'using a text blob' do context 'using a text blob' do
it 'converts the data to UTF-8' do it 'converts the data to UTF-8' do
blob = described_class.new(double(binary?: false, data: "\n\xFF\xB9\xC3")) blob = fake_blob(binary: false, data: "\n\xFF\xB9\xC3")
expect(blob.data).to eq("\n���") expect(blob.data).to eq("\n���")
end end
end end
end end
describe '#svg?' do describe '#raw_binary?' do
it 'is falsey when not text' do context 'if the blob is a valid LFS pointer' do
git_blob = double(text?: false) context 'if the extension has a rich viewer' do
context 'if the viewer is binary' do
it 'return true' do
blob = fake_blob(path: 'file.pdf', lfs: true)
expect(described_class.decorate(git_blob)).not_to be_svg expect(blob.raw_binary?).to be_truthy
end end
it 'is falsey when no language is detected' do
git_blob = double(text?: true, language: nil)
expect(described_class.decorate(git_blob)).not_to be_svg
end end
it' is falsey when language is not SVG' do context 'if the viewer is text-based' do
git_blob = double(text?: true, language: double(name: 'XML')) it 'return false' do
blob = fake_blob(path: 'file.md', lfs: true)
expect(described_class.decorate(git_blob)).not_to be_svg expect(blob.raw_binary?).to be_falsey
end end
it 'is truthy when language is SVG' do
git_blob = double(text?: true, language: double(name: 'SVG'))
expect(described_class.decorate(git_blob)).to be_svg
end end
end end
describe '#pdf?' do context "if the extension doesn't have a rich viewer" do
it 'is falsey when file extension is not .pdf' do it 'returns true' do
git_blob = Gitlab::Git::Blob.new(name: 'git_blob.txt') blob = fake_blob(path: 'file.exe', lfs: true)
expect(described_class.decorate(git_blob)).not_to be_pdf expect(blob.raw_binary?).to be_truthy
end end
it 'is truthy when file extension is .pdf' do
git_blob = Gitlab::Git::Blob.new(name: 'git_blob.pdf')
expect(described_class.decorate(git_blob)).to be_pdf
end end
end end
describe '#ipython_notebook?' do context 'if the blob is not an LFS pointer' do
it 'is falsey when language is not Jupyter Notebook' do context 'if the blob is binary' do
git_blob = double(text?: true, language: double(name: 'JSON')) it 'return true' do
blob = fake_blob(path: 'file.pdf', binary: true)
expect(described_class.decorate(git_blob)).not_to be_ipython_notebook expect(blob.raw_binary?).to be_truthy
end
end end
it 'is truthy when language is Jupyter Notebook' do context 'if the blob is text-based' do
git_blob = double(text?: true, language: double(name: 'Jupyter Notebook')) it 'return false' do
blob = fake_blob(path: 'file.md')
expect(described_class.decorate(git_blob)).to be_ipython_notebook expect(blob.raw_binary?).to be_falsey
end
end
end end
end end
describe '#sketch?' do describe '#extension' do
it 'is falsey with image extension' do it 'returns the extension' do
git_blob = Gitlab::Git::Blob.new(name: "design.png") blob = fake_blob(path: 'file.md')
expect(described_class.decorate(git_blob)).not_to be_sketch expect(blob.extension).to eq('md')
end
end end
it 'is truthy with sketch extension' do describe '#simple_viewer' do
git_blob = Gitlab::Git::Blob.new(name: "design.sketch") context 'when the blob is empty' do
it 'returns an empty viewer' do
blob = fake_blob(data: '')
expect(described_class.decorate(git_blob)).to be_sketch expect(blob.simple_viewer).to be_a(BlobViewer::Empty)
end end
end end
describe '#video?' do context 'when the file represented by the blob is binary' do
it 'is falsey with image extension' do it 'returns a download viewer' do
git_blob = Gitlab::Git::Blob.new(name: 'image.png') blob = fake_blob(binary: true)
expect(described_class.decorate(git_blob)).not_to be_video expect(blob.simple_viewer).to be_a(BlobViewer::Download)
end
end end
UploaderHelper::VIDEO_EXT.each do |ext| context 'when the file represented by the blob is text-based' do
it "is truthy when extension is .#{ext}" do it 'returns a text viewer' do
git_blob = Gitlab::Git::Blob.new(name: "video.#{ext}") blob = fake_blob
expect(described_class.decorate(git_blob)).to be_video expect(blob.simple_viewer).to be_a(BlobViewer::Text)
end end
end end
end end
describe '#stl?' do describe '#rich_viewer' do
it 'is falsey with image extension' do context 'when the blob is an invalid LFS pointer' do
git_blob = Gitlab::Git::Blob.new(name: 'file.png') before do
project.lfs_enabled = false
expect(described_class.decorate(git_blob)).not_to be_stl
end end
it 'is truthy with STL extension' do it 'returns nil' do
git_blob = Gitlab::Git::Blob.new(name: 'file.stl') blob = fake_blob(path: 'file.pdf', lfs: true)
expect(described_class.decorate(git_blob)).to be_stl expect(blob.rich_viewer).to be_nil
end end
end end
describe '#to_partial_path' do context 'when the blob is empty' do
let(:project) { double(lfs_enabled?: true) } it 'returns nil' do
blob = fake_blob(data: '')
def stubbed_blob(overrides = {}) expect(blob.rich_viewer).to be_nil
overrides.reverse_merge!(
name: nil,
image?: false,
language: nil,
lfs_pointer?: false,
svg?: false,
text?: false,
binary?: false,
stl?: false
)
described_class.decorate(Gitlab::Git::Blob.new({})).tap do |blob|
allow(blob).to receive_messages(overrides)
end end
end end
it 'handles LFS pointers with LFS enabled' do context 'when the blob is a valid LFS pointer' do
blob = stubbed_blob(lfs_pointer?: true, text?: true) it 'returns a matching viewer' do
expect(blob.to_partial_path(project)).to eq 'download' blob = fake_blob(path: 'file.pdf', lfs: true)
end
it 'handles LFS pointers with LFS disabled' do expect(blob.rich_viewer).to be_a(BlobViewer::PDF)
blob = stubbed_blob(lfs_pointer?: true, text?: true)
project = double(lfs_enabled?: false)
expect(blob.to_partial_path(project)).to eq 'text'
end end
it 'handles SVGs' do
blob = stubbed_blob(text?: true, svg?: true)
expect(blob.to_partial_path(project)).to eq 'svg'
end end
it 'handles images' do context 'when the blob is binary' do
blob = stubbed_blob(image?: true) it 'returns a matching binary viewer' do
expect(blob.to_partial_path(project)).to eq 'image' blob = fake_blob(path: 'file.pdf', binary: true)
end
it 'handles text' do expect(blob.rich_viewer).to be_a(BlobViewer::PDF)
blob = stubbed_blob(text?: true, name: 'test.txt')
expect(blob.to_partial_path(project)).to eq 'text'
end end
it 'defaults to download' do
blob = stubbed_blob
expect(blob.to_partial_path(project)).to eq 'download'
end end
it 'handles PDFs' do context 'when the blob is text-based' do
blob = stubbed_blob(name: 'blob.pdf', pdf?: true) it 'returns a matching text-based viewer' do
expect(blob.to_partial_path(project)).to eq 'pdf' blob = fake_blob(path: 'file.md')
end
it 'handles iPython notebooks' do expect(blob.rich_viewer).to be_a(BlobViewer::Markup)
blob = stubbed_blob(text?: true, ipython_notebook?: true) end
expect(blob.to_partial_path(project)).to eq 'notebook'
end end
it 'handles Sketch files' do
blob = stubbed_blob(text?: true, sketch?: true, binary?: true)
expect(blob.to_partial_path(project)).to eq 'sketch'
end end
it 'handles STLs' do describe '#rendered_as_text?' do
blob = stubbed_blob(text?: true, stl?: true) context 'when ignoring errors' do
expect(blob.to_partial_path(project)).to eq 'stl' context 'when the simple viewer is text-based' do
it 'returns true' do
blob = fake_blob(path: 'file.md', size: 100.megabytes)
expect(blob.rendered_as_text?).to be_truthy
end end
end end
describe '#size_within_svg_limits?' do context 'when the simple viewer is binary' do
let(:blob) { described_class.decorate(double(:blob)) } it 'returns false' do
blob = fake_blob(path: 'file.pdf', binary: true, size: 100.megabytes)
it 'returns true when the blob size is smaller than the SVG limit' do
expect(blob).to receive(:size).and_return(42)
expect(blob.size_within_svg_limits?).to eq(true) expect(blob.rendered_as_text?).to be_falsey
end
end
end end
it 'returns true when the blob size is equal to the SVG limit' do context 'when not ignoring errors' do
expect(blob).to receive(:size).and_return(Blob::MAXIMUM_SVG_SIZE) context 'when the viewer has render errors' do
it 'returns false' do
blob = fake_blob(path: 'file.md', size: 100.megabytes)
expect(blob.size_within_svg_limits?).to eq(true) expect(blob.rendered_as_text?(ignore_errors: false)).to be_falsey
end
end end
it 'returns false when the blob size is larger than the SVG limit' do context "when the viewer doesn't have render errors" do
expect(blob).to receive(:size).and_return(1.terabyte) it 'returns true' do
blob = fake_blob(path: 'file.md')
expect(blob.size_within_svg_limits?).to eq(false) expect(blob.rendered_as_text?(ignore_errors: false)).to be_truthy
end
end
end end
end end
end end
require 'spec_helper'
describe BlobViewer::Base, model: true do
include FakeBlobHelpers
let(:project) { build(:empty_project) }
let(:viewer_class) do
Class.new(described_class) do
self.extensions = %w(pdf)
self.max_size = 1.megabyte
self.absolute_max_size = 5.megabytes
self.client_side = false
end
end
let(:viewer) { viewer_class.new(blob) }
describe '.can_render?' do
context 'when the extension is supported' do
let(:blob) { fake_blob(path: 'file.pdf') }
it 'returns true' do
expect(viewer_class.can_render?(blob)).to be_truthy
end
end
context 'when the extension is not supported' do
let(:blob) { fake_blob(path: 'file.txt') }
it 'returns false' do
expect(viewer_class.can_render?(blob)).to be_falsey
end
end
end
describe '#too_large?' do
context 'when the blob size is larger than the max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 2.megabytes) }
it 'returns true' do
expect(viewer.too_large?).to be_truthy
end
end
context 'when the blob size is smaller than the max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.kilobytes) }
it 'returns false' do
expect(viewer.too_large?).to be_falsey
end
end
end
describe '#absolutely_too_large?' do
context 'when the blob size is larger than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.megabytes) }
it 'returns true' do
expect(viewer.absolutely_too_large?).to be_truthy
end
end
context 'when the blob size is smaller than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 2.megabytes) }
it 'returns false' do
expect(viewer.absolutely_too_large?).to be_falsey
end
end
end
describe '#can_override_max_size?' do
context 'when the blob size is larger than the max size' do
context 'when the blob size is larger than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.megabytes) }
it 'returns false' do
expect(viewer.can_override_max_size?).to be_falsey
end
end
context 'when the blob size is smaller than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 2.megabytes) }
it 'returns true' do
expect(viewer.can_override_max_size?).to be_truthy
end
end
end
context 'when the blob size is smaller than the max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.kilobytes) }
it 'returns false' do
expect(viewer.can_override_max_size?).to be_falsey
end
end
end
describe '#render_error' do
context 'when the max size is overridden' do
before do
viewer.override_max_size = true
end
context 'when the blob size is larger than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.megabytes) }
it 'returns :too_large' do
expect(viewer.render_error).to eq(:too_large)
end
end
context 'when the blob size is smaller than the absolute max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 2.megabytes) }
it 'returns nil' do
expect(viewer.render_error).to be_nil
end
end
end
context 'when the max size is not overridden' do
context 'when the blob size is larger than the max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 2.megabytes) }
it 'returns :too_large' do
expect(viewer.render_error).to eq(:too_large)
end
end
context 'when the blob size is smaller than the max size' do
let(:blob) { fake_blob(path: 'file.pdf', size: 10.kilobytes) }
it 'returns nil' do
expect(viewer.render_error).to be_nil
end
end
end
context 'when the viewer is server side but the blob is stored in LFS' do
let(:project) { build(:empty_project, lfs_enabled: true) }
let(:blob) { fake_blob(path: 'file.pdf', lfs: true) }
before do
allow(Gitlab.config.lfs).to receive(:enabled).and_return(true)
end
it 'return :server_side_but_stored_in_lfs' do
expect(viewer.render_error).to eq(:server_side_but_stored_in_lfs)
end
end
end
describe '#prepare!' do
context 'when the viewer is server side' do
let(:blob) { fake_blob(path: 'file.md') }
before do
viewer_class.client_side = false
end
it 'loads all blob data' do
expect(blob).to receive(:load_all_data!)
viewer.prepare!
end
end
context 'when the viewer is client side' do
let(:blob) { fake_blob(path: 'file.md') }
before do
viewer_class.client_side = true
end
it "doesn't load all blob data" do
expect(blob).not_to receive(:load_all_data!)
viewer.prepare!
end
end
end
end
module FakeBlobHelpers
class FakeBlob
include Linguist::BlobHelper
attr_reader :path, :size, :data, :lfs_oid, :lfs_size
def initialize(path: 'file.txt', size: 1.kilobyte, data: 'foo', binary: false, lfs: nil)
@path = path
@size = size
@data = data
@binary = binary
@lfs_pointer = lfs.present?
if @lfs_pointer
@lfs_oid = SecureRandom.hex(20)
@lfs_size = 1.megabyte
end
end
alias_method :name, :path
def mode
nil
end
def id
0
end
def binary?
@binary
end
def load_all_data!(repository)
# No-op
end
def lfs_pointer?
@lfs_pointer
end
def truncated?
false
end
end
def fake_blob(**kwargs)
Blob.decorate(FakeBlob.new(**kwargs), project)
end
end
require 'spec_helper'
describe 'projects/blob/_viewer.html.haml', :view do
include FakeBlobHelpers
let(:project) { build(:empty_project) }
let(:viewer_class) do
Class.new(BlobViewer::Base) do
include BlobViewer::Rich
self.partial_name = 'text'
self.max_size = 1.megabyte
self.absolute_max_size = 5.megabytes
self.client_side = false
end
end
let(:viewer) { viewer_class.new(blob) }
let(:blob) { fake_blob }
before do
assign(:project, project)
assign(:id, File.join('master', blob.path))
controller.params[:controller] = 'projects/blob'
controller.params[:action] = 'show'
controller.params[:namespace_id] = project.namespace.to_param
controller.params[:project_id] = project.to_param
controller.params[:id] = File.join('master', blob.path)
end
def render_view
render partial: 'projects/blob/viewer', locals: { viewer: viewer }
end
context 'when the viewer is server side' do
before do
viewer_class.client_side = false
end
context 'when there is no render error' do
it 'adds a URL to the blob viewer element' do
render_view
expect(rendered).to have_css('.blob-viewer[data-url]')
end
it 'displays a spinner' do
render_view
expect(rendered).to have_css('i[aria-label="Loading content"]')
end
end
context 'when there is a render error' do
let(:blob) { fake_blob(size: 10.megabytes) }
it 'renders the error' do
render_view
expect(view).to render_template('projects/blob/_render_error')
end
end
end
context 'when the viewer is client side' do
before do
viewer_class.client_side = true
end
context 'when there is no render error' do
it 'prepares the viewer' do
expect(viewer).to receive(:prepare!)
render_view
end
it 'renders the viewer' do
render_view
expect(view).to render_template('projects/blob/viewers/_text')
end
end
context 'when there is a render error' do
let(:blob) { fake_blob(size: 10.megabytes) }
it 'renders the error' do
render_view
expect(view).to render_template('projects/blob/_render_error')
end
end
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment