git 如何使用rugged添加和提交存储库中的所有文件

hs1ihplo  于 2023-03-16  发布在  Git
关注(0)|答案(1)|浏览(130)

我正在初始化一个已经包含一些文件的git仓库

repo = Rugged::Repository.init_at(".")

我需要暂存该文件夹中的文件并提交它们。这是我尝试过的:

repo = Rugged::Repository.new(".")
    index = repo.index
    index.add_all()

    options = {}
    options[:tree] = index.write_tree(repo)

    options[:author] = { :email => "testuser@github.com", :name => 'Test Author', :time => Time.now }
    options[:committer] = { :email => "testuser@github.com", :name => 'Test Author', :time => Time.now }
    options[:message] ||= "Making a commit via Rugged!"
    options[:parents] = repo.empty? ? [] : [ repo.head.target ].compact
    options[:update_ref] = 'HEAD'
    Rugged::Commit.create(repo, options)

但是,如果我查看目录并运行git status,我得到的是:

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    .editorconfig
    deleted:    .gitignore
    deleted:    Procfile
    deleted:    README.md

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .editorconfig
    .gitignore
    Procfile
    README.md
r6hnlfcb

r6hnlfcb1#

这个解决方案将原始代码更新为当前的Rubocop标准,添加了一种通过编程创建一些文件的方法,并包含了@DeepParekh提供的建议。

require 'rugged'
require 'tmpdir'

def write(file_name_content)
  file_name_content.each do |item|
    item.each do |name, content|
      File.write name, content
    end
  end
end

def write_files
  write [
    'file1.html' => <<~END_INDEX
      <p>
        Line 1 in file1.html.
      </p>
    END_INDEX
  ]
  write [
    'file2.html' => <<~END_INDEX
      <p>
        Line 1 in file2.html.
        Line 2.
      </p>
    END_INDEX
  ]
end

Dir.mktmpdir do |temp_dir| # This directory will be deleted on exit
  Dir.chdir(temp_dir)
  puts "Working in #{temp_dir}"

  write_files

  repo = Rugged::Repository.init_at temp_dir
  index = repo.index
  index.add_all
  index.write

  options = {}
  options[:tree] = index.write_tree(repo)

  now = Time.now
  options[:author] = { email: "testuser@github.com", name: 'Test Author', time: now }
  options[:committer] = { email: "testuser@github.com", name: 'Test Author', time: now }
  options[:message] ||= "Making a commit via Rugged"
  options[:parents] = repo.empty? ? [] : [repo.head.target].compact
  options[:update_ref] = 'HEAD'
  new_commit = Rugged::Commit.create(repo, options)
  puts "Commit #{new_commit[-8..]} created.\n\n"

  puts `git status`

  files = Dir["*"]
  if files.reject { |x| x == '.git' }.empty?
    puts "No physical files were created."
  else
    puts "Physical files are:\n  #{files.join("\n  ")}"
  end
end

输出为:

Working in /tmp/d20230311-236770-h93tav
Commit 9fa0a9be created.

On branch master
nothing to commit, working tree clean
Physical files are:
  file1.html
  file2.html

相关问题