Skip to content

Instantly share code, notes, and snippets.

@rkistner
Created August 6, 2013 10:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rkistner/6163367 to your computer and use it in GitHub Desktop.
Save rkistner/6163367 to your computer and use it in GitHub Desktop.
Automated installation of Android SDK components
require 'pty'
require 'expect'
def parse_android_packages(packages_raw)
packages_raw = packages_raw.split("\n----------\n")
result = []
packages_raw.each do |raw|
id_match = /id: (\d+) or "(.+)"/.match(raw)
type_match = /Type: (.*)/.match(raw)
desc_match = /Desc: (.*)/.match(raw)
next if id_match.nil? || type_match.nil? || desc_match.nil?
result << {
:id => id_match[1],
:name => id_match[2],
:desc => desc_match[1],
:type => type_match[1]
}
end
result
end
def filter_packages(packages, filters)
result = []
unknown = []
filters.each do |filter|
found = []
packages.each do |package|
if package[:name].include?(filter) || package[:type] == filter || package[:desc].include?(filter)
found << package
end
end
result += found
if found.empty?
unknown << filter
end
end
unless unknown.empty?
raise ArgumentError, "Could not find matches for the following filters: #{unknown}"
end
result
end
def list_packages
packages_raw = `android list sdk -a --extended`
parse_android_packages(packages_raw)
end
def accept_license(cout, cin, timeout=3000)
start_at = Time.now
buffer = ''
loop do
if Time.now - start_at > timeout
raise 'Timeout while waiting to accept license'
end
begin
nextc = cout.getc
rescue
nextc = nil
end
return buffer if nextc.nil?
buffer << nextc
break if buffer =~ /Do you accept the license '.*' \[y\/n\]: /
end
cin.puts 'y'
buffer
end
def install_packages(packages)
ids = packages.collect {|package| package[:id]}
cmd = "android update sdk --no-ui -a --filter #{ids.join(',')}"
puts cmd
android_out, android_in, pid = PTY.spawn(cmd)
loop do
buffer = accept_license(android_out, android_in)
break if buffer.empty? # Reached the end
puts buffer
end
end
# The filters can match on (partial) package id, package type, or partial match of the first line of the package description.
filters = ['platform-tools', 'build-tools', 'Extras', 'Google Play Services']
packages = list_packages
filtered = filter_packages(packages, filters)
install_packages(filtered)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment