Class: Grit::Repo

Inherits:
Object
  • Object
show all
Defined in:
lib/grit/repo.rb

Constant Summary collapse

DAEMON_EXPORT_FILE =
'git-daemon-export-ok'
BATCH_PARSERS =
{
  'commit' => ::Grit::Commit
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, options = {}) ⇒ Repo

Public: Create a new Repo instance.

path - The String path to either the root git directory or the bare

git repo. Bare repos are expected to end with ".git".

options - A Hash of options (default: {}):

:is_bare - Boolean whether to consider the repo as bare even
           if the repo name does not end with ".git".

Examples

r = Repo.new("/Users/tom/dev/normal")
r = Repo.new("/Users/tom/public/bare.git")
r = Repo.new("/Users/tom/public/bare", {:is_bare => true})

Returns a newly initialized Grit::Repo. Raises Grit::InvalidGitRepositoryError if the path exists but is not

a Git repository.

Raises Grit::NoSuchPathError if the path does not exist.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/grit/repo.rb', line 40

def initialize(path, options = {})
  epath = File.expand_path(path)

  if File.exist?(File.join(epath, '.git'))
    self.working_dir = epath
    self.path = File.join(epath, '.git')
    @bare = false
  elsif File.exist?(epath) && (epath =~ /\.git$/ || options[:is_bare])
    self.path = epath
    @bare = true
  elsif File.exist?(epath)
    raise InvalidGitRepositoryError.new(epath)
  else
    raise NoSuchPathError.new(epath)
  end

  self.git = Git.new(self.path)
end

Instance Attribute Details

#bareObject (readonly)

Public: The Boolean of whether or not the repo is bare.



17
18
19
# File 'lib/grit/repo.rb', line 17

def bare
  @bare
end

#gitObject

Public: The Grit::Git command line interface object.



20
21
22
# File 'lib/grit/repo.rb', line 20

def git
  @git
end

#pathObject

Public: The String path of the Git repo.



10
11
12
# File 'lib/grit/repo.rb', line 10

def path
  @path
end

#working_dirObject

Public: The String path to the working directory of the repo, or nil if there is no working directory.



14
15
16
# File 'lib/grit/repo.rb', line 14

def working_dir
  @working_dir
end

Class Method Details

.init(path, git_options = {}, repo_options = {}) ⇒ Object

Public: Initialize a git repository (create it on the filesystem). By default, the newly created repository will contain a working directory. If you would like to create a bare repo, use Grit::Repo.init_bare.

path - The String full path to the repo. Traditionally ends with

"/<name>.git".

git_options - A Hash of additional options to the git init command

(default: {}).

repo_options - A Hash of additional options to the Grit::Repo.new call

(default: {}).

Examples

Grit::Repo.init('/var/git/myrepo.git')

Returns the newly created Grit::Repo.



75
76
77
78
79
80
81
# File 'lib/grit/repo.rb', line 75

def self.init(path, git_options = {}, repo_options = {})
  git_options = {:base => false}.merge(git_options)
  git = Git.new(path)
  git.fs_mkdir('..')
  git.init(git_options, path)
  self.new(path, repo_options)
end

.init_bare(path, git_options = {}, repo_options = {}) ⇒ Object

Public: Initialize a bare git repository (create it on the filesystem).

path - The String full path to the repo. Traditionally ends with

"/<name>.git".

git_options - A Hash of additional options to the git init command

(default: {}).

repo_options - A Hash of additional options to the Grit::Repo.new call

(default: {}).

Examples

Grit::Repo.init_bare('/var/git/myrepo.git')

Returns the newly created Grit::Repo.



97
98
99
100
101
102
103
# File 'lib/grit/repo.rb', line 97

def self.init_bare(path, git_options = {}, repo_options = {})
  git_options = {:bare => true}.merge(git_options)
  git = Git.new(path)
  git.fs_mkdir('..')
  git.init(git_options)
  self.new(path, repo_options)
end

.init_bare_or_open(path, git_options = {}, repo_options = {}) ⇒ Object

Public: Initialize a bare Git repository (create it on the filesystem) or, if the repo already exists, simply return it.

path - The String full path to the repo. Traditionally ends with

"/<name>.git".

git_options - A Hash of additional options to the git init command

(default: {}).

repo_options - A Hash of additional options to the Grit::Repo.new call

(default: {}).

Returns the new or existing Grit::Repo.



116
117
118
119
120
121
122
123
124
125
# File 'lib/grit/repo.rb', line 116

def self.init_bare_or_open(path, git_options = {}, repo_options = {})
  git = Git.new(path)

  unless git.exist?
    git.fs_mkdir(path)
    git.init(git_options)
  end

  self.new(path, repo_options)
end

Instance Method Details

#add(*files) ⇒ Object

Adds files to the index



251
252
253
# File 'lib/grit/repo.rb', line 251

def add(*files)
  self.git.add({}, *files.flatten)
end

#alternatesObject

The list of alternates for this repo

Returns Array (pathnames of alternates)



600
601
602
603
604
605
# File 'lib/grit/repo.rb', line 600

def alternates
  alternates_path = "objects/info/alternates"
  self.git.fs_read(alternates_path).strip.split("\n")
rescue Errno::ENOENT
  []
end

#alternates=(alts) ⇒ Object

Sets the alternates

+alts+ is the Array of String paths representing the alternates

Returns nothing



611
612
613
614
615
616
617
618
619
620
621
622
623
# File 'lib/grit/repo.rb', line 611

def alternates=(alts)
  alts.each do |alt|
    unless File.exist?(alt)
      raise "Could not set alternates. Alternate path #{alt} must exist"
    end
  end

  if alts.empty?
    self.git.fs_write('objects/info/alternates', '')
  else
    self.git.fs_write('objects/info/alternates', alts.join("\n"))
  end
end

#archive_tar(treeish = 'master', prefix = nil) ⇒ Object

Archive the given treeish

+treeish+ is the treeish name/id (default 'master')
+prefix+ is the optional prefix

Examples

repo.archive_tar
# => <String containing tar archive>

repo.archive_tar('a87ff14')
# => <String containing tar archive for commit a87ff14>

repo.archive_tar('master', 'myproject/')
# => <String containing tar archive and prefixed with 'myproject/'>

Returns String (containing tar archive)



535
536
537
538
539
# File 'lib/grit/repo.rb', line 535

def archive_tar(treeish = 'master', prefix = nil)
  options = {}
  options[:prefix] = prefix if prefix
  self.git.archive(options, treeish)
end

#archive_tar_gz(treeish = 'master', prefix = nil) ⇒ Object

Archive and gzip the given treeish

+treeish+ is the treeish name/id (default 'master')
+prefix+ is the optional prefix

Examples

repo.archive_tar_gz
# => <String containing tar.gz archive>

repo.archive_tar_gz('a87ff14')
# => <String containing tar.gz archive for commit a87ff14>

repo.archive_tar_gz('master', 'myproject/')
# => <String containing tar.gz archive and prefixed with 'myproject/'>

Returns String (containing tar.gz archive)



556
557
558
559
560
# File 'lib/grit/repo.rb', line 556

def archive_tar_gz(treeish = 'master', prefix = nil)
  options = {}
  options[:prefix] = prefix if prefix
  self.git.archive(options, treeish, "| gzip -n")
end

#archive_to_file(treeish = 'master', prefix = nil, filename = 'archive.tar.gz', format = nil, pipe = "gzip") ⇒ Object

Write an archive directly to a file

+treeish+ is the treeish name/id (default 'master')
+prefix+ is the optional prefix (default nil)
+filename+ is the name of the file (default 'archive.tar.gz')
+format+ is the optional format (default nil)
+pipe+ is the command to run the output through (default 'gzip')

Returns nothing



570
571
572
573
574
575
# File 'lib/grit/repo.rb', line 570

def archive_to_file(treeish = 'master', prefix = nil, filename = 'archive.tar.gz', format = nil, pipe = "gzip")
  options = {}
  options[:prefix] = prefix if prefix
  options[:format] = format if format
  self.git.archive(options, treeish, "| #{pipe} > #{filename}")
end

#batch(*shas) ⇒ Object

Public: Return the full Git objects from the given SHAs. Only Commit objects are parsed for now.

