Class: Gitlab::Git::Repository
- Inherits:
-
Object
- Object
- Gitlab::Git::Repository
- Extended by:
- Forwardable
- Includes:
- Popen
- Defined in:
- lib/gitlab_git/repository.rb
Defined Under Namespace
Classes: InvalidBlobName, InvalidRef, NoRepository
Constant Summary collapse
- SEARCH_CONTEXT_LINES =
3
- AUTOCRLF_VALUES =
{ "true" => true, "false" => false, "input" => :input }.freeze
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Directory name of repo.
-
#path ⇒ Object
readonly
Full path to repo.
-
#rugged ⇒ Object
readonly
Rugged repo object.
Instance Method Summary collapse
-
#add_tag(tag_name, ref_target, options = nil) ⇒ Object
Add a tag with
tag_name+
name to the repository in correspondingref_target+
supports passing a hash of options to create an annotated tag. - #archive_file_path(name, storage_path, format = "tar.gz") ⇒ Object
- #archive_metadata(ref, storage_path, format = "tar.gz") ⇒ Object
- #autocrlf ⇒ Object
- #autocrlf=(value) ⇒ Object
- #bare? ⇒ Boolean
-
#branch_count ⇒ Object
Returns the number of valid branches.
-
#branch_exists?(name) ⇒ Boolean
Returns true if the given branch exists.
-
#branch_names ⇒ Object
Returns an Array of branch names sorted by name ASC.
-
#branch_names_contains(commit) ⇒ Object
Returns branch names collection that contains the special commit(SHA1 or name).
-
#branches ⇒ Object
Returns an Array of Branches.
-
#branches_contains(commit) ⇒ Object
Returns branch collection that contains the special commit(SHA1 or name).
-
#checkout(ref, options = {}, start_point = "HEAD") ⇒ Object
Check out the specified ref.
-
#clean(options = {}) ⇒ Object
Mimic the ‘git clean` command and recursively delete untracked files.
-
#commit_count(ref) ⇒ Object
Return total commits count accessible from passed ref.
-
#commits_between(from, to) ⇒ Object
Return a collection of Rugged::Commits between the two revspec arguments.
- #commits_since(from_date) ⇒ Object
- #copy_gitattributes(ref) ⇒ Object
-
#count_commits_between(from, to) ⇒ Object
Counts the amount of commits between ‘from` and `to`.
-
#create_branch(ref, start_point = "HEAD") ⇒ Object
Create a new branch named **ref+ based on **stat_point+, HEAD by default.
-
#delete_branch(branch_name) ⇒ Object
Delete the specified branch from the repository.
-
#diff(from, to, options = {}, *paths) ⇒ Object
Return an array of Diff objects that represent the diff between
from
andto
. -
#diff_text(from, to, options = {}, *paths) ⇒ Object
Return the diff between
from
andto
in a single patch string. -
#diffable?(blob) ⇒ Boolean
Checks if the blob should be diffable according to its attributes.
-
#discover_default_branch ⇒ Object
Discovers the default branch based on the repository’s available branches.
- #empty? ⇒ Boolean
-
#fetch(remote_name) ⇒ Object
Fetch the specified remote.
-
#find_commits(options = {}) ⇒ Object
Returns commits collection.
-
#format_patch(from, to, options = {}) ⇒ Object
Return a String containing the mbox-formatted diff between
from
andto
. - #has_commits? ⇒ Boolean
-
#heads ⇒ Object
Deprecated.
-
#initialize(path) ⇒ Repository
constructor
‘path’ must be the path to a bare git repository, e.g.
-
#log(options) ⇒ Object
Use the Rugged Walker API to build an array of commits.
- #log_by_shell(sha, options) ⇒ Object
- #log_by_walk(sha, options) ⇒ Object
- #log_using_shell?(options) ⇒ Boolean
-
#lookup(oid_or_ref_name) ⇒ Object
Lookup for rugged object by oid or ref name.
-
#ls_files(ref) ⇒ Object
Returns result like “git ls-files” , recursive and full file path.
-
#merge(source_name, target_name, options = {}) ⇒ Object
Merge the
source_name
branch into thetarget_name
branch. -
#merge_base_commit(from, to) ⇒ Object
Returns the SHA of the most recent common ancestor of
from
andto
. -
#mkdir(path, options = {}) ⇒ Object
Create a new directory with a .gitkeep file.
-
#push(remote_name, *refspecs) ⇒ Object
Push *refspecs to the remote identified by
remote_name
. -
#raw ⇒ Object
Alias to old method for compatibility.
-
#ref_names ⇒ Object
Returns an Array of branch and tag names.
-
#refs_hash ⇒ Object
Get refs hash which key is SHA1 and value is a Rugged::Reference.
-
#remote_add(remote_name, url) ⇒ Object
Add a new remote to this repository.
-
#remote_delete(remote_name) ⇒ Object
Delete the specified remote from this repository.
-
#remote_names ⇒ Object
Return an array of this repository’s remote names.
-
#remote_update(remote_name, options = {}) ⇒ Object
Update the specified remote using the values in the
options
hash. - #repo_exists? ⇒ Boolean
-
#reset(ref, reset_type) ⇒ Object
Sets HEAD to the commit specified by
ref
;ref
can be a branch or tag name or a commit SHA. -
#rev_parse_target(revspec) ⇒ Object
Return the object that
revspec
points to. -
#root_ref ⇒ Object
Default branch in the repository.
- #rugged_head ⇒ Object
-
#search_files(query, ref = nil) ⇒ Object
Returns an array of BlobSnippets for files at the specified
ref
that contain thequery
string. - #sha_from_ref(ref) ⇒ Object
-
#size ⇒ Object
Return repo size in megabytes.
-
#submodules(ref) ⇒ Object
Return hash with submodules info for this repository.
-
#tag_exists?(name) ⇒ Boolean
Returns true if the given tag exists.
-
#tag_names ⇒ Object
Returns an Array of tag names.
-
#tags ⇒ Object
Returns an Array of Tags.
Methods included from Popen
Constructor Details
#initialize(path) ⇒ Repository
‘path’ must be the path to a bare git repository, e.g. /path/to/my-repo.git
33 34 35 36 |
# File 'lib/gitlab_git/repository.rb', line 33 def initialize(path) @path = path @name = path.split("/").last end |
Instance Attribute Details
#name ⇒ Object (readonly)
Directory name of repo
23 24 25 |
# File 'lib/gitlab_git/repository.rb', line 23 def name @name end |
#path ⇒ Object (readonly)
Full path to repo
20 21 22 |
# File 'lib/gitlab_git/repository.rb', line 20 def path @path end |
#rugged ⇒ Object (readonly)
Rugged repo object
26 27 28 |
# File 'lib/gitlab_git/repository.rb', line 26 def rugged @rugged end |
Instance Method Details
#add_tag(tag_name, ref_target, options = nil) ⇒ Object
Add a tag with tag_name+
name to the repository in corresponding ref_target+
supports passing a hash of options to create an annotated tag
Valid annotation options are:
:tagger ::
same structure as a committer, the user that is creating the tag
:message ::
the message to include in the tag annotation
Returns a Gitlab::Git::Tag
765 766 767 768 769 770 771 772 773 774 775 776 |
# File 'lib/gitlab_git/repository.rb', line 765 def add_tag(tag_name, ref_target, = nil) tag = rugged..create(tag_name, ref_target, ) if tag.annotated? Tag.new(tag_name, ref_target, tag.annotation.) else Tag.new(tag_name, ref_target) end rescue Rugged::TagError raise InvalidRef.new("Tag #{tag_name} already exists") rescue Rugged::ReferenceError raise InvalidRef.new("Target #{ref_target} is invalid") end |
#archive_file_path(name, storage_path, format = "tar.gz") ⇒ Object
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/gitlab_git/repository.rb', line 202 def archive_file_path(name, storage_path, format = "tar.gz") # Build file path return nil unless name extension = case format when "tar.bz2", "tbz", "tbz2", "tb2", "bz2" "tar.bz2" when "tar" "tar" when "zip" "zip" else # everything else should fall back to tar.gz "tar.gz" end file_name = "#{name}.#{extension}" File.join(storage_path, self.name, file_name) end |
#archive_metadata(ref, storage_path, format = "tar.gz") ⇒ Object
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
# File 'lib/gitlab_git/repository.rb', line 186 def (ref, storage_path, format = "tar.gz") ref ||= root_ref commit = Gitlab::Git::Commit.find(self, ref) return {} if commit.nil? project_name = self.name.chomp('.git') prefix = "#{project_name}-#{ref}-#{commit.id}" { 'RepoPath' => path, 'ArchivePrefix' => prefix, 'ArchivePath' => archive_file_path(prefix, storage_path, format), 'CommitId' => commit.id, } end |
#autocrlf ⇒ Object
872 873 874 |
# File 'lib/gitlab_git/repository.rb', line 872 def autocrlf AUTOCRLF_VALUES[rugged.config['core.autocrlf']] end |
#autocrlf=(value) ⇒ Object
876 877 878 |
# File 'lib/gitlab_git/repository.rb', line 876 def autocrlf=(value) rugged.config['core.autocrlf'] = AUTOCRLF_VALUES.invert[value] end |
#bare? ⇒ Boolean
147 148 149 |
# File 'lib/gitlab_git/repository.rb', line 147 def rugged. end |
#branch_count ⇒ Object
Returns the number of valid branches
72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/gitlab_git/repository.rb', line 72 def branch_count rugged.branches.count do |ref| begin ref.name && ref.target # ensures the branch is valid true rescue Rugged::ReferenceError false end end end |
#branch_exists?(name) ⇒ Boolean
Returns true if the given branch exists
name - The name of the branch as a String.
116 117 118 119 120 121 122 123 124 125 |
# File 'lib/gitlab_git/repository.rb', line 116 def branch_exists?(name) rugged.branches.exists?(name) # If the branch name is invalid (e.g. ".foo") Rugged will raise an error. # Whatever code calls this method shouldn't have to deal with that so # instead we just return `false` (which is true since a branch doesn't # exist when it has an invalid name). rescue Rugged::ReferenceError false end |
#branch_names ⇒ Object
Returns an Array of branch names sorted by name ASC
56 57 58 |
# File 'lib/gitlab_git/repository.rb', line 56 def branch_names branches.map(&:name) end |
#branch_names_contains(commit) ⇒ Object
Returns branch names collection that contains the special commit(SHA1 or name)
Ex.
repo.branch_names_contains('master')
463 464 465 |
# File 'lib/gitlab_git/repository.rb', line 463 def branch_names_contains(commit) branches_contains(commit).map { |c| c.name } end |
#branches ⇒ Object
Returns an Array of Branches
61 62 63 64 65 66 67 68 69 |
# File 'lib/gitlab_git/repository.rb', line 61 def branches rugged.branches.map do |rugged_ref| begin Branch.new(rugged_ref.name, rugged_ref.target) rescue Rugged::ReferenceError # Omit invalid branch end end.compact.sort_by(&:name) end |
#branches_contains(commit) ⇒ Object
Returns branch collection that contains the special commit(SHA1 or name)
Ex.
repo.branch_names_contains('master')
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 |
# File 'lib/gitlab_git/repository.rb', line 472 def branches_contains(commit) commit_obj = rugged.rev_parse(commit) parent = commit_obj.parents.first unless commit_obj.parents.empty? walker = Rugged::Walker.new(rugged) rugged.branches.select do |branch| walker.push(branch.target_id) walker.hide(parent) if parent result = walker.any? { |c| c.oid == commit_obj.oid } walker.reset result end end |
#checkout(ref, options = {}, start_point = "HEAD") ⇒ Object
Check out the specified ref. Valid options are:
:b - Create a new branch at +start_point+ and set HEAD to the new
branch.
* These options are passed to the Rugged::Repository#checkout method:
:progress ::
A callback that will be executed for checkout progress notifications.
Up to 3 parameters are passed on each execution:
- The path to the last updated file (or +nil+ on the very first
invocation).
- The number of completed checkout steps.
- The number of total checkout steps to be performed.
:notify ::
A callback that will be executed for each checkout notification
types specified with +:notify_flags+. Up to 5 parameters are passed
on each execution:
- An array containing the +:notify_flags+ that caused the callback
execution.
- The path of the current file.
- A hash describing the baseline blob (or +nil+ if it does not
exist).
- A hash describing the target blob (or +nil+ if it does not exist).
- A hash describing the workdir blob (or +nil+ if it does not
exist).
:strategy ::
A single symbol or an array of symbols representing the strategies
to use when performing the checkout. Possible values are:
:none ::
Perform a dry run (default).
:safe ::
Allow safe updates that cannot overwrite uncommitted data.
:safe_create ::
Allow safe updates plus creation of missing files.
:force ::
Allow all updates to force working directory to look like index.
:allow_conflicts ::
Allow checkout to make safe updates even if conflicts are found.
:remove_untracked ::
Remove untracked files not in index (that are not ignored).
:remove_ignored ::
Remove ignored files not in index.
:update_only ::
Only update existing files, don't create new ones.
:dont_update_index ::
Normally checkout updates index entries as it goes; this stops
that.
:no_refresh ::
Don't refresh index/config/etc before doing checkout.
:disable_pathspec_match ::
Treat pathspec as simple list of exact match file paths.
:skip_locked_directories ::
Ignore directories in use, they will be left empty.
:skip_unmerged ::
Allow checkout to skip unmerged files (NOT IMPLEMENTED).
:use_ours ::
For unmerged files, checkout stage 2 from index (NOT IMPLEMENTED).
:use_theirs ::
For unmerged files, checkout stage 3 from index (NOT IMPLEMENTED).
:update_submodules ::
Recursively checkout submodules with same options (NOT
IMPLEMENTED).
:update_submodules_if_changed ::
Recursively checkout submodules if HEAD moved in super repo (NOT
IMPLEMENTED).
:disable_filters ::
If +true+, filters like CRLF line conversion will be disabled.
:dir_mode ::
Mode for newly created directories. Default: +0755+.
:file_mode ::
Mode for newly created files. Default: +0755+ or +0644+.
:file_open_flags ::
Mode for opening files. Default:
<code>IO::CREAT | IO::TRUNC | IO::WRONLY</code>.
:notify_flags ::
A single symbol or an array of symbols representing the cases in
which the +:notify+ callback should be invoked. Possible values are:
:none ::
Do not invoke the +:notify+ callback (default).
:conflict ::
Invoke the callback for conflicting paths.
:dirty ::
Invoke the callback for "dirty" files, i.e. those that do not need
an update but no longer match the baseline.
:updated ::
Invoke the callback for any file that was changed.
:untracked ::
Invoke the callback for untracked files.
:ignored ::
Invoke the callback for ignored files.
:all ::
Invoke the callback for all these cases.
:paths ::
A glob string or an array of glob strings specifying which paths
should be taken into account for the checkout operation. +nil+ will
match all files. Default: +nil+.
:baseline ::
A Rugged::Tree that represents the current, expected contents of the
workdir. Default: +HEAD+.
:target_directory ::
A path to an alternative workdir directory in which the checkout
should be performed.
727 728 729 730 731 732 733 734 |
# File 'lib/gitlab_git/repository.rb', line 727 def checkout(ref, = {}, start_point = "HEAD") if [:b] rugged.branches.create(ref, start_point) .delete(:b) end = { strategy: [:recreate_missing, :safe] } rugged.checkout(ref, .merge()) end |
#clean(options = {}) ⇒ Object
Mimic the ‘git clean` command and recursively delete untracked files. Valid keys that can be passed in the options
hash are:
:d - Remove untracked directories :f - Remove untracked directories that are managed by a different
repository
:x - Remove ignored files
The value in options
must evaluate to true for an option to take effect.
Examples:
repo.clean(d: true, f: true) # Enable the -d and -f options
repo.clean(d: false, x: true) # -x is enabled, -d is not
580 581 582 583 584 585 586 |
# File 'lib/gitlab_git/repository.rb', line 580 def clean( = {}) strategies = [:remove_untracked] strategies.push(:force) if [:f] strategies.push(:remove_ignored) if [:x] # TODO: implement this method end |
#commit_count(ref) ⇒ Object
Return total commits count accessible from passed ref
540 541 542 543 544 545 546 |
# File 'lib/gitlab_git/repository.rb', line 540 def commit_count(ref) walker = Rugged::Walker.new(rugged) walker.sorting(Rugged::SORT_TOPO | Rugged::SORT_REVERSE) oid = rugged.rev_parse_oid(ref) walker.push(oid) walker.count end |
#commits_between(from, to) ⇒ Object
Return a collection of Rugged::Commits between the two revspec arguments. See git-scm.com/docs/git-rev-parse.html#_specifying_revisions for a detailed list of valid arguments.
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
# File 'lib/gitlab_git/repository.rb', line 347 def commits_between(from, to) walker = Rugged::Walker.new(rugged) walker.sorting(Rugged::SORT_DATE | Rugged::SORT_REVERSE) sha_from = sha_from_ref(from) sha_to = sha_from_ref(to) walker.push(sha_to) walker.hide(sha_from) commits = walker.to_a walker.reset commits end |
#commits_since(from_date) ⇒ Object
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 |
# File 'lib/gitlab_git/repository.rb', line 849 def commits_since(from_date) walker = Rugged::Walker.new(rugged) walker.sorting(Rugged::SORT_DATE | Rugged::SORT_REVERSE) rugged.references.each("refs/heads/*") do |ref| walker.push(ref.target_id) end commits = [] walker.each do |commit| break if commit.[:time].to_date < from_date commits.push(commit) end commits end |
#copy_gitattributes(ref) ⇒ Object
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 |
# File 'lib/gitlab_git/repository.rb', line 958 def copy_gitattributes(ref) begin commit = lookup(ref) rescue Rugged::ReferenceError raise InvalidRef.new("Ref #{ref} is invalid") end # Create the paths info_dir_path = File.join(path, 'info') info_attributes_path = File.join(info_dir_path, 'attributes') begin # Retrieve the contents of the blob gitattributes_content = blob_content(commit, '.gitattributes') rescue InvalidBlobName # No .gitattributes found. Should now remove any info/attributes and return File.delete(info_attributes_path) if File.exists?(info_attributes_path) return end # Create the info directory if needed Dir.mkdir(info_dir_path) unless File.directory?(info_dir_path) # Write the contents of the .gitattributes file to info/attributes File.write(info_attributes_path, gitattributes_content) end |
#count_commits_between(from, to) ⇒ Object
Counts the amount of commits between ‘from` and `to`.
364 365 366 |
# File 'lib/gitlab_git/repository.rb', line 364 def count_commits_between(from, to) commits_between(from, to).size end |
#create_branch(ref, start_point = "HEAD") ⇒ Object
Create a new branch named **ref+ based on **stat_point+, HEAD by default
Examples:
create_branch("feature")
create_branch("other-feature", "master")
746 747 748 749 750 751 752 |
# File 'lib/gitlab_git/repository.rb', line 746 def create_branch(ref, start_point = "HEAD") rugged_ref = rugged.branches.create(ref, start_point) Branch.new(rugged_ref.name, rugged_ref.target) rescue Rugged::ReferenceError => e raise InvalidRef.new("Branch #{ref} already exists") if e.to_s =~ /'refs\/heads\/#{ref}'/ raise InvalidRef.new("Invalid reference #{start_point}") end |
#delete_branch(branch_name) ⇒ Object
Delete the specified branch from the repository
737 738 739 |
# File 'lib/gitlab_git/repository.rb', line 737 def delete_branch(branch_name) rugged.branches.delete(branch_name) end |
#diff(from, to, options = {}, *paths) ⇒ Object
Return an array of Diff objects that represent the diff between from
and to
. See Diff::filter_diff_options for the allowed diff options. The options
hash can also include :break_rewrites to split larger rewrites into delete/add pairs.
377 378 379 |
# File 'lib/gitlab_git/repository.rb', line 377 def diff(from, to, = {}, *paths) DiffCollection.new(diff_patches(from, to, , *paths), ) end |
#diff_text(from, to, options = {}, *paths) ⇒ Object
Return the diff between from
and to
in a single patch string. The options
hash has the same allowed keys as #diff.
383 384 385 386 387 388 389 390 |
# File 'lib/gitlab_git/repository.rb', line 383 def diff_text(from, to, = {}, *paths) # NOTE: It would be simpler to use the Rugged::Diff#patch method, but # that formats the diff text differently than Rugged::Patch#to_s for # changes to binary files. diff_patches(from, to, , *paths).map do |p| p.to_s end.join("\n") end |
#diffable?(blob) ⇒ Boolean
Checks if the blob should be diffable according to its attributes
986 987 988 989 |
# File 'lib/gitlab_git/repository.rb', line 986 def diffable?(blob) blob_attributes = attributes(blob.path).to_h blob_attributes.fetch('diff', blob.text?) end |
#discover_default_branch ⇒ Object
Discovers the default branch based on the repository’s available branches
-
If no branches are present, returns nil
-
If one branch is present, returns its name
-
If two or more branches are present, returns current HEAD or master or first branch
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
# File 'lib/gitlab_git/repository.rb', line 160 def discover_default_branch names = branch_names return if names.empty? return names[0] if names.length == 1 if rugged_head extracted_name = Ref.extract_branch_name(rugged_head.name) return extracted_name if names.include?(extracted_name) end if names.include?('master') 'master' else names[0] end end |
#empty? ⇒ Boolean
143 144 145 |
# File 'lib/gitlab_git/repository.rb', line 143 def empty? rugged.empty? end |
#fetch(remote_name) ⇒ Object
Fetch the specified remote
803 804 805 |
# File 'lib/gitlab_git/repository.rb', line 803 def fetch(remote_name) rugged.remotes[remote_name].fetch end |
#find_commits(options = {}) ⇒ Object
Returns commits collection
Ex.
repo.find_commits(
ref: 'master',
max_count: 10,
skip: 5,
order: :date
)
+options+ is a Hash of optional arguments to git
:ref is the ref from which to begin (SHA1 or name)
:contains is the commit contained by the refs from which to begin (SHA1 or name)
:max_count is the maximum number of commits to fetch
:skip is the number of commits to skip
:order is the commits order and allowed value is :date(default) or :topo
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
# File 'lib/gitlab_git/repository.rb', line 409 def find_commits( = {}) = .dup = [:ref, :max_count, :skip, :contains, :order] .keep_if do |key| .include?(key) end = { skip: 0 } = .merge() walker = Rugged::Walker.new(rugged) if [:ref] walker.push(rugged.rev_parse_oid([:ref])) elsif [:contains] branches_contains([:contains]).each do |branch| walker.push(branch.target_id) end else rugged.references.each("refs/heads/*") do |ref| walker.push(ref.target_id) end end if [:order] == :topo walker.sorting(Rugged::SORT_TOPO) else walker.sorting(Rugged::SORT_DATE) end commits = [] offset = [:skip] limit = [:max_count] walker.each(offset: offset, limit: limit) do |commit| gitlab_commit = Gitlab::Git::Commit.decorate(commit) commits.push(gitlab_commit) end walker.reset commits rescue Rugged::OdbError [] end |
#format_patch(from, to, options = {}) ⇒ Object
Return a String containing the mbox-formatted diff between from
and to
. See #diff for the allowed keys in the options
hash.
814 815 816 817 818 819 820 821 822 823 824 825 826 |
# File 'lib/gitlab_git/repository.rb', line 814 def format_patch(from, to, = {}) ||= {} break_rewrites = [:break_rewrites] = Diff.() from_sha = rugged.rev_parse_oid(from) to_sha = rugged.rev_parse_oid(to) commits_between(from_sha, to_sha).map do |commit| # Ignore merge commits, which have more than one parent, # in creation of patch to mimic the behavior of `git format-patch` commit.to_mbox() if commit.parents.length <= 1 end.flatten.join("\n") end |
#has_commits? ⇒ Boolean
139 140 141 |
# File 'lib/gitlab_git/repository.rb', line 139 def has_commits? !empty? end |
#heads ⇒ Object
Deprecated. Will be removed in 5.2
133 134 135 136 137 |
# File 'lib/gitlab_git/repository.rb', line 133 def heads rugged.references.each("refs/heads/*").map do |head| Gitlab::Git::Ref.new(head.name, head.target) end.sort_by(&:name) end |
#log(options) ⇒ Object
Use the Rugged Walker API to build an array of commits.
Usage.
repo.log(
ref: 'master',
path: 'app/models',
limit: 10,
offset: 5,
after: Time.new(2016, 4, 21, 14, 32, 10)
)
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
# File 'lib/gitlab_git/repository.rb', line 262 def log() = { limit: 10, offset: 0, path: nil, ref: root_ref, follow: false, skip_merges: false, disable_walk: false, after: nil, before: nil } = .merge() [:limit] ||= 0 [:offset] ||= 0 actual_ref = [:ref] || root_ref begin sha = sha_from_ref(actual_ref) rescue Rugged::OdbError, Rugged::InvalidError, Rugged::ReferenceError # Return an empty array if the ref wasn't found return [] end if log_using_shell?() log_by_shell(sha, ) else log_by_walk(sha, ) end end |
#log_by_shell(sha, options) ⇒ Object
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 |
# File 'lib/gitlab_git/repository.rb', line 311 def log_by_shell(sha, ) cmd = %W(git --git-dir=#{path} log) cmd += %W(-n #{[:limit].to_i}) cmd += %W(--format=%H) cmd += %W(--skip=#{[:offset].to_i}) cmd += %W(--follow) if [:follow] cmd += %W(--no-merges) if [:skip_merges] cmd += %W(--after=#{[:after].iso8601}) if [:after] cmd += %W(--before=#{[:before].iso8601}) if [:before] cmd += [sha] cmd += %W(-- #{[:path]}) if [:path].present? raw_output = IO.popen(cmd) {|io| io.read } log = raw_output.lines.map do |c| Rugged::Commit.new(rugged, c.strip) end log.is_a?(Array) ? log : [] end |
#log_by_walk(sha, options) ⇒ Object
301 302 303 304 305 306 307 308 309 |
# File 'lib/gitlab_git/repository.rb', line 301 def log_by_walk(sha, ) = { show: sha, sort: Rugged::SORT_DATE, limit: [:limit], offset: [:offset] } Rugged::Walker.walk(rugged, ).to_a end |
#log_using_shell?(options) ⇒ Boolean
293 294 295 296 297 298 299 |
# File 'lib/gitlab_git/repository.rb', line 293 def log_using_shell?() [:path].present? || [:disable_walk] || [:skip_merges] || [:after] || [:before] end |
#lookup(oid_or_ref_name) ⇒ Object
Lookup for rugged object by oid or ref name
508 509 510 |
# File 'lib/gitlab_git/repository.rb', line 508 def lookup(oid_or_ref_name) rugged.rev_parse(oid_or_ref_name) end |
#ls_files(ref) ⇒ Object
Returns result like “git ls-files” , recursive and full file path
Ex.
repo.ls_files('master')
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 |
# File 'lib/gitlab_git/repository.rb', line 932 def ls_files(ref) actual_ref = ref || root_ref begin sha_from_ref(actual_ref) rescue Rugged::OdbError, Rugged::InvalidError, Rugged::ReferenceError # Return an empty array if the ref wasn't found return [] end cmd = %W(git --git-dir=#{path} ls-tree) cmd += %w(-r) cmd += %w(--full-tree) cmd += %w(--full-name) cmd += %W(-- #{actual_ref}) raw_output = IO.popen(cmd, &:read).split("\n").map do |f| stuff, path = f.split("\t") mode, type, sha = stuff.split(" ") path if type == "blob" # Contain only blob type end raw_output.compact end |
#merge(source_name, target_name, options = {}) ⇒ Object
Merge the source_name
branch into the target_name
branch. This is equivalent to ‘git merge –no_ff source_name
`, since a merge commit is always created.
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 |
# File 'lib/gitlab_git/repository.rb', line 831 def merge(source_name, target_name, = {}) our_commit = rugged.branches[target_name].target their_commit = rugged.branches[source_name].target raise "Invalid merge target" if our_commit.nil? raise "Invalid merge source" if their_commit.nil? merge_index = rugged.merge_commits(our_commit, their_commit) return false if merge_index.conflicts? = .merge( parents: [our_commit, their_commit], tree: merge_index.write_tree(rugged), update_ref: "refs/heads/#{target_name}" ) Rugged::Commit.create(rugged, ) end |
#merge_base_commit(from, to) ⇒ Object
Returns the SHA of the most recent common ancestor of from
and to
369 370 371 |
# File 'lib/gitlab_git/repository.rb', line 369 def merge_base_commit(from, to) rugged.merge_base(from, to) end |
#mkdir(path, options = {}) ⇒ Object
Create a new directory with a .gitkeep file. Creates all required nested directories (i.e. mkdir -p behavior)
options should contain next structure:
author: {
email: '[email protected]',
name: 'Test User',
time: Time.now
},
committer: {
email: '[email protected]',
name: 'Test User',
time: Time.now
},
commit: {
message: 'Wow such commit',
branch: 'master'
}
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 |
# File 'lib/gitlab_git/repository.rb', line 898 def mkdir(path, = {}) # Check if this directory exists; if it does, then don't bother # adding .gitkeep file. ref = [:commit][:branch] path = PathHelper.normalize_path(path).to_s rugged_ref = rugged.ref(ref) raise InvalidRef.new("Invalid ref") if rugged_ref.nil? target_commit = rugged_ref.target raise InvalidRef.new("Invalid target commit") if target_commit.nil? entry = tree_entry(target_commit, path) if entry if entry[:type] == :blob raise InvalidBlobName.new("Directory already exists as a file") else raise InvalidBlobName.new("Directory already exists") end end [:file] = { content: '', path: "#{path}/.gitkeep", update: true } Blob.commit(self, ) end |
#push(remote_name, *refspecs) ⇒ Object
Push *refspecs to the remote identified by remote_name
.
808 809 810 |
# File 'lib/gitlab_git/repository.rb', line 808 def push(remote_name, *refspecs) rugged.remotes[remote_name].push(refspecs) end |
#raw ⇒ Object
Alias to old method for compatibility
44 45 46 |
# File 'lib/gitlab_git/repository.rb', line 44 def raw rugged end |
#ref_names ⇒ Object
Returns an Array of branch and tag names
128 129 130 |
# File 'lib/gitlab_git/repository.rb', line 128 def ref_names branch_names + tag_names end |
#refs_hash ⇒ Object
Get refs hash which key is SHA1 and value is a Rugged::Reference
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 |
# File 'lib/gitlab_git/repository.rb', line 490 def refs_hash # Initialize only when first call if @refs_hash.nil? @refs_hash = Hash.new { |h, k| h[k] = [] } rugged.references.each do |r| # Symbolic/remote references may not have an OID; skip over them target_oid = r.target.try(:oid) if target_oid sha = rev_parse_target(target_oid).oid @refs_hash[sha] << r end end end @refs_hash end |
#remote_add(remote_name, url) ⇒ Object
Add a new remote to this repository. Returns a Rugged::Remote object
789 790 791 |
# File 'lib/gitlab_git/repository.rb', line 789 def remote_add(remote_name, url) rugged.remotes.create(remote_name, url) end |
#remote_delete(remote_name) ⇒ Object
Delete the specified remote from this repository.
784 785 786 |
# File 'lib/gitlab_git/repository.rb', line 784 def remote_delete(remote_name) rugged.remotes.delete(remote_name) end |
#remote_names ⇒ Object
Return an array of this repository’s remote names
779 780 781 |
# File 'lib/gitlab_git/repository.rb', line 779 def remote_names rugged.remotes.each_name.to_a end |
#remote_update(remote_name, options = {}) ⇒ Object
Update the specified remote using the values in the options
hash
Example repo.update_remote(“origin”, url: “path/to/repo”)
797 798 799 800 |
# File 'lib/gitlab_git/repository.rb', line 797 def remote_update(remote_name, = {}) # TODO: Implement other remote options rugged.remotes.set_url(remote_name, [:url]) if [:url] end |
#repo_exists? ⇒ Boolean
151 152 153 |
# File 'lib/gitlab_git/repository.rb', line 151 def repo_exists? !!rugged end |
#reset(ref, reset_type) ⇒ Object
Sets HEAD to the commit specified by ref
; ref
can be a branch or tag name or a commit SHA. Valid reset_type
values are:
[:soft]
the head will be moved to the commit.
[:mixed]
will trigger a +:soft+ reset, plus the index will be replaced
with the content of the commit tree.
[:hard]
will trigger a +:mixed+ reset and the working directory will be
replaced with the content of the index. (Untracked and ignored files
will be left alone)
560 561 562 |
# File 'lib/gitlab_git/repository.rb', line 560 def reset(ref, reset_type) rugged.reset(ref, reset_type) end |
#rev_parse_target(revspec) ⇒ Object
Return the object that revspec
points to. If revspec
is an annotated tag, then return the tag’s target instead.
338 339 340 341 342 |
# File 'lib/gitlab_git/repository.rb', line 338 def rev_parse_target(revspec) obj = rugged.rev_parse(revspec) obj = obj.target while obj.is_a?(Rugged::Tag::Annotation) obj end |
#root_ref ⇒ Object
Default branch in the repository
39 40 41 |
# File 'lib/gitlab_git/repository.rb', line 39 def root_ref @root_ref ||= discover_default_branch end |
#rugged_head ⇒ Object
180 181 182 183 184 |
# File 'lib/gitlab_git/repository.rb', line 180 def rugged_head rugged.head rescue Rugged::ReferenceError nil end |
#search_files(query, ref = nil) ⇒ Object
Returns an array of BlobSnippets for files at the specified ref
that contain the query
string.
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
# File 'lib/gitlab_git/repository.rb', line 231 def search_files(query, ref = nil) greps = [] ref ||= root_ref populated_index(ref).each do |entry| # Discard submodules next if submodule?(entry) blob = Blob.raw(self, entry[:oid]) # Skip binary files next if blob.data.encoding == Encoding::ASCII_8BIT blob.load_all_data!(self) greps += build_greps(blob.data, query, ref, entry[:path]) end greps end |
#sha_from_ref(ref) ⇒ Object
332 333 334 |
# File 'lib/gitlab_git/repository.rb', line 332 def sha_from_ref(ref) rev_parse_target(ref).oid end |
#size ⇒ Object
Return repo size in megabytes
224 225 226 227 |
# File 'lib/gitlab_git/repository.rb', line 224 def size size = popen(%W(du -sk), path).first.strip.to_i (size.to_f / 1024).round(2) end |
#submodules(ref) ⇒ Object
Return hash with submodules info for this repository
Ex.
{
"rack" => {
"id" => "c67be4624545b4263184c4a0e8f887efd0a66320",
"path" => "rack",
"url" => "git://github.com/chneukirchen/rack.git"
},
"encoding" => {
"id" => ....
}
}
526 527 528 529 530 531 532 533 534 535 536 537 |
# File 'lib/gitlab_git/repository.rb', line 526 def submodules(ref) commit = rev_parse_target(ref) return {} unless commit begin content = blob_content(commit, ".gitmodules") rescue InvalidBlobName return {} end parse_gitmodules(commit, content) end |
#tag_exists?(name) ⇒ Boolean
Returns true if the given tag exists
name - The name of the tag as a String.
109 110 111 |
# File 'lib/gitlab_git/repository.rb', line 109 def tag_exists?(name) !!rugged.[name] end |
#tag_names ⇒ Object
Returns an Array of tag names
85 86 87 |
# File 'lib/gitlab_git/repository.rb', line 85 def tag_names rugged..map { |t| t.name } end |
#tags ⇒ Object
Returns an Array of Tags
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/gitlab_git/repository.rb', line 90 def rugged.references.each("refs/tags/*").map do |ref| = nil if ref.target.is_a?(Rugged::Tag::Annotation) = ref.target. if .respond_to?(:chomp) = .chomp end end Tag.new(ref.name, ref.target, ) end.sort_by(&:name) end |