You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reposman.rb 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #!/usr/bin/env ruby
  2. require 'optparse'
  3. require 'find'
  4. require 'etc'
  5. require 'rubygems'
  6. Version = "1.5"
  7. SUPPORTED_SCM = %w( Subversion Darcs Mercurial Bazaar Git Filesystem )
  8. $verbose = 0
  9. $quiet = false
  10. $redmine_host = ''
  11. $repos_base = ''
  12. $svn_owner = 'root'
  13. $svn_group = 'root'
  14. $use_groupid = true
  15. $svn_url = false
  16. $test = false
  17. $force = false
  18. $scm = 'Subversion'
  19. def log(text, options={})
  20. level = options[:level] || 0
  21. puts text unless $quiet or level > $verbose
  22. exit 1 if options[:exit]
  23. end
  24. def system_or_raise(command)
  25. raise "\"#{command}\" failed" unless system command
  26. end
  27. module SCM
  28. module Subversion
  29. def self.create(path)
  30. system_or_raise "svnadmin create #{path}"
  31. end
  32. end
  33. module Git
  34. def self.create(path)
  35. Dir.mkdir path
  36. Dir.chdir(path) do
  37. system_or_raise "git --bare init --shared"
  38. system_or_raise "git update-server-info"
  39. end
  40. end
  41. end
  42. end
  43. def read_key_from_file(filename)
  44. begin
  45. $api_key = File.read(filename).strip
  46. rescue Exception => e
  47. $stderr.puts "Unable to read the key from #{filename}: #{e.message}"
  48. exit 1
  49. end
  50. end
  51. def set_scm(scm)
  52. $scm = scm.capitalize
  53. unless SUPPORTED_SCM.include?($scm)
  54. log("Invalid SCM: #{$scm}\nValid SCM are: #{SUPPORTED_SCM.join(', ')}", :exit => true)
  55. end
  56. end
  57. optparse = OptionParser.new do |opts|
  58. opts.banner = "Usage: reposman.rb [OPTIONS...] -s [DIR] -r [HOST] -k [KEY]"
  59. opts.separator("")
  60. opts.separator("Manages your repositories with Redmine.")
  61. opts.separator("")
  62. opts.separator("Required arguments:")
  63. opts.on("-s", "--svn-dir DIR", "use DIR as base directory for svn repositories") {|v| $repos_base = v}
  64. opts.on("-r", "--redmine-host HOST","assume Redmine is hosted on HOST. Examples:",
  65. " -r redmine.example.net",
  66. " -r http://redmine.example.net",
  67. " -r https://redmine.example.net") {|v| $redmine_host = v}
  68. opts.on("-k", "--key KEY", "use KEY as the Redmine API key",
  69. "(you can use --key-file option as an alternative)") {|v| $api_key = v}
  70. opts.separator("")
  71. opts.separator("Options:")
  72. opts.on("-o", "--owner OWNER", "owner of the repository. using the rails login",
  73. "allows users to browse the repository within",
  74. "Redmine even for private projects. If you want to",
  75. "share repositories through Redmine.pm, you need",
  76. "to use the apache owner.") {|v| $svn_owner = v; $use_groupid = false}
  77. opts.on("-g", "--group GROUP", "group of the repository (default: root)") {|v| $svn_group = v; $use_groupid = false}
  78. opts.on("-u", "--url URL", "the base url Redmine will use to access your",
  79. "repositories. This option is used to register",
  80. "the repositories in Redmine automatically. The",
  81. "project identifier will be appended to this url.",
  82. "Examples:",
  83. " -u https://example.net/svn",
  84. " -u file:///var/svn/",
  85. "if this option isn't set, reposman won't register",
  86. "the repositories in Redmine") {|v| $svn_url = v}
  87. opts.on( "--scm SCM", "the kind of SCM repository you want to create",
  88. "(and register) in Redmine (default: Subversion).",
  89. "reposman is able to create Git and Subversion",
  90. "repositories.",
  91. "For all other kind, you must specify a --command",
  92. "option") {|v| set_scm(v)}
  93. opts.on("-c", "--command COMMAND", "use this command instead of `svnadmin create` to",
  94. "create a repository. This option can be used to",
  95. "create repositories other than subversion and git",
  96. "kind.",
  97. "This command override the default creation for",
  98. "git and subversion.") {|v| $command = v}
  99. opts.on( "--key-file FILE", "path to a file that contains the Redmine API key",
  100. "(use this option instead of --key if you don't",
  101. "want the key to appear in the command line)") {|v| read_key_from_file(v)}
  102. opts.on("-t", "--test", "only show what should be done") {$test = true}
  103. opts.on("-f", "--force", "force repository creation even if the project", "repository is already declared in Redmine") {$force = true}
  104. opts.on("-v", "--verbose", "verbose") {$verbose += 1}
  105. opts.on("-V", "--version", "show version and exit") {puts Version; exit}
  106. opts.on("-h", "--help", "show help and exit") {puts opts; exit 1}
  107. opts.on("-q", "--quiet", "no log") {$quiet = true}
  108. opts.separator("")
  109. opts.separator("Examples:")
  110. opts.separator(" reposman.rb --svn-dir=/var/svn --redmine-host=redmine.host")
  111. opts.separator(" reposman.rb -s /var/git -r redmine.host -u http://git.host --scm git")
  112. opts.separator("")
  113. opts.separator("You can find more information on the redmine's wiki:\nhttp://www.redmine.org/projects/redmine/wiki/HowTos")
  114. opts.summary_width = 25
  115. end
  116. optparse.parse!
  117. if $test
  118. log("running in test mode")
  119. end
  120. # Make sure command is overridden if SCM vendor is not handled internally (for the moment Subversion and Git)
  121. if $command.nil?
  122. begin
  123. scm_module = SCM.const_get($scm)
  124. rescue
  125. log("Please use --command option to specify how to create a #{$scm} repository.", :exit => true)
  126. end
  127. end
  128. $svn_url += "/" if $svn_url and not $svn_url.match(/\/$/)
  129. if ($redmine_host.empty? or $repos_base.empty?)
  130. puts "Some arguments are missing. Use reposman.rb --help for getting help."
  131. exit 1
  132. end
  133. unless File.directory?($repos_base)
  134. log("directory '#{$repos_base}' doesn't exists", :exit => true)
  135. end
  136. begin
  137. require 'active_resource'
  138. rescue LoadError
  139. log("This script requires activeresource.\nRun 'gem install activeresource' to install it.", :exit => true)
  140. end
  141. class Project < ActiveResource::Base
  142. self.headers["User-agent"] = "Redmine repository manager/#{Version}"
  143. self.format = :json
  144. end
  145. log("querying Redmine for active projects with repository module enabled...", :level => 1);
  146. $redmine_host.gsub!(/^/, "http://") unless $redmine_host.match("^https?://")
  147. $redmine_host.gsub!(/\/$/, '')
  148. Project.site = "#{$redmine_host}/sys";
  149. begin
  150. # Get all active projects that have the Repository module enabled
  151. projects = Project.find(:all, :params => {:key => $api_key})
  152. rescue ActiveResource::ForbiddenAccess
  153. log("Request was denied by your Redmine server. Make sure that 'WS for repository management' is enabled in application settings and that you provided the correct API key.")
  154. rescue => e
  155. log("Unable to connect to #{Project.site}: #{e}", :exit => true)
  156. end
  157. if projects.nil?
  158. log('No project found, perhaps you forgot to "Enable WS for repository management"', :exit => true)
  159. end
  160. log("retrieved #{projects.size} projects", :level => 1)
  161. def set_owner_and_rights(project, repos_path, &block)
  162. if mswin?
  163. yield if block_given?
  164. else
  165. uid, gid = Etc.getpwnam($svn_owner).uid, ($use_groupid ? Etc.getgrnam(project.identifier).gid : Etc.getgrnam($svn_group).gid)
  166. right = project.is_public ? 0775 : 0770
  167. yield if block_given?
  168. Find.find(repos_path) do |f|
  169. File.chmod right, f
  170. File.chown uid, gid, f
  171. end
  172. end
  173. end
  174. def other_read_right?(file)
  175. (File.stat(file).mode & 0007).zero? ? false : true
  176. end
  177. def owner_name(file)
  178. mswin? ?
  179. $svn_owner :
  180. Etc.getpwuid( File.stat(file).uid ).name
  181. end
  182. def mswin?
  183. (RUBY_PLATFORM =~ /(:?mswin|mingw)/) || (RUBY_PLATFORM == 'java' && (ENV['OS'] || ENV['os']) =~ /windows/i)
  184. end
  185. projects.each do |project|
  186. if project.identifier.empty?
  187. log("\tno identifier for project #{project.name}")
  188. next
  189. elsif not project.identifier.match(/^[a-z0-9\-_]+$/)
  190. log("\tinvalid identifier for project #{project.name} : #{project.identifier}");
  191. next;
  192. end
  193. log("processing project #{project.identifier} (#{project.name})", :level => 1)
  194. repos_path = File.join($repos_base, project.identifier).gsub(File::SEPARATOR, File::ALT_SEPARATOR || File::SEPARATOR)
  195. if File.directory?(repos_path)
  196. # we must verify that repository has the good owner and the good
  197. # rights before leaving
  198. other_read = other_read_right?(repos_path)
  199. owner = owner_name(repos_path)
  200. next if project.is_public == other_read and owner == $svn_owner
  201. if $test
  202. log("\tchange mode on #{repos_path}")
  203. next
  204. end
  205. begin
  206. set_owner_and_rights(project, repos_path)
  207. rescue Errno::EPERM => e
  208. log("\tunable to change mode on #{repos_path} : #{e}\n")
  209. next
  210. end
  211. log("\tmode change on #{repos_path}");
  212. else
  213. # if repository is already declared in redmine, we don't create
  214. # unless user use -f with reposman
  215. if $force == false and project.respond_to?(:repository)
  216. log("\trepository for project #{project.identifier} already exists in Redmine", :level => 1)
  217. next
  218. end
  219. project.is_public ? File.umask(0002) : File.umask(0007)
  220. if $test
  221. log("\trepository #{repos_path} created")
  222. log("\trepository #{repos_path} registered in Redmine with url #{$svn_url}#{project.identifier}") if $svn_url;
  223. next
  224. end
  225. begin
  226. set_owner_and_rights(project, repos_path) do
  227. if scm_module.nil?
  228. system_or_raise "#{$command} #{repos_path}"
  229. else
  230. scm_module.create(repos_path)
  231. end
  232. end
  233. rescue => e
  234. log("\tunable to create #{repos_path} : #{e}\n")
  235. next
  236. end
  237. log("\trepository #{repos_path} created");
  238. if $svn_url
  239. begin
  240. project.post(:repository, :vendor => $scm, :repository => {:url => "#{$svn_url}#{project.identifier}"}, :key => $api_key)
  241. log("\trepository #{repos_path} registered in Redmine with url #{$svn_url}#{project.identifier}");
  242. rescue => e
  243. log("\trepository #{repos_path} not registered in Redmine: #{e.message}");
  244. end
  245. end
  246. end
  247. end