*shas - Array of String SHAs.

Returns an Array of Grit objects (Grit::Commit).



167
168
169
170
171
172
173
174
175
# File 'lib/grit/repo.rb', line 167

def batch(*shas)
  shas.flatten!
  text = git.native(:cat_file, {:batch => true}) do |stdin|
    stdin.write(shas * "\n")
    stdin.close
  end

  parse_batch(text)
end

#blame(file, commit = nil) ⇒ Object



206
207
208
# File 'lib/grit/repo.rb', line 206

def blame(file, commit = nil)
  Blame.new(self, file, commit)
end

#blame_tree(commit, path = nil) ⇒ Object



261
262
263
264
265
266
267
268
269
# File 'lib/grit/repo.rb', line 261

def blame_tree(commit, path = nil)
  commit_array = self.git.blame_tree(commit, path)

  final_array = {}
  commit_array.each do |file, sha|
    final_array[file] = commit(sha)
  end
  final_array
end

#blob(id) ⇒ Object

The Blob object for the given id

+id+ is the SHA1 id of the blob

Returns Grit::Blob (unbaked)



482
483
484
# File 'lib/grit/repo.rb', line 482

def blob(id)
  Blob.create(self, :id => id)
end

#commit(id) ⇒ Object

The Commit object for the specified id

+id+ is the SHA1 identifier of the commit

Returns Grit::Commit (baked)



406
407
408
409
410
# File 'lib/grit/repo.rb', line 406

def commit(id)
  options = {:max_count => 1}

  Commit.find_all(self, id, options).first
end

#commit_all(message) ⇒ Object

Commits all tracked and modified files

Returns true/false if commit worked



246
247
248
# File 'lib/grit/repo.rb', line 246

def commit_all(message)
  self.git.commit({}, '-a', '-m', message)
end

#commit_count(start = 'master') ⇒ Object

The number of commits reachable by the given branch/commit

+start+ is the branch/commit name (default 'master')

Returns Integer



398
399
400
# File 'lib/grit/repo.rb', line 398

def commit_count(start = 'master')
  Commit.count(self, start)
end

#commit_deltas_from(other_repo, ref = "master", other_ref = "master") ⇒ Object

Returns a list of commits that is in other_repo but not in self

Returns Grit::Commit[]



415
416
417
418
419
420
421
422
423
424
# File 'lib/grit/repo.rb', line 415

def commit_deltas_from(other_repo, ref = "master", other_ref = "master")
  # TODO: we should be able to figure out the branch point, rather than
  # rev-list'ing the whole thing
  repo_refs       = self.git.rev_list({}, ref).strip.split("\n")
  other_repo_refs = other_repo.git.rev_list({}, other_ref).strip.split("\n")

  (other_repo_refs - repo_refs).map do |ref|
    Commit.find_all(other_repo, ref, {:max_count => 1}).first
  end
end

#commit_diff(commit) ⇒ Object

The commit diff for the given commit

+commit+ is the commit name/id

Returns Grit::Diff[]



516
517
518
# File 'lib/grit/repo.rb', line 516

def commit_diff(commit)
  Commit.diff(self, commit)
end

#commit_index(message) ⇒ Object

Commits current index

Returns true/false if commit worked



239
240
241
# File 'lib/grit/repo.rb', line 239

def commit_index(message)
  self.git.commit({}, '-m', message)
end

#commit_objects(refs) ⇒ Object



433
434
435
436
437
438
# File 'lib/grit/repo.rb', line 433

def commit_objects(refs)
  Grit.no_quote = true
  obj = self.git.rev_list({:timeout => false}, refs).split("\n").map { |a| a[0, 40] }
  Grit.no_quote = false
  obj
end

#commit_stats(start = 'master', max_count = 10, skip = 0) ⇒ Object



351
352
353
354
355
356
# File 'lib/grit/repo.rb', line 351

def commit_stats(start = 'master', max_count = 10, skip = 0)
  options = {:max_count => max_count,
             :skip => skip}

  CommitStats.find_all(self, start, options)
end

#commits(start = 'master', max_count = 10, skip = 0) ⇒ Object

An array of Commit objects representing the history of a given ref/commit

