require 'net/https' namespace :repositories do def get_url_content(url, headers = {}) uri = URI.parse(url) req = Net::HTTP::Get.new(uri) headers.each do |header, value| req[header] = value end Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http| http.request(req) end.body end def branch(software_id, branches, version) name = version.match(/^v?(?\d+\.\d+)(\.\d+)?$/)[:branch] return branches[name] if branches.include?(name) branch = Branch.new( name: name, software_id: software_id ) branch.save branches[name] = branch.id branch.id end desc 'Update version from github repositories' task github: :environment do headers = { 'Accept' => 'application/vnd.github.v3+json' } headers['Authorization'] = "token #{Figaro.env.github_token}" if Figaro.env.github_token GithubRepository.all.each do |repo| begin software = Software.find(repo.software_id) branches = software.branches.all.map { |b| [b.name, b.id] }.to_h versions = software.branches.all.map { |b| b.versions.all.map(&:number) } tags = JSON.parse( get_url_content( "https://api.github.com/repos/#{repo.name}/tags", headers ) ) tags.each do |tag| next if versions.include?(tag['name']) branch_id = branch(software.id, branches, tag['name']) date = JSON.parse( get_url_content(tag['commit']['url'], headers) )['commit']['committer']['date'] puts Version.new( branch_id: branch_id, number: tag['name'], date: date ).save end rescue => e puts e.strace next end end end end