├── .gitignore ├── Gemfile ├── LICENSE ├── README.rdoc ├── app ├── controllers │ ├── gitolite_hook_controller.rb │ └── gitolite_public_keys_controller.rb ├── helpers │ ├── gitolite_hook_helper.rb │ └── gitolite_public_keys_helper.rb ├── models │ ├── gitolite_observer.rb │ └── gitolite_public_key.rb └── views │ ├── gitolite_public_keys │ ├── _form.html.erb │ ├── edit.html.erb │ ├── index.html.erb │ └── new.html.erb │ ├── projects │ └── _redmine_gitolite.html.erb │ ├── repositories │ └── git_instructions.html.erb │ └── settings │ └── _redmine_gitolite.html.erb ├── config ├── locales │ └── en.yml └── routes.rb ├── contrib └── hooks │ ├── post-receive-redmine_gitolite │ └── post-receive-redmine_gitolite.simple ├── db └── migrate │ └── 20091119162427_create_gitolite_public_keys.rb ├── init.rb └── lib ├── gitolite └── patches │ ├── repositories_controller_patch.rb │ └── repositories_helper_patch.rb ├── gitolite_redmine.rb └── tasks └── gitolite.rake /.gitignore: -------------------------------------------------------------------------------- 1 | extra/ssh/private_key 2 | extra/ssh/private_key.pub 3 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | gem "net-ssh" 2 | gem "gitolite", ">= 0.0.3.alpha" 3 | gem "lockfile" 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 Kah Seng Tay - Gitolite modifications 2 | Copyright (c) 2010 Jakob Skjerning - Original code 3 | Copyright (c) 2009-2010 Jan Schulz-Hofen, ROCKET RENTALS GmbH (http://www.rocket-rentals.de). MIT License. 4 | Copyright (c) 2010 Eric Bishop (ericpaulbishop@gmail.com) MIT License. 5 | Copyright (c) 2011 Arkadiusz Hiler 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in 15 | all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.rdoc: -------------------------------------------------------------------------------- 1 | = redmine-gitolite 2 | 3 | CURRENT HEAD VERSION WORKS WITH TRUNK REDMINE 4 | 5 | This is {Redmine Gitolite Hook}[https://github.com/kahseng/redmine_gitolite_hook] combined with {redmine-gitolite}[https://github.com/jhogendorn/redmine-gitolite] 6 | 7 | A Redmine plugin which manages your gitolite configuration based on your projects and user memberships in Redmine. 8 | 9 | Provides Gitolite hook, for automaticaly pulling changes to local clone of repository. You don't need to any access to your, this plugin will create local clone and keep it up to date. 10 | 11 | Includes Public Key management views (extracted from http://plan.io). 12 | 13 | == Requirements: 14 | 15 | === Gems: 16 | * net-ssh 17 | * lockfile 18 | * {gitolite}[https://github.com/wingrunr21/gitolite/] (works with 1.8.7) 19 | 20 | === Other: 21 | * Gitolite server 22 | * accessible Git executable 23 | * curl 24 | 25 | 26 | == Setup: 27 | 1. Install Redmine and put this plugin in vendor/plugins directory and migrate 28 | database (plugins) 29 | $ cd redmine/plugins 30 | $ git clone git://github.com/ivyl/redmine-gitolite.git redmine_gitolite 31 | $ cd .. 32 | $ RAILS_ENV=production rake db:migrate_plugins 33 | 34 | 2. User running redmine (his key must be named named "redmine") must have RW+ access to gitolite-admin (assuming that you have gitolite installed). 35 | 36 | 3. Make sure that redmine user has gitolite server in his known_host list 37 | $ sudo su - redmine 38 | $ ssh gitolite.server 39 | * [accept key] 40 | 41 | 4. Configure email and name of git user for your redmine account 42 | $ git config --global user.email "redmine@gitolite.org" 43 | $ git config --global user.name "Redmine Gitolite" 44 | 45 | 5. Add post-receive hook to common gitolite hooks (examples in contrib dir) and configure it 46 | (host, api key, etc, see sources) 47 | $ sudo su - gitolite #login on gitolite user 48 | $ cat > .gitolite/hooks/common/post-receive 49 | * [paste hook] 50 | $ vim .gitolite/hooks/common/post-receive 51 | * [enable WS for repository management in administration->settings->repositories] 52 | * [copy generated API key] 53 | * [configure, in complex hook you can do this by git config options] 54 | $ chmod +x .gitolite/hooks/common/post-receive 55 | $ gl-setup 56 | 57 | 6. Configure plugin in redmine settings 58 | * [Adminitration -> Plugins -> Redmine Gitolite] 59 | * [Gitolite URL should be set to your gitolite-admin git repository] 60 | * [Base path should point directory which will hold local copies (must exist) 61 | * [Set developer and ro urls as in given examples (just slightly modify them)] 62 | * [%{name} will be replaced with your repository identifier] 63 | 64 | == Pro Tips: 65 | 66 | * You should manage your keys only from Redmine to avoid conflicts. 67 | * Need new bare git repo? Create it via Redmine, disable other features. 68 | * This is most convenient way to manage keys by your user. 69 | 70 | == Found bug? 71 | 72 | Open new issue and complain. You can also fix it and sent pull request. 73 | This plugin is in active usage in current, edge Redmine. Any suggestions are welcome. 74 | -------------------------------------------------------------------------------- /app/controllers/gitolite_hook_controller.rb: -------------------------------------------------------------------------------- 1 | require 'open3' 2 | 3 | class GitoliteHookController < ApplicationController 4 | unloadable 5 | 6 | skip_before_filter :verify_authenticity_token, :check_if_login_required 7 | 8 | def index 9 | repository = find_repository 10 | update_repository(repository) 11 | repository.fetch_changesets 12 | render(:text => 'OK') 13 | end 14 | 15 | private 16 | 17 | def exec(command) 18 | logger.debug { "GitoliteHook: Executing command: '#{command}'" } 19 | stdin, stdout, stderr = Open3.popen3(command) 20 | 21 | output = stdout.readlines.collect(&:strip) 22 | errors = stderr.readlines.collect(&:strip) 23 | 24 | logger.debug { "GitoliteHook: Output from git:" } 25 | logger.debug { "GitoliteHook: * STDOUT: #{output}"} 26 | logger.debug { "GitoliteHook: * STDERR: #{errors}"} 27 | end 28 | 29 | def update_repository(repository) 30 | origin = Setting.plugin_redmine_gitolite['developerBaseUrls'].lines.first 31 | origin = origin.gsub("%{name}", repository.project.identifier) 32 | exec("git clone --mirror '#{origin}' '#{repository.url}'") if !File.directory?(repository.url) 33 | exec("cd '#{repository.url}' && git remote update --prune") 34 | end 35 | 36 | def get_identifier 37 | identifier = params[:project_id] 38 | # TODO: Can obtain 'oldrev', 'newrev', 'refname', 'user' in POST params for further action if needed. 39 | raise ActiveRecord::RecordNotFound, "Project identifier not specified" if identifier.nil? 40 | return identifier 41 | end 42 | 43 | def find_project 44 | identifier = get_identifier 45 | project = Project.find_by_identifier(identifier.downcase) 46 | raise ActiveRecord::RecordNotFound, "No project found with identifier '#{identifier}'" if project.nil? 47 | return project 48 | end 49 | 50 | def find_repository 51 | project = find_project 52 | repository = project.repository 53 | raise TypeError, "Project '#{project.to_s}' ('#{project.identifier}') has no repository" if repository.nil? 54 | raise TypeError, "Repository for project '#{project.to_s}' ('#{project.identifier}') is not a Git repository" unless repository.is_a?(Repository::Git) 55 | return repository 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /app/controllers/gitolite_public_keys_controller.rb: -------------------------------------------------------------------------------- 1 | class GitolitePublicKeysController < ApplicationController 2 | unloadable 3 | 4 | 5 | before_filter :require_login 6 | before_filter :set_user_variable 7 | before_filter :find_gitolite_public_key, :except => [:index, :new, :create] 8 | 9 | def index 10 | @status = if (session[:gitolite_public_key_filter_status]=params[:status]).nil? 11 | GitolitePublicKey::STATUS_ACTIVE 12 | elsif params[:status].blank? 13 | nil 14 | else 15 | params[:status].to_i != 0 16 | end 17 | 18 | scope = @user.gitolite_public_keys 19 | scope = scope.where(active: true) if @status 20 | @gitolite_public_keys = scope.all(:order => 'active DESC, created_at DESC') 21 | 22 | 23 | respond_to do |format| 24 | format.html # index.html.erb 25 | format.json { render :json => @gitolite_public_keys } 26 | end 27 | end 28 | 29 | def edit 30 | end 31 | 32 | def update 33 | if params[:public_key][:active] 34 | status = params[:public_key].delete(:active).to_i 35 | if status == GitolitePublicKey::STATUS_ACTIVE 36 | @gitolite_public_key.active = true 37 | elsif status == GitolitePublicKey::STATUS_LOCKED 38 | @gitolite_public_key.active = false 39 | end 40 | end 41 | 42 | if @gitolite_public_key.update_attributes(params[:public_key]) 43 | flash[:notice] = l(:notice_public_key_updated) 44 | redirect_to url_for(:action => 'index', :status => session[:gitolite_public_key_filter_status]) 45 | else 46 | render :action => 'edit' 47 | end 48 | end 49 | 50 | def new 51 | @gitolite_public_key = GitolitePublicKey.new(:user => @user) 52 | end 53 | 54 | def create 55 | @gitolite_public_key = GitolitePublicKey.new(params[:public_key].merge(:user => @user)) 56 | if @gitolite_public_key.save 57 | flash[:notice] = l(:notice_public_key_added) 58 | redirect_to url_for(:action => 'index', :status => session[:gitolite_public_key_filter_status]) 59 | else 60 | render :action => 'new' 61 | end 62 | end 63 | 64 | def show 65 | respond_to do |format| 66 | format.html # show.html.erb 67 | format.json { render :json => @gitolite_public_key } 68 | end 69 | end 70 | 71 | protected 72 | 73 | def set_user_variable 74 | @user = User.current 75 | end 76 | 77 | def find_gitolite_public_key 78 | key = GitolitePublicKey.find_by_id(params[:id]) 79 | if key and key.user == @user 80 | @gitolite_public_key = key 81 | elsif key 82 | render_403 83 | else 84 | render_404 85 | end 86 | end 87 | end 88 | -------------------------------------------------------------------------------- /app/helpers/gitolite_hook_helper.rb: -------------------------------------------------------------------------------- 1 | module GitoliteHookHelper 2 | end 3 | -------------------------------------------------------------------------------- /app/helpers/gitolite_public_keys_helper.rb: -------------------------------------------------------------------------------- 1 | module GitolitePublicKeysHelper 2 | def gitolite_public_keys_status_options_for_select(user, selected) 3 | key_count_by_active = user.gitolite_public_keys.count(:group => 'active').to_hash 4 | options_for_select([[l(:label_all), nil], 5 | ["#{l(:status_active)} (#{key_count_by_active[GitolitePublicKey::STATUS_ACTIVE].to_i})", GitolitePublicKey::STATUS_ACTIVE], 6 | ["#{l(:status_locked)} (#{key_count_by_active[GitolitePublicKey::STATUS_LOCKED].to_i})", GitolitePublicKey::STATUS_LOCKED]], selected) 7 | end 8 | end 9 | -------------------------------------------------------------------------------- /app/models/gitolite_observer.rb: -------------------------------------------------------------------------------- 1 | class GitoliteObserver < ActiveRecord::Observer 2 | unloadable 3 | 4 | observe :project, :user, :gitolite_public_key, :member, :role, :repository 5 | 6 | def after_save(object) ; update_repositories(object) ; end 7 | def after_destroy(object) ; update_repositories(object) ; end 8 | 9 | protected 10 | 11 | def update_repositories(object) 12 | gr = GitoliteRedmine::AdminHandler.new 13 | case object 14 | when Repository then gr.update_projects(object.project) 15 | when User then (gr.update_projects(object.projects) && gr.update_user(object)) unless is_login_save?(object) 16 | when GitolitePublicKey then gr.update_user(object.user) 17 | when Member then gr.update_projects(object.project) 18 | when Role then gr.update_projects(object.members.map(&:project).uniq.compact) 19 | end 20 | end 21 | 22 | private 23 | 24 | # Test for the fingerprint of changes to the user model when the User actually logs in. 25 | def is_login_save?(user) 26 | user.changed? && user.changed.length == 2 && user.changed.include?("updated_on") && user.changed.include?("last_login_on") 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /app/models/gitolite_public_key.rb: -------------------------------------------------------------------------------- 1 | class GitolitePublicKey < ActiveRecord::Base 2 | unloadable 3 | STATUS_ACTIVE = 1 4 | STATUS_LOCKED = 0 5 | 6 | belongs_to :user 7 | validates_uniqueness_of :title, :scope => :user_id 8 | validates_uniqueness_of :identifier, :score => :user_id 9 | validates_presence_of :title, :key, :identifier 10 | 11 | scope :active, {:conditions => {:active => GitolitePublicKey::STATUS_ACTIVE}} 12 | scope :inactive, {:conditions => {:active => GitolitePublicKey::STATUS_LOCKED}} 13 | 14 | validate :has_not_been_changed, :is_valid_key 15 | 16 | before_validation :set_identifier 17 | 18 | def has_not_been_changed 19 | unless new_record? 20 | %w(identifier key user_id).each do |attribute| 21 | errors.add(attribute, 'may not be changed') unless changes[attribute].blank? 22 | end 23 | end 24 | end 25 | 26 | def is_valid_key 27 | valid = check_key(key) 28 | if !valid 29 | begin 30 | # We try validating again, after adding a newline, since some 4096-bit 31 | # public keys fail validation when a newline isn't present 32 | key = "#{key}\n" 33 | valid = check_key(key) 34 | if !valid 35 | errors[:base] = "invalid key" 36 | else 37 | self.key = key 38 | end 39 | rescue 40 | errors[:base] = "invalid key" 41 | end 42 | end 43 | end 44 | 45 | def check_key(key) 46 | File.open('/tmp/check_key', 'w') {|f| f.write(key)} 47 | stdin, stdout, stderr = Open3.popen3('ssh-keygen -l -f /tmp/check_key') 48 | data = stdout.gets() 49 | hash_regex = /([0-9a-f][0-9a-f](:[0-9a-f][0-9a-f])+)/ 50 | matching = hash_regex.match data 51 | File.delete('/tmp/check_key') 52 | if matching == nil 53 | false 54 | else 55 | true 56 | end 57 | end 58 | 59 | def set_identifier 60 | self.identifier ||= "#{self.user.login.underscore}@#{self.title.underscore}".gsub(/[^0-9a-zA-Z\-\_]/,'_') 61 | end 62 | 63 | def to_s ; title ; end 64 | 65 | def location 66 | self.title.underscore.gsub(/[^0-9a-zA-Z\-\_]/,'_') 67 | end 68 | 69 | def owner 70 | self.user.login.underscore.gsub(/[^0-9a-zA-Z\-\_]/,'_') 71 | end 72 | end 73 | -------------------------------------------------------------------------------- /app/views/gitolite_public_keys/_form.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

<%= f.text_field :title, :required => true %>

3 |

<%= f.text_area :key, :required => true, :disabled => !@gitolite_public_key.new_record?, :style => 'width:99%;height:140px;', :label => :field_public_key %> 4 | <% if !@gitolite_public_key.new_record?%> 5 |
<%= l(:label_key_cannot_be_changed_please_create_new_key) %> 6 | <% end %> 7 |

8 |

<%= f.check_box :active %>

9 |
10 | -------------------------------------------------------------------------------- /app/views/gitolite_public_keys/edit.html.erb: -------------------------------------------------------------------------------- 1 |

<%= link_to l(:label_public_keys), public_keys_path %> » <%= h @gitolite_public_key %>

2 | FOO 3 | <% if @gitolite_public_key.errors.any? %> 4 | 9 | <% end %> 10 | 11 | <%= labelled_form_for :public_key, @gitolite_public_key, :url => { :action => "update" }, :html => { :method => :put}, :lang => current_language do |f| %> 12 | 13 | <%= render :partial => 'form', :locals => { :f => f } %> 14 | <%= submit_tag l(:button_save) %> 15 | <% end %> 16 | 17 | <% html_title(l(:label_public_keys)) -%> 18 | -------------------------------------------------------------------------------- /app/views/gitolite_public_keys/index.html.erb: -------------------------------------------------------------------------------- 1 |

<%= link_to l(:label_my_account), :controller => 'my', :action => 'account' %> » <%=l(:label_public_keys)%>

2 | 3 | <% form_tag({}, :method => :get) do %> 4 |
<%= l(:label_filter_plural) %> 5 | 6 | <%= select_tag 'status', gitolite_public_keys_status_options_for_select(@user, @status), :class => "small", :onchange => "this.form.submit(); return false;" %> 7 | <%= submit_tag l(:button_apply), :class => "small", :name => nil %> 8 |
9 | <% end %> 10 |   11 | 12 | 13 | <% if @gitolite_public_keys.any? %> 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | <% @gitolite_public_keys.each do |key| %> 23 | 24 | 25 | 26 | 27 | 30 | 31 | <% end %> 32 |
<%= l(:field_name) %><%= l(:field_created_on) %><%= l(:field_active) %>
<%= link_to h(key), :action => 'edit', :id => key %><%= format_time(key.created_at) %><%= image_tag('true.png') if key.active? %> 28 | <%= link_to l(key.active? ? :button_lock : :button_unlock), public_key_path(key, :public_key => {:active => key.active? ? GitolitePublicKey::STATUS_LOCKED : GitolitePublicKey::STATUS_ACTIVE}), :method => :put, :class => "icon #{key.active? ? 'icon-lock' : 'icon-unlock'}" %> 29 |
33 | 34 | <% end %> 35 | 36 |

<%= link_to l(:label_enumeration_new), { :action => 'new'} %>

37 | 38 | <% html_title(l(:label_public_keys)) -%> 39 | -------------------------------------------------------------------------------- /app/views/gitolite_public_keys/new.html.erb: -------------------------------------------------------------------------------- 1 |

<%= link_to l(:label_public_keys), public_keys_path %> » <%=l(:label_public_key_new)%>

2 | 3 | <% if @gitolite_public_key.errors.any? %> 4 | 9 | <% end %> 10 | 11 | <%= labelled_form_for :public_key, @gitolite_public_key, :url => { :action => "create" }, :lang => current_language do |f| %> 12 | <%= render :partial => 'form', :locals => { :f => f } %> 13 | <%= submit_tag l(:button_create) %> 14 | <% end %> 15 | 16 | <% html_title(l(:label_public_keys)) -%> 17 | -------------------------------------------------------------------------------- /app/views/projects/_redmine_gitolite.html.erb: -------------------------------------------------------------------------------- 1 | <% if @project.repository && @project.repository.is_a?(Repository::Git) %> 2 |
3 |

Git Repository

4 |

5 | <% baseUrlStr = Setting.plugin_redmine_gitolite['readOnlyBaseUrls'] -%> 6 | <% if !baseUrlStr.empty? && User.current.allowed_to?(:view_changesets, @project) %> 7 | Read Only URL:
8 |

14 | <% end %> 15 |

16 |

17 | <% baseUrlStr = Setting.plugin_redmine_gitolite['developerBaseUrls'] %> 18 | <% if !baseUrlStr.empty? && User.current.allowed_to?(:commit_access, @project) %> 19 | Developer URL:
20 |

26 | <% end %> 27 |

28 |
29 | <% end %> 30 | -------------------------------------------------------------------------------- /app/views/repositories/git_instructions.html.erb: -------------------------------------------------------------------------------- 1 | <%# This is used to display basic git setup instructions, like on github... %> 2 | <% flash.now[:error] = "Repository does not exist. Create one using the instructions below." %> 3 |
4 | 5 |

Git Setup:

6 |
  Download and Install Git
 7 |   git config --global user.name "<%= User.current.login %>"
 8 |   git config --global user.email <%= User.current.mail %>
 9 | 
10 | 11 |

Permission Setup:

12 |
  <%= link_to "Upload SSH Public Key", {:controller => 'gitolite_public_keys', :action => 'index'} %>
13 |   Add yourself as a project developer: <%= link_to @project.name + " Settings", {:controller => 'projects', :action => 'settings'} %> -> Members Tab -> New Member
14 | 
15 | 16 |

Repository Setup:

17 |
  cd <%= @project.identifier %>
18 |   git init
19 |   git add .
20 |   git commit -m 'Initializing <%= @project %> repository'
21 |   git remote add origin <%= Setting.plugin_redmine_gitolite['developerBaseUrls'].gsub("%{name}", @project.identifier) %>
22 |   git push origin master
23 | 
24 | 25 |

Existing Git Repo?

26 |
  cd existing_git_repo
27 |   git remote add origin <%= Setting.plugin_redmine_gitolite['developerBaseUrls'].gsub("%{name}", @project.identifier) %>
28 |   git push origin master
29 | 
30 | 31 |
32 | -------------------------------------------------------------------------------- /app/views/settings/_redmine_gitolite.html.erb: -------------------------------------------------------------------------------- 1 |
2 |

3 | 4 | <%= text_field_tag("settings[gitoliteUrl]", @settings['gitoliteUrl'], :size => 60) %> 5 |
6 |

7 |

8 | 9 | <%= text_field_tag("settings[basePath]", @settings['basePath'], :size => 60) %> 10 |
11 |

12 |

13 | 14 | <%= text_area_tag("settings[developerBaseUrls]", @settings['developerBaseUrls'].split(/[\r\n\t ,;]+/).join("\n"), :size => 60) %> 15 |
16 |

17 |

18 | 19 | <%= text_area_tag("settings[readOnlyBaseUrls]", @settings['readOnlyBaseUrls'].split(/[\r\n\t ,;]+/).join("\n"), :size => 60) %> 20 |
21 |

22 |
23 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # English strings go here for Rails i18n 2 | en: 3 | label_public_keys: Public keys 4 | label_public_key_new: New public key 5 | label_gitolite_url: Gitolite URL 6 | label_gitolite_identity_file: Gitolite identity file 7 | label_base_path: Base path 8 | label_developer_base_urls: Developer base URL(s) 9 | label_read_only_base_urls: Read-only base URL(s) 10 | field_public_key: Key 11 | notice_public_key_updated: Public key was successfully updated. 12 | notice_public_key_added: Public key was successfully added. 13 | 14 | label_key_cannot_be_changed_please_create_new_key: 'The key cannot be altered anymore. However, you can deactivate it and create a new one.' 15 | -------------------------------------------------------------------------------- /config/routes.rb: -------------------------------------------------------------------------------- 1 | # Plugin's routes 2 | # See: http://guides.rubyonrails.org/routing.html 3 | 4 | resources :public_keys, :controller => 'gitolite_public_keys' 5 | match 'gitolite_hook' => 'gitolite_hook#index' 6 | -------------------------------------------------------------------------------- /contrib/hooks/post-receive-redmine_gitolite: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | HOOK_URL=gitolite_hook 4 | FETCH_URL=sys/fetch_changesets 5 | LOG=/home/git/logs/post-receive.log 6 | 7 | DEFAULT_REDMINE_KEY=your_redmine_api_key 8 | DEFAULT_REDMINE_SERVER=http://your.redmine.server.com 9 | DEFAULT_REDMINE_PROJECT_ID=$GL_REPO 10 | DEFAULT_CURL_IGNORE_SECURITY_CFG="false" 11 | 12 | KEY=$(git config hooks.redmine_gitolite.key 2>/dev/null) 13 | if [ -z "$KEY" ]; then 14 | KEY=$DEFAULT_REDMINE_KEY 15 | fi 16 | 17 | REDMINE_SERVER=$(git config hooks.redmine_gitolite.server 2>/dev/null) 18 | if [ -z "$REDMINE_SERVER" ]; then 19 | REDMINE_SERVER=$DEFAULT_REDMINE_SERVER 20 | fi 21 | 22 | REDMINE_PROJECT_ID=$(git config hooks.redmine_gitolite.projectid 2>/dev/null) 23 | if [ -z "$REDMINE_PROJECT_ID" ]; then 24 | REDMINE_PROJECT_ID=$DEFAULT_REDMINE_PROJECT_ID 25 | fi 26 | 27 | CURL_IGNORE_SECURITY_CFG=$(git config --bool hooks.redmine_gitolite.curlignoresecurity 2>/dev/null) 28 | if [ -z "$CURL_IGNORE_SECURITY_CFG" ]; then 29 | CURL_IGNORE_SECURITY_CFG=$DEFAULT_CURL_IGNORE_SECURITY_CFG 30 | fi 31 | 32 | case "$CURL_IGNORE_SECURITY_CFG" in 33 | true) 34 | CURL_IGNORE_SECURITY=" -k " 35 | ;; 36 | false) 37 | CURL_IGNORE_SECURITY=" " 38 | ;; 39 | esac 40 | 41 | echo 42 | echo "Notifying Redmine (${REDMINE_SERVER}) about changes to this repo (${GL_REPO} => ${REDMINE_PROJECT_ID})" 43 | echo 44 | 45 | # Read from stdin 46 | while read old new refname; do 47 | echo "Hitting the Redmine Gitolite hook for $old $new $refname" 48 | echo -n "Response: " 49 | curl $CURL_IGNORE_SECURITY -S -s -d "oldrev=$old&newrev=$new&refname=$refname&user=$GL_USER" "$REDMINE_SERVER/$HOOK_URL?project_id=$REDMINE_PROJECT_ID" 50 | echo "" 51 | echo "" 52 | echo "Hitting the Redmine fetch changesets URL" 53 | curl -S -s $CURL_IGNORE_SECURITY "$REDMINE_SERVER/$FETCH_URL?id=$REDMINE_PROJECT_ID&key=$KEY" 54 | echo "" 55 | done 56 | -------------------------------------------------------------------------------- /contrib/hooks/post-receive-redmine_gitolite.simple: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # 3 | # The "post-receive" script is run after receive-pack has accepted a pack 4 | # and the repository has been updated. It is passed arguments in through 5 | # stdin in the form 6 | # 7 | # For example: 8 | # aa453216d1b3e49e7f6f98441fa56946ddcd6a20 68f7abf4e6f922807889f52bc043ecd31b79f814 refs/heads/master 9 | 10 | REDMINE_SERVER=http://your.redmine.server.com 11 | HOOK_URL=gitolite_hook 12 | FETCH_URL=sys/fetch_changesets 13 | KEY=your_redmine_api_key 14 | LOG=/home/git/logs/post-receive.log 15 | 16 | # Read from stdin 17 | while read old new refname; do 18 | echo "Post-receive hook for this repo: [$GL_REPO] $old $new $refname" 19 | # Hit the Redmine Gitolite hook for this repo 20 | curl -d "oldrev=$old&newrev=$new&refname=$refname&user=$GL_USER" "$REDMINE_SERVER/$HOOK_URL?project_id=$GL_REPO" 21 | # Hit the fetch changesets URL 22 | curl "$REDMINE_SERVER/$FETCH_URL?id=$GL_REPO&key=$KEY" 23 | echo "Done." 24 | echo "" 25 | done 26 | -------------------------------------------------------------------------------- /db/migrate/20091119162427_create_gitolite_public_keys.rb: -------------------------------------------------------------------------------- 1 | class CreateGitolitePublicKeys < ActiveRecord::Migration 2 | def self.up 3 | create_table :gitolite_public_keys do |t| 4 | t.column :title, :string 5 | t.column :identifier, :string 6 | t.column :key, :text 7 | t.column :active, :integer, :default => 1 8 | t.references :user 9 | t.timestamps 10 | 11 | end 12 | end 13 | 14 | def self.down 15 | drop_table :gitolite_public_keys 16 | end 17 | end 18 | -------------------------------------------------------------------------------- /init.rb: -------------------------------------------------------------------------------- 1 | require 'redmine' 2 | require_dependency 'principal' 3 | require_dependency 'user' 4 | 5 | require_dependency 'gitolite_redmine' 6 | require_dependency 'gitolite/patches/repositories_controller_patch' 7 | require_dependency 'gitolite/patches/repositories_helper_patch' 8 | 9 | Redmine::Plugin.register :redmine_gitolite do 10 | name 'Redmine Gitolite plugin' 11 | author 'Arkadiusz Hiler, Joshua Hogendorn, Jan Schulz-Hofen, Kah Seng Tay, Jakob Skjerning' 12 | description 'Enables Redmine to manage gitolite repositorie.' 13 | version '0.0.2' 14 | 15 | requires_redmine :version_or_higher => '2.0.0' 16 | url 'https://github.com/ivyl/redmine-gitolite/' 17 | author_url 'http://ivyl.0xcafe.eu/' 18 | 19 | settings :default => { 20 | 'gitoliteUrl' => 'gitolite@localhost:gitolite-admin.git', 21 | 'developerBaseUrls' => "git@example.com:%{name}.git", 22 | 'readOnlyBaseUrls' => 'http://example.com/git/%{name}', 23 | 'basePath' => '/home/redmine/repositories/', 24 | } 25 | end 26 | 27 | # initialize hook 28 | class GitolitePublicKeyHook < Redmine::Hook::ViewListener 29 | render_on :view_my_account_contextual, :inline => "| <%= link_to(l(:label_public_keys), public_keys_path) %>" 30 | end 31 | 32 | class GitoliteProjectShowHook < Redmine::Hook::ViewListener 33 | render_on :view_projects_show_left, :partial => 'redmine_gitolite' 34 | end 35 | 36 | # initialize association from user -> public keys 37 | User.send(:has_many, :gitolite_public_keys, :dependent => :destroy) 38 | 39 | # initialize observer 40 | ActiveRecord::Base.observers = ActiveRecord::Base.observers << GitoliteObserver 41 | -------------------------------------------------------------------------------- /lib/gitolite/patches/repositories_controller_patch.rb: -------------------------------------------------------------------------------- 1 | require_dependency 'repositories_controller' 2 | module GitoliteRedmine 3 | module Patches 4 | module RepositoriesControllerPatch 5 | 6 | def show_with_git_instructions 7 | if @repository.is_a?(Repository::Git) and @repository.entries(@path, @rev).blank? 8 | render :action => 'git_instructions' 9 | else 10 | show_without_git_instructions 11 | end 12 | end 13 | 14 | def edit_with_scm_settings 15 | git_parametrize 16 | edit_without_scm_settings 17 | end 18 | 19 | def update_with_scm_settings 20 | git_parametrize 21 | update_without_scm_settings 22 | end 23 | 24 | def create_with_scm_settings 25 | git_parametrize 26 | create_without_scm_settings 27 | end 28 | 29 | def self.included(base) 30 | base.class_eval do 31 | unloadable 32 | end 33 | base.send(:alias_method_chain, :show, :git_instructions) 34 | base.send(:alias_method_chain, :edit, :scm_settings) 35 | base.send(:alias_method_chain, :update, :scm_settings) 36 | base.send(:alias_method_chain, :create, :scm_settings) 37 | end 38 | 39 | private 40 | 41 | def git_parametrize 42 | params[:repository] ||= {} 43 | params[:repository][:extra_report_last_commit] = '1' 44 | params[:repository][:url] = File.join(Setting.plugin_redmine_gitolite['basePath'],@project.identifier+".git") if params[:repository_scm] == 'Git' 45 | end 46 | 47 | end 48 | end 49 | end 50 | 51 | RepositoriesController.send(:include, GitoliteRedmine::Patches::RepositoriesControllerPatch) unless RepositoriesController.include?(GitoliteRedmine::Patches::RepositoriesControllerPatch) 52 | -------------------------------------------------------------------------------- /lib/gitolite/patches/repositories_helper_patch.rb: -------------------------------------------------------------------------------- 1 | require_dependency 'repositories_helper' 2 | module GitoliteRedmine 3 | module Patches 4 | module RepositoriesHelperPatch 5 | def git_field_tags_with_disabled_configuration(form, repository) ; '' ; end 6 | 7 | def self.included(base) 8 | base.class_eval do 9 | unloadable 10 | end 11 | base.send(:alias_method_chain, :git_field_tags, :disabled_configuration) 12 | end 13 | 14 | end 15 | end 16 | end 17 | RepositoriesHelper.send(:include, GitoliteRedmine::Patches::RepositoriesHelperPatch) unless RepositoriesHelper.include?(GitoliteRedmine::Patches::RepositoriesHelperPatch) 18 | -------------------------------------------------------------------------------- /lib/gitolite_redmine.rb: -------------------------------------------------------------------------------- 1 | require 'lockfile' 2 | require 'gitolite' 3 | require 'fileutils' 4 | require 'net/ssh' 5 | require 'tmpdir' 6 | 7 | module GitoliteRedmine 8 | class AdminHandler 9 | @@recursionCheck = false 10 | 11 | def update_user(user) 12 | recursion_check do 13 | if lock 14 | clone(Setting.plugin_redmine_gitolite['gitoliteUrl'], local_dir) 15 | 16 | logger.debug "[Gitolite] Handling #{user.inspect}" 17 | add_active_keys(user.gitolite_public_keys.active) 18 | remove_inactive_keys(user.gitolite_public_keys.inactive) 19 | 20 | @repo.save 21 | @repo.apply 22 | FileUtils.rm_rf local_dir 23 | unlock 24 | end 25 | end 26 | end 27 | 28 | def update_projects(projects) 29 | recursion_check do 30 | projects = (projects.is_a?(Array) ? projects : [projects]) 31 | 32 | if projects.detect{|p| p.repository.is_a?(Repository::Git)} && lock 33 | clone(Setting.plugin_redmine_gitolite['gitoliteUrl'], local_dir) 34 | 35 | projects.select{|p| p.repository.is_a?(Repository::Git)}.each do |project| 36 | logger.debug "[Gitolite] Handling #{project.inspect}" 37 | handle_project project 38 | end 39 | 40 | @repo.save 41 | @repo.apply 42 | FileUtils.rm_rf local_dir 43 | unlock 44 | end 45 | end 46 | end 47 | 48 | private 49 | 50 | def local_dir 51 | @local_dir ||= File.join(Rails.root, "tmp", "redmine_gitolite_#{Time.now.to_i}") 52 | end 53 | 54 | def clone(origin, local_dir) 55 | FileUtils.mkdir_p local_dir 56 | result = `git clone #{origin} #{local_dir}` 57 | logger.debug result 58 | @repo = Gitolite::GitoliteAdmin.new local_dir 59 | end 60 | 61 | def lock 62 | lockfile_path = File.join(RAILS_ROOT,"tmp",'redmine_gitolite_lock') 63 | @lockfile = File.new(lockfile_path, File::CREAT|File::RDONLY) 64 | retries = 5 65 | while (retries -= 1) > 0 66 | return @lockfile if @lockfile.flock(File::LOCK_EX|File::LOCK_NB) 67 | sleep 2 68 | end 69 | false 70 | end 71 | 72 | def unlock 73 | @lockfile.flock(File::LOCK_UN) 74 | end 75 | 76 | def handle_project(project) 77 | users = project.member_principals.map(&:user).compact.uniq 78 | 79 | name = project.identifier.to_s 80 | conf = @repo.config.repos[name] 81 | 82 | unless conf 83 | conf = Gitolite::Config::Repo.new(name) 84 | @repo.config.add_repo(conf) 85 | end 86 | 87 | conf.permissions = build_permissions(users, project) 88 | end 89 | 90 | def add_active_keys(keys) 91 | keys.each do |key| 92 | parts = key.key.split 93 | repo_keys = @repo.ssh_keys[key.owner] 94 | repo_key = repo_keys.find_all{|k| k.location == key.location && k.owner == key.owner}.first 95 | if repo_key 96 | repo_key.type, repo_key.blob, repo_key.email = parts 97 | repo_key.owner = key.owner 98 | else 99 | repo_key = Gitolite::SSHKey.new(parts[0], parts[1], parts[2]) 100 | repo_key.location = key.location 101 | repo_key.owner = key.owner 102 | @repo.add_key repo_key 103 | end 104 | end 105 | end 106 | 107 | def remove_inactive_keys(keys) 108 | keys.each do |key| 109 | repo_keys = @repo.ssh_keys[key.owner] 110 | repo_key = repo_keys.find_all{|k| k.location == key.location && k.owner == key.owner}.first 111 | @repo.rm_key repo_key if repo_key 112 | end 113 | end 114 | 115 | def build_permissions(users, project) 116 | write_users = users.select{|user| user.allowed_to?(:commit_access, project) } 117 | read_users = users.select{|user| user.allowed_to?(:view_changesets, project) && !user.allowed_to?(:commit_access, project) } 118 | 119 | write = write_users.map{|usr| usr.login.underscore.gsub(/[^0-9a-zA-Z\-\_]/,'_')}.sort 120 | read = read_users.map{|usr| usr.login.underscore.gsub(/[^0-9a-zA-Z\-\_]/,'_')}.sort 121 | 122 | read << "redmine" 123 | read << "daemon" if User.anonymous.allowed_to?(:view_changesets, project) 124 | read << "gitweb" if User.anonymous.allowed_to?(:view_gitweb, project) 125 | 126 | permissions = {} 127 | permissions["RW+"] = {"" => write} unless write.empty? 128 | permissions["R"] = {"" => read} unless read.empty? 129 | 130 | [permissions] 131 | end 132 | 133 | def recursion_check 134 | return if @@recursionCheck 135 | begin 136 | @@recursionCheck = true 137 | yield 138 | rescue Exception => e 139 | logger.error "#{e.inspect} #{e.backtrace}" 140 | ensure 141 | @@recursionCheck = false 142 | end 143 | end 144 | 145 | def logger 146 | Rails.logger 147 | end 148 | end 149 | end 150 | -------------------------------------------------------------------------------- /lib/tasks/gitolite.rake: -------------------------------------------------------------------------------- 1 | namespace :gitolite do 2 | desc "update gitolite repositories" 3 | task :update_repositories => [:environment] do 4 | projects = Project.active 5 | puts "Updating repositories for projects #{projects.join(' ')}" 6 | Gitolite.update_repositories(projects) 7 | end 8 | desc "fetch commits from gitolite repositories" 9 | task :fetch_changes => [:environment] do 10 | Repository.fetch_changesets 11 | end 12 | end 13 | 14 | --------------------------------------------------------------------------------