+start+ is the branch/commit name (default 'master')
+max_count+ is the maximum number of commits to return (default 10, use +false+ for all)
+skip+ is the number of commits to skip (default 0)

Returns Grit::Commit[] (baked)



364
365
366
367
368
369
# File 'lib/grit/repo.rb', line 364

def commits(start = 'master', max_count = 10, skip = 0)
  options = {:max_count => max_count,
             :skip => skip}

  Commit.find_all(self, start, options)
end

#commits_between(from, to) ⇒ Object

The Commits objects that are reachable via to but not via from Commits are returned in chronological order.

+from+ is the branch/commit name of the younger item
+to+ is the branch/commit name of the older item

Returns Grit::Commit[] (baked)



377
378
379
# File 'lib/grit/repo.rb', line 377

def commits_between(from, to)
  Commit.find_all(self, "#{from}..#{to}").reverse
end

#commits_since(start = 'master', since = '1970-01-01', extra_options = {}) ⇒ Object

The Commits objects that are newer than the specified date. Commits are returned in chronological order.

+start+ is the branch/commit name (default 'master')
+since+ is a string represeting a date/time
+extra_options+ is a hash of extra options

Returns Grit::Commit[] (baked)



388
389
390
391
392
# File 'lib/grit/repo.rb', line 388

def commits_since(start = 'master', since = '1970-01-01', extra_options = {})
  options = {:since => since}.merge(extra_options)

  Commit.find_all(self, start, options)
end

#configObject



625
626
627
# File 'lib/grit/repo.rb', line 625

def config
  @config ||= Config.new(self)
end

#descriptionObject

The project’s description. Taken verbatim from GIT_REPO/description

Returns String



202
203
204
# File 'lib/grit/repo.rb', line 202

def description
  self.git.fs_read('description').chomp
end

#diff(a, b, *paths) ⇒ Object

The diff from commit a to commit b, optionally restricted to the given file(s)

+a+ is the base commit
+b+ is the other commit
+paths+ is an optional list of file paths on which to restrict the diff


501
502
503
504
505
506
507
508
509
510
# File 'lib/grit/repo.rb', line 501

def diff(a, b, *paths)
  diff = self.git.native('diff', {:full_index => true}, a, b, '--', *paths)

  if diff =~ /diff --git a/
    diff = diff.sub(/.*?(diff --git a)/m, '\1')
  else
    diff = ''
  end
  Diff.list_from_string(self, diff)
end

#diff_objects(commit_sha, parents = true) ⇒ Object



449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/grit/repo.rb', line 449

def diff_objects(commit_sha, parents = true)
  revs = []
  Grit.no_quote = true
  if parents
    # PARENTS:
    cmd = "-r -t -m #{commit_sha}"
    revs = self.git.diff_tree({:timeout => false}, cmd).strip.split("\n").map{ |a| r = a.split(' '); r[3] if r[1] != '160000' }
  else
    # NO PARENTS:
    cmd = "-r -t #{commit_sha}"
    revs = self.git.method_missing('ls-tree', {:timeout => false}, "-r -t #{commit_sha}").split("\n").map{ |a| a.split("\t").first.split(' ')[2] }
  end
  revs << self.commit(commit_sha).tree.id
  Grit.no_quote = false
  return revs.uniq.compact
end

#disable_daemon_serveObject

Disable git-daemon serving of this repository by ensuring there is no git-daemon-export-ok file in its git directory

Returns nothing



589
590
591
# File 'lib/grit/repo.rb', line 589

def disable_daemon_serve
  self.git.fs_delete(DAEMON_EXPORT_FILE)
end

#enable_daemon_serveObject

Enable git-daemon serving of this repository by writing the git-daemon-export-ok file to its git directory

Returns nothing



581
582
583
# File 'lib/grit/repo.rb', line 581

def enable_daemon_serve
  self.git.fs_write(DAEMON_EXPORT_FILE, '')
end

#fork_bare(path, options = {}) ⇒ Object

Public: Create a bare fork of this repository.

path - The String full path of where to create the new fork.

Traditionally ends with "/<name>.git".

options - The Hash of additional options to the git clone command.

