Question

I am trying to create a file in a certain branch on github via the API, but don't find a way to set the branch successfully for either getting or creating the file. Here is my method:

   def self.save_file_to_github access_token, github_user, github_repo, path, content, branch

     sha = nil
     url = "https://api.github.com/repos/#{github_user}/#{github_repo}/contents/#{path}"
     RestClient.get(url,{ params:{access_token:access_token,branch:branch},accept:'json'}){ |response, request, result| 
         if response.code==200 
           sha=JSON.parse(response)['sha']
         end
     }

     RestClient.put(url, { message: "my message", content: Base64.strict_encode64(content), sha: sha }.to_json,{ params:{access_token:access_token},accept:'json'}){ |response, request, result| 
        puts response.code
        puts response
     }

   end 

It first checks if the file is there, gets the sha1 key. Then its put the new file. This all works fine, I just can't find a way to specify the branch when getting the file and putting it again. How can I specify the branch?

Was it helpful?

Solution

The action you're using in the Repo API to retrieve the file if it's there takes a parameter ref which defaults to the master branch. Replace this with the branch you need.

For creating the file, the parameter in the API is called branch and again defaults to master. Set this to your required branch and you should be good to go. Something like this:

def self.save_file_to_github access_token, github_user, github_repo, path, content, branch

  sha = nil
  url = "https://api.github.com/repos/#{github_user}/#{github_repo}/contents/#{path}"
  RestClient.get(url,{ params:{access_token:access_token, ref: branch},accept:'json'}){ |response, request, result| 
    if response.code==200 
      sha=JSON.parse(response)['sha']
    end
  }

  RestClient.put(url, { message: "my message", content: Base64.strict_encode64(content), branch: branch, sha: sha }.to_json,{ params:{access_token:access_token},accept:'json'}){ |response, request, result| 
    puts response.code
    puts response
  }

end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top