2019-07-25 01:27:42 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-10-23 16:12:11 -04:00
|
|
|
require 'zlib'
|
|
|
|
|
|
|
|
class BareRepoOperations
|
|
|
|
include Gitlab::Popen
|
|
|
|
|
|
|
|
def initialize(path_to_repo)
|
|
|
|
@path_to_repo = path_to_repo
|
|
|
|
end
|
|
|
|
|
2018-04-11 23:05:07 -04:00
|
|
|
def commit_tree(tree_id, msg, parent: Gitlab::Git::EMPTY_TREE_ID)
|
2018-02-06 17:49:33 -05:00
|
|
|
commit_tree_args = ['commit-tree', tree_id, '-m', msg]
|
2018-04-11 23:05:07 -04:00
|
|
|
commit_tree_args += ['-p', parent] unless parent == Gitlab::Git::EMPTY_TREE_ID
|
2018-02-06 17:49:33 -05:00
|
|
|
commit_id = execute(commit_tree_args)
|
|
|
|
|
|
|
|
commit_id[0]
|
|
|
|
end
|
|
|
|
|
2017-10-23 16:12:11 -04:00
|
|
|
# Based on https://stackoverflow.com/a/25556917/1856239
|
|
|
|
def commit_file(file, dst_path, branch = 'master')
|
2018-04-11 23:05:07 -04:00
|
|
|
head_id = execute(['show', '--format=format:%H', '--no-patch', branch], allow_failure: true)[0] || Gitlab::Git::EMPTY_TREE_ID
|
2017-10-23 16:12:11 -04:00
|
|
|
|
|
|
|
execute(['read-tree', '--empty'])
|
|
|
|
execute(['read-tree', head_id])
|
|
|
|
|
|
|
|
blob_id = execute(['hash-object', '--stdin', '-w']) do |stdin|
|
|
|
|
stdin.write(file.read)
|
|
|
|
end
|
|
|
|
|
|
|
|
execute(['update-index', '--add', '--cacheinfo', '100644', blob_id[0], dst_path])
|
|
|
|
|
|
|
|
tree_id = execute(['write-tree'])
|
|
|
|
|
2018-02-06 17:49:33 -05:00
|
|
|
commit_id = commit_tree(tree_id[0], "Add #{dst_path}", parent: head_id)
|
2017-10-23 16:12:11 -04:00
|
|
|
|
2018-02-06 17:49:33 -05:00
|
|
|
execute(['update-ref', "refs/heads/#{branch}", commit_id])
|
2017-10-23 16:12:11 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def execute(args, allow_failure: false)
|
|
|
|
output, status = popen(base_args + args, nil) do |stdin|
|
|
|
|
yield stdin if block_given?
|
|
|
|
end
|
|
|
|
|
2020-08-04 14:09:49 -04:00
|
|
|
unless status == 0
|
2017-10-23 16:12:11 -04:00
|
|
|
if allow_failure
|
|
|
|
return []
|
|
|
|
else
|
|
|
|
raise "Got a non-zero exit code while calling out `#{args.join(' ')}`: #{output}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
output.split("\n")
|
|
|
|
end
|
|
|
|
|
|
|
|
def base_args
|
|
|
|
[
|
|
|
|
Gitlab.config.git.bin_path,
|
|
|
|
"--git-dir=#{@path_to_repo}"
|
|
|
|
]
|
|
|
|
end
|
|
|
|
end
|