GIT和Ruby:如何在Ruby脚本内部取消设置GIT_DIR变量?

5
我已经编写了一个非常简单的“deploy”脚本,作为我裸的git仓库中的post-update钩子运行。
变量如下:
live domain         = ~/mydomain.com
staging domain      = ~/stage.mydomain.com
git repo location   = ~/git.mydomain.com/thisrepo.git (bare)

core                = ~/git.mydomain.com/thisrepo.git
core                == added remote into each live & stage gits

both live & stage已经初始化了git仓库(非裸仓库),我已将我的裸仓库添加为它们各自的远程仓库(命名为core),这样git pull core stagegit pull core live就会从core仓库的相应分支中拉取更新的文件。

脚本如下:

#!/usr/bin/env ruby

# Loop over each passed in argument
ARGV.each do |branch|

  # If it matches the stage then 'update' the staging files
  if branch == "refs/heads/stage"

    puts ""
    puts "Looks like the staging branch was updated."
    puts "Running a tree checkout now…"
    puts ""
    `cd ~/stage.mydomain.com`
    `unset GIT_DIR` # <= breaks!
    `git pull core stage`
    puts ""
    puts "Tree pull completed on staging branch."
    puts ""

  # If it's a live site update, update those files
  elsif branch == "refs/heads/live"

    puts ""
    puts "Looks like the live branch was updated."
    puts "Running a tree checkout now…"
    puts ""
    `cd ~/mydomain.com`
    `unset GIT_DIR` # <= breaks!
    `git pull core live`
    puts ""
    puts "Tree checkout completed on live branch."
    puts ""

  end

end

我已经尝试了从这个bash脚本中的文件'更新',它使用unset GIT_DIR来运行下一个git命令,例如git pull core stage。在这里,core是我在服务器上不同文件夹中的repo的添加remote
但是,当执行上述脚本时,我会遇到以下错误:
remote: hooks/post-update:35: command not found: unset GIT_DIR        
remote: fatal: /usr/lib/git-core/git-pull cannot be used without a working tree.        

有没有办法在我的Ruby脚本中像bash脚本中的 unset GIT_DIR 一样做同样的事情?
谢谢,
Jannis
2个回答

6

这看起来像是

`cd ~/stage.mydomain.com && unset GIT_DIR && git pull core stage`

帮助您翻译的内容如下:

关于为什么会出现这种情况(我并不熟悉Ruby,以下是我的猜测):您可能是在与运行git pull的不同shell中运行了unset命令(正如samold在他的回答中指出的那样,当前工作目录也存在相同的问题)。

这表明可能存在一些Ruby API来操作环境变量,Ruby通过反引号运算符启动的shell以及更改当前工作目录。


这就像魔法一样!非常感谢。现在已经全部启动并运行了!接下来要找出如何通过将特殊格式的注释传递到提交说明中来完成相同的操作 :) 我想知道是否可以使用类似 [update:live][update:stage] 的东西来触发此 pull 操作... - Jannis
刚刚省了我很多的沮丧 - 谢谢!没意识到这些变量有如此重要的意义! - TJ Biddle

5

尝试用以下代码替换您的代码:

ENV['GIT_DIR']=nil

我不确定您的意思:

`cd ~/stage.mydomain.com`
`unset GIT_DIR` # <= breaks!
`git pull core stage`

即使GIT_DIR已经被正确取消设置,部分功能仍然可以正常工作。每个反引号都会启动一个新的shell,与旧的shell无关,子shell不能更改其父进程的当前工作目录。

尝试这个:

ENV["GIT_DIR"]=nil
`cd ~/stage.mydomain.com ; git pull core stage`

谢谢你的提示!这个答案和__ndim__的答案一样好,但因为我的最终脚本使用了他的单引号字符串格式化,所以我选择接受他的答案而不是这个。无论如何,再次感谢! - Jannis
1
@Jannis,这取决于你的目标:如果你只想在一个调用中取消设置GIT_DIR,那么@ndim的答案更好。如果你想在整个脚本中取消设置GIT_DIR,那么我的答案更好。它们做不同的事情 :) 所以选择适合任务的那个。 - sarnold
哦,既然你提到了,这确实很有道理!感谢你让我知道这个,对于这种情况,我会保持 unset ..,但对于未来的脚本编写,这肯定会非常有用。再次感谢。 - Jannis
在我看来,这是大多数情况下更优秀的解决方案;例如,在整个构建过程中应该保持清洁的构建环境。我认识到有些构建可能会执行逐步的 ENV 更改,但我认为这不是最佳实践。我已经在我们的构建环境中实施了 @sarnold 的解决方案。 - New Alexandria

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接