/bin/bbnew
Ruby | 112 lines | 86 code | 24 blank | 2 comment | 3 complexity | d36e4fbcf579bf070b0863098337901e MD5 | raw file
- #!/usr/bin/env ruby
- require 'optparse'
- require 'net/https'
- require 'uri'
- require 'rubygems' # needed for following library requires
- require 'highline/import' # needed for interactive authorization input
- help_text = {
- :conf => 'Specify a custom config file.',
- :desc => 'Specify a project description.',
- :lang => 'Specify a programming language.',
- :pass => 'Specify a Bitbucket password.',
- :user => 'Specify a Bitbucket user name.',
- :site => 'Specify a project website URI.',
- :private => 'Specify if a project is private',
- :help => 'Display this help text and exit.'
- }
- @usage = <<EOF
- USAGE: #{File.basename $0} [options] <NAME>
- The <NAME> token is the name of the remote repository you wish to create.
- EOF
- @config = {:conf => '~/.bitbucket'}
- @repo = Hash.new
- OptionParser.new do |opts|
- opts.banner = @usage
- opts.on('-c', '--conf=FILE', help_text[:conf]) do |conf|
- @config[:conf] = conf
- end
-
- opts.on('-d', '--desc=DESCRIPTION', help_text[:desc]) do |desc|
- @repo[:description] = desc
- end
-
- opts.on('-l', '--lang=LANGUAGE', help_text[:lang]) do |lang|
- @repo[:language] = lang
- end
-
- opts.on('-p', '--pass=PASSWORD', help_text[:pass]) do |pass|
- @config[:pass] = pass
- end
-
- opts.on('-u', '--user=USERNAME', help_text[:user]) do |user|
- @config[:user] = user
- end
-
- opts.on('--private', '--private', help_text[:private]) do |is_private|
- @repo[:is_private] = is_private
- end
-
- opts.on('-s', '--site=URI', help_text[:site]) do |site|
- @repo[:website] = site
- end
- opts.on('--help', '-h', help_text[:help]) do
- puts opts
- puts
- exit!(0)
- end
-
- end.parse!
-
- if 0 < ARGV.size
- p ARGV[0]
- @repo[:name] = ARGV[0]
- else
- puts @usage
- puts %Q{ Try "#{File.basename $0} --help" for usage information.}
- puts
- exit 1
- end
-
- @config[:conf] ||= "~/.bitbucket"
- if File.exist?(File.expand_path @config[:conf])
- File.open File.expand_path(@config[:conf]) do |bb|
- user, pass = bb.gets.chomp.split ':',2
- @config[:user] ||= user
- @config[:pass] ||= pass
- end
- end
-
- uri = URI.parse('https://api.bitbucket.org/1.0/repositories/')
-
- http = Net::HTTP.new(uri.host, uri.port)
- http.use_ssl = true
- req = Net::HTTP::Post.new(uri.path)
-
- # uses BitBucket password, not SSH password
- req.basic_auth(
- @config[:user] ||= ask('username: '),
- @config[:pass] || ask('password: ') {|q| q.echo = '' }
- )
-
- req.set_form_data(@repo)
- res = http.start {|http| http.request(req) }
- case res
- when Net::HTTPSuccess, Net::HTTPRedirection
- puts 'Successfully created the repository. Now cloning via ssh.'
- system `hg clone ssh://hg@bitbucket.org/#{
- @config[:user]
- }/#{@repo[:name]}`
- else
- res.error!
- end