Bugfix: make sure to require yaml in bin/setup
[gitorious:bclow-gitorious.git] / bin / setup.rb
1 # Wrapper script for Gitorious-related CLIs
2 # It will :
3 # - set up an environment for bundler
4 # - check if a specific user is required in gitorious.yml
5 # - if so: check if we are it
6 # - if not and we are root: setuid+setgid to that user
7 # - if not and we are not root, fail
8 require "etc"
9
10 module Gitorious
11   class CLI
12     def run_with_gitorious_environment(options={})
13       setup_environment(options)
14       require_valid_user!
15       yield
16     end
17
18     def setup_environment(options)
19       require "pathname"
20       require "rubygems"
21       ENV["BUNDLE_GEMFILE"] = (Pathname(rails_root) + "Gemfile").to_s
22       ENV["RAILS_ENV"] ||= "production"
23       Dir.chdir(rails_root)
24       require "bundler/setup" unless options[:skip_bundler]
25     end
26
27     def rails_root
28       rails_root ||= (Pathname(__FILE__) + "../../").realpath.to_s
29     end
30
31     def require_valid_user!
32       if rails_env == "production"
33         if git_user = gitorious_config("gitorious_user")
34           etc_user = Etc.getpwnam(git_user)
35           uid = etc_user.uid
36           if git_group = Etc.getgrnam(git_user)
37             gid = git_group.gid
38           else
39             gid = etc_user.gid
40           end
41           ENV["HOME"] = etc_user.dir
42           current_userid = Process.euid
43           if current_userid == uid
44             # OK, running as correct user
45           else
46             if current_userid == 0
47               Process::GID.change_privilege(gid)
48               Process::UID.change_privilege(uid)
49             else
50               raise "You need to be root to do this!"
51             end
52           end
53         end
54       end
55     end
56
57     require "yaml"
58     def gitorious_config(key)
59       YAML::load_file(rails_root + "/config/gitorious.yml")[rails_env][key]
60     end
61
62     def rails_env
63       ENV["RAILS_ENV"]
64     end
65   end
66 end