Class: Rack::Git::File

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/git/file.rb

Constant Summary collapse

F =
::File

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ File

Returns a new instance of File.



14
15
16
17
# File 'lib/rack/git/file.rb', line 14

def initialize(root)
  @root = root
  @repo = Grit::Repo.new(@root)
end

Instance Attribute Details

#pathObject Also known as: to_path

Returns the value of attribute path.



10
11
12
# File 'lib/rack/git/file.rb', line 10

def path
  @path
end

#rootObject

Returns the value of attribute root.



9
10
11
# File 'lib/rack/git/file.rb', line 9

def root
  @root
end

Instance Method Details

#_call(env) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/git/file.rb', line 25

def _call(env)
  @branch_name = env['PATH_PREFIX'].sub(/^\//,"") || "master"
  @path_info = Rack::Utils.unescape(env["PATH_INFO"]).sub(/^\//,"")
  return forbidden  if @path_info.include? ".."

  begin
    serving
  rescue SystemCallError
    not_found
  end
end

#call(env) ⇒ Object



19
20
21
# File 'lib/rack/git/file.rb', line 19

def call(env)
  dup._call(env)
end

#eachObject



74
75
76
77
78
79
80
81
# File 'lib/rack/git/file.rb', line 74

def each
  body = @repo.tree(@branch_name).contents.select{|c| c.name == @path_info}[0].data
  StringIO.new(body, "rb") do |file|
    while part = file.read(8192)
      yield part
    end
  end
end

#forbiddenObject



37
38
39
40
41
42
43
# File 'lib/rack/git/file.rb', line 37

def forbidden
  body = "Forbidden\n"
  [403, {"Content-Type" => "text/plain",
      "Content-Length" => body.size.to_s,
      "X-Cascade" => "pass"},
    [body]]
end

#not_foundObject



66
67
68
69
70
71
72
# File 'lib/rack/git/file.rb', line 66

def not_found
  body = "File not found: #{@path_info}\n"
  [404, {"Content-Type" => "text/plain",
      "Content-Length" => body.size.to_s,
      "X-Cascade" => "pass"},
    [body]]
end

#servingObject

NOTE:

We check via File::size? whether this file provides size info
via stat (e.g. /proc files often don't), otherwise we have to
figure it out by reading the whole file into memory. And while
we're at it we also use this as body then.


51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rack/git/file.rb', line 51

def serving
  history       = @repo.log(@branch_name, @path_info, :max_count => 1, :skip => 0)
  blob          = history[0].tree / @path_info

  body          = blob.data
  last_modified = history[0].authored_date
  size          = blob.size

  [200, {
      "Last-Modified"  => last_modified.httpdate,
      "Content-Type"   => Rack::Mime.mime_type(F.extname(@path_info), 'text/plain'),
      "Content-Length" => size.to_s
    }, body]
end