These options will be merged on top of the default Hash:
{:bare => true, :shared => true}.

Returns the newly forked Grit::Repo.



136
137
138
139
140
141
142
# File 'lib/grit/repo.rb', line 136

def fork_bare(path, options = {})
  default_options = {:bare => true, :shared => true}
  real_options = default_options.merge(options)
  Git.new(path).fs_mkdir('..')
  self.git.clone(real_options, self.path, path)
  Repo.new(path)
end

#fork_bare_from(path, options = {}) ⇒ Object

Public: Fork a bare git repository from another repo.

path - The String full path of the repo from which to fork..

Traditionally ends with "/<name>.git".

options - The Hash of additional options to the git clone command.

These options will be merged on top of the default Hash:
{:bare => true, :shared => true}.

Returns the newly forked Grit::Repo.



153
154
155
156
157
158
159
# File 'lib/grit/repo.rb', line 153

def fork_bare_from(path, options = {})
  default_options = {:bare => true, :shared => true}
  real_options = default_options.merge(options)
  Git.new(self.path).fs_mkdir('..')
  self.git.clone(real_options, path, self.path)
  Repo.new(self.path)
end

#gc_autoObject



593
594
595
# File 'lib/grit/repo.rb', line 593

def gc_auto
  self.git.gc({:auto => true})
end

#get_head(head_name) ⇒ Object



220
221
222
# File 'lib/grit/repo.rb', line 220

def get_head(head_name)
  heads.find { |h| h.name == head_name }
end

#headObject

Object reprsenting the current repo head.

Returns Grit::Head (baked)



231
232
233
# File 'lib/grit/repo.rb', line 231

def head
  Head.current(self)
end

#headsObject Also known as: branches

An array of Head objects representing the branch heads in this repo

Returns Grit::Head[] (baked)



214
215
216
# File 'lib/grit/repo.rb', line 214

def heads
  Head.find_all(self)
end

#indexObject



629
630
631
# File 'lib/grit/repo.rb', line 629

def index
  Index.new(self)
end

#inspectObject

Pretty object inspection



652
653
654
# File 'lib/grit/repo.rb', line 652

def inspect
  %Q{#<Grit::Repo "#{@path}">}
end

#is_head?(head_name) ⇒ Boolean

Returns:

  • (Boolean)


224
225
226
# File 'lib/grit/repo.rb', line 224

def is_head?(head_name)
  get_head(head_name)
end

#log(commit = 'master', path = nil, options = {}) ⇒ Object

The commit log for a treeish

Returns Grit::Commit[]



489
490
491
492
493
494
495
# File 'lib/grit/repo.rb', line 489

def log(commit = 'master', path = nil, options = {})
  default_options = {:pretty => "raw"}
  actual_options  = default_options.merge(options)
  arg = path ? [commit, '--', path] : [commit]
  commits = self.git.log(actual_options, *arg)
  Commit.list_from_string(self, commits)
end

#objects(refs) ⇒ Object



426
427
428
429
430
431
# File 'lib/grit/repo.rb', line 426

def objects(refs)
  Grit.no_quote = true
  obj = self.git.rev_list({:objects => true, :timeout => false}, refs).split("\n").map { |a| a[0, 40] }
  Grit.no_quote = false
  obj
end

#objects_between(ref1, ref2 = nil) ⇒ Object



440
441
442
443
444
445
446
447
# File 'lib/grit/repo.rb', line 440

def objects_between(ref1, ref2 = nil)
  if ref2
    refs = "#{ref2}..#{ref1}"
  else
    refs = ref1
  end
  self.objects(refs)
end

#parse_batch(text) ⇒ Object

Parses ‘git cat-file –batch` output, returning an array of Grit objects.

text - Raw String output.

Returns an Array of Grit objects (Grit::Commit).



182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/grit/repo.rb', line 182

def parse_batch(text)
  io = StringIO.new(text)
  objects = []
  while line = io.gets
    sha, type, size = line.split(" ", 3)
    parser = BATCH_PARSERS[type]
    if type == 'missing' || !parser
      objects << nil
      next
    end

    object   = io.read(size.to_i + 1)
    objects << parser.parse_batch(self, sha, size, object)
  end
  objects
end

#recent_tag_name(committish = nil, options = {}) ⇒ Object

Finds the most recent annotated tag name that is reachable from a commit.

@repo.recent_tag_name('master')
# => "v1.0-0-abcdef"

committish - optional commit SHA, branch, or tag name. options - optional hash of options to pass to git.

Default: {:always => true}
:tags => true      # use lightweight tags too.
:abbrev => Integer # number of hex digits to form the unique
  name.  Defaults to 7.
:long => true      # always output tag + commit sha
# see `git describe` docs for more options.

Returns the String tag name, or just the commit if no tag is found. If there have been updates since the tag was made, a suffix is added with the number of commits since the tag, and the abbreviated object name of the most recent commit. Returns nil if the committish value is not found.



302
303
304
305
# File 'lib/grit/repo.rb', line 302

def recent_tag_name(committish = nil, options = {})
  value = git.describe({:always => true}.update(options), committish.to_s).to_s.strip
  value.size.zero? ? nil : value
end

#refsObject

An array of Ref objects representing the refs in this repo

Returns Grit::Ref[] (baked)



347
348
349
# File 'lib/grit/repo.rb', line 347

def refs
  [ Head.find_all(self), Tag.find_all(self), Remote.find_all(self) ].flatten
end

#remote_add(name, url) ⇒ Object



319
320
321
# File 'lib/grit/repo.rb', line 319

def remote_add(name, url)
  self.git.remote({}, 'add', name, url)
end

#remote_fetch(name) ⇒ Object



323
324
325
# File 'lib/grit/repo.rb', line 323

def remote_fetch(name)
  self.git.fetch({}, name)
end

#remote_listObject



315
316
317
# File 'lib/grit/repo.rb', line 315

def remote_list
  self.git.list_remotes
end

#remotesObject

An array of Remote objects representing the remote branches in this repo

Returns Grit::Remote[] (baked)



311
312
313
# File 'lib/grit/repo.rb', line 311

def remotes
  Remote.find_all(self)
end

#remotes_fetch_needed(remotes) ⇒ Object

takes an array of remote names and last pushed dates fetches from all of the remotes where the local fetch date is earlier than the passed date, then records the last fetched date

{ ‘origin’ => date,

'peter => date,

}



335
336
337
338
339
340
# File 'lib/grit/repo.rb', line 335

def remotes_fetch_needed(remotes)
  remotes.each do |remote, date|
    # TODO: check against date
    self.remote_fetch(remote)
  end
end

#remove(*files) ⇒ Object

Remove files from the index



256
257
258
# File 'lib/grit/repo.rb', line 256

def remove(*files)
  self.git.rm({}, *files.flatten)
end

#rename(name) ⇒ Object

Rename the current repository directory.

+name+ is the new name

Returns nothing



643
644
645
646
647
648
649
# File 'lib/grit/repo.rb', line 643

def rename(name)
  if @bare
    self.git.fs_move('/', "../#{name}")
  else
    self.git.fs_move('/', "../../#{name}")
  end
end

#statusObject



271
272
273
# File 'lib/grit/repo.rb', line 271

def status
  Status.new(self)
end

#tagsObject

An array of Tag objects that are available in this repo

Returns Grit::Tag[] (baked)



279
280
281
# File 'lib/grit/repo.rb', line 279

def tags
  Tag.find_all(self)
end

#tree(treeish = 'master', paths = []) ⇒ Object

The Tree object for the given treeish reference

+treeish+ is the reference (default 'master')
+paths+ is an optional Array of directory paths to restrict the tree (deafult [])

Examples

repo.tree('master', ['lib/'])

Returns Grit::Tree (baked)



474
475
476
# File 'lib/grit/repo.rb', line 474

def tree(treeish = 'master', paths = [])
  Tree.construct(self, treeish, paths)
end

#update_ref(head, commit_sha) ⇒ Object



633
634
635
636
637
# File 'lib/grit/repo.rb', line 633

def update_ref(head, commit_sha)
  return nil if !commit_sha || (commit_sha.size != 40)
  self.git.fs_write("refs/heads/#{head}", commit_sha)
  commit_sha
end