0

I am logged in using Octokit::Client.new and want to create a file inside one of my repos. Please tell me which method/function does this.

I tried searching a lot but cannot find a good reference for octokit; developer.github.com describes only HTTP GET. If possible also provide a good source for documentation.

Thank you!

Abhishek Kumar
  • 298
  • 4
  • 10
  • I'm pretty sure you want to start with [create_commit](http://octokit.github.io/octokit.rb/Octokit/Client/Commits.html#create_commit-instance_method). – Sergio Tulentsev Nov 20 '16 at 08:15
  • @SergioTulentsev I am writing a program which needs to create a file inside the user's repo. Is there a method which given the repo, path, etc. creates the file. P.S.: I could not figure out how to create a file using commits. – Abhishek Kumar Nov 20 '16 at 08:20
  • "is there a method which creates a file" - Well, this is git. There are no files, no directories, there are only commits. – Sergio Tulentsev Nov 20 '16 at 08:55
  • @SergioTulentsev So how do I create a file using a commit? – Abhishek Kumar Nov 20 '16 at 08:56
  • Try this one: https://developer.github.com/v3/repos/contents/#create-a-file, octokit version: http://octokit.github.io/octokit.rb/Octokit/Client/Contents.html#create_contents-instance_method – Sergio Tulentsev Nov 20 '16 at 09:00
  • How do I use that method? I mean on what object it would be called a how do I create that object. There is zero documentation about these topics. Could you please give me a code example. – Abhishek Kumar Nov 20 '16 at 09:56
  • Huh? there's a code example in the docs I linked – Sergio Tulentsev Nov 20 '16 at 10:03

1 Answers1

0

An amazing tutorial from Matt Greensmith with an answer for this appeared on his blog that I totally recommend checking out.

require 'octokit'
#github = Octokit::Client.new(:login => "me", :password => "sekret")

# set up some vars:
repo = 'me/myrepo'
ref = 'heads/master'

sha_latest_commit = github.ref(repo, ref).object.sha
sha_base_tree = github.commit(repo, sha_latest_commit).commit.tree.sha
file_name = File.join("some_dir", "new_file.txt")
blob_sha = github.create_blob(repo, Base64.encode64(my_content), "base64")
sha_new_tree = github.create_tree(repo, 
                                   [ { :path => file_name, 
                                       :mode => "100644", 
                                       :type => "blob", 
                                       :sha => blob_sha } ], 
                                   {:base_tree => sha_base_tree }).sha
commit_message = "Committed via Octokit!"
sha_new_commit = github.create_commit(repo, commit_message, sha_new_tree, sha_latest_commit).sha
updated_ref = github.update_ref(repo, ref, sha_new_commit)
puts updated_ref
Seb Wilgosz
  • 1,240
  • 15
  • 24