Merge branch 'master' of git://gitorious.org/gitorious/chuyeow-gitorious
[gitorious:mainline.git] / lib / gitorious / ssh / client.rb
1 #--
2 #   Copyright (C) 2007, 2008 Johan Sørensen <johan@johansorensen.com>
3 #
4 #   This program is free software: you can redistribute it and/or modify
5 #   it under the terms of the GNU Affero General Public License as published by
6 #   the Free Software Foundation, either version 3 of the License, or
7 #   (at your option) any later version.
8 #
9 #   This program is distributed in the hope that it will be useful,
10 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #   GNU Affero General Public License for more details.
13 #
14 #   You should have received a copy of the GNU Affero General Public License
15 #   along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 #++
17
18 require "net/http"
19
20 module Gitorious
21   module SSH  
22     class AccessDeniedError < StandardError; end
23   
24     class Client
25       def initialize(strainer, username)
26         @strainer = strainer
27         @project_name, @repository_name = strainer.path.split("/")
28         @repository_name.gsub!(/\.git$/, "")
29         @user_name = username
30       end
31       attr_accessor :project_name, :repository_name, :user_name
32     
33       def writable_by_user?
34         $stderr.puts "Querying #{query_url}" if $DEBUG
35         resp = connection.get(query_url)
36         resp.body == "true"
37       end
38     
39       def assure_user_can_write!
40         writable_by_user? || raise(AccessDeniedError)
41       end
42     
43       def query_url
44         url = ["/projects"]
45         url << @project_name
46         url << "repos"
47         url << @repository_name
48         url << "writable_by?username=#{@user_name}"
49         url.join("/")
50       end
51     
52       def to_git_shell_argument
53         "#{@strainer.verb} '#{@strainer.full_path}'"
54       end
55     
56       protected
57         def connection
58           port = GitoriousConfig["gitorious_client_port"]
59           host = GitoriousConfig["gitorious_client_host"]
60           @connection ||= Net::HTTP.start(host, port)
61         end
62     end
63   end
64 end