When I try to use the git
gem to push, I get this error: src refspec master does not match any
. My repo uses main
instead of master
; but (assuming that is the problem), I don't see how to change the upstream branch.
Details:
I am writing a Ruby script that modifies a set of existing, already cloned repositories and pushes the changes. I'm using the git
gem (https://github.com/ruby-git/ruby-git)
Here is the minimal example:
git_dir = '.'
begin
$stderr.puts "Opening with git_dir: #{git_dir}"
g = Git.open("#{git_dir}", :raise => true)
g.config('remote.remote-name.push', 'refs/heads/main:refs/heads/main')
$stderr.puts "Current branch: #{g.current_branch}"
if g.status.changed.any?
g.add
g.commit('Updated grade report')
g.push(branch: g.current_branch)
else
$stderr.puts "No changes"
end
rescue Git::GitExecuteError => e
puts "Problem updating repo"
puts "error: #{e.message}"
end
I run this program after modifying a file in an existing, previously cloned git repo. When I do, it fails with this error:
Problem updating repo
error: git '--git-dir=testGitRepo' '-c' 'core.quotePath=true' '-c' 'color.ui=false' push '{:branch=>"main"}' 'master' 2>&1:error: src refspec master does not match any
error: failed to push some refs to '{:branch=>"main"}'
I suspect the important part of this error message is push '{:branch=>"main"}' 'master'
The fact that master
still appears suggests that I need to do something else to tell the push
command that I want to push the local main
to origin main
; but, I don't see how to do that.
The docs for push
say this:
pushes changes to a remote repository - easiest if this is a cloned repository, otherwise you may have to run something like this first to setup the push parameters:
@git.config('remote.remote-name.push', 'refs/heads/master:refs/heads/master')
But I don't see how to call config
in a way that sets the upstream branch to main. (I tried g.config('remote.remote-name.push', 'refs/heads/main:refs/heads/main')
and it appeared to have no effect. Of course, I don't fully understand what this command is supposed to do.)
CodePudding user response:
push
takes the remote and branch names as separate arguments:
#push(remote = 'origin', branch = 'master', opts = {})
https://rubydoc.info/gems/git/Git/Base#push-instance_method
Using the following should work:
g.push('origin', 'main')