【问题标题】:basic ruby script not working as expected基本的 ruby​​ 脚本没有按预期工作
【发布时间】:2012-02-06 11:14:29
【问题描述】:

我正在尝试编写一个简单的 ruby​​ 脚本来更新我的 GIT 工作目录。脚本产生错误,我不知道为什么。我有以下功能(我知道可以更简单地编写,但我尝试的任何方法似乎都不起作用)

def performCommandInDir(command, dir)
  old_dir = Dir.pwd
  Dir.chdir(dir)
  system(command)
  Dir.chdir(old_dir)
end

我这样称呼它

performCommandInDir("git svn rebase", repo[:name])

当我运行脚本时,我看到以下错误:

fatal: /usr/libexec/git-core/git-rebase cannot be used without a working tree.
rebase refs/remotes/git-svn: command returned error: 1

我已验证 repo[:name] 是我的 GIT 存储库的正确路径。我可以手动将其值粘贴到 shell 中,并且 git 命令可以正常工作。

这里会发生什么?

感谢您的帮助

【问题讨论】:

标签: ruby git shell


【解决方案1】:

不是您问题的确切答案,但您可以将 --git-dir--work-tree 传递给 git 命令来告诉它在哪里操作,这可能会对您有所帮助。

我假设这不是一个裸 git 存储库,因为您重新基于它,所以这意味着 git 目录位于 .git

system("git --git-dir=#{repo[:name]}/.git --work-tree=#{repo[:name]} svn rebase")

【讨论】:

  • 这似乎解决了我的问题。感谢您的帮助。
【解决方案2】:

系统命令上有一个 chdir 选项 - 你可以这样做:

def performCommandInDir(command, dir)
  system(command, :chdir => dir)
end

【讨论】:

    【解决方案3】:

    不存储实际目录,而是使用带块的 Dir.chdir 更改它并切换回来:

    Dir.chdir(dir) do
      # your actions
    end
    # back in the original directory
    

    您的错误看起来像是 Git 问题,而不是 Ruby 问题。看来你进错目录了。

    您可以使用Dir.pwd 来检查工作目录。

    【讨论】:

      【解决方案4】:

      我解决问题的方法:

      def performCommandInDir(command, dir)
          system("cd #{dir} && #{command}")
      end
      

      【讨论】:

      • 如果您还打算在system 通话中使用cd #{dir},那么使用Dir.chdir 有什么意义?
      • 我对使用这个脚本没有任何想法,但是@darren 在他的示例的 2 行和 5 行中使用了一些丑陋的方法来回到旧路径。我认为你是对的,没有必要。
      猜你喜欢
      • 2014-05-07
      • 2019-06-16
      • 2015-06-23
      • 1970-01-01
      • 2013-11-25
      • 2012-05-10
      • 2022-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多