|
| 1 | +class UserBench |
| 2 | + attr_reader :errors, :name, :url, :sha, :sha2, :commits |
| 3 | + |
| 4 | + def initialize(name, url, sha, sha2 = nil) |
| 5 | + @name = name&.strip |
| 6 | + @url = url&.strip |
| 7 | + @sha = sha&.strip |
| 8 | + @sha2 = sha2&.strip |
| 9 | + @errors = [] |
| 10 | + @commits = [] |
| 11 | + @client = Octokit::Client.new(access_token: Rails.application.secrets.github_api_token) |
| 12 | + end |
| 13 | + |
| 14 | + def validate! |
| 15 | + errors.push(err('missing_name')) if name.blank? |
| 16 | + errors.push(err('missing_url')) if url.blank? |
| 17 | + errors.push(err('missing_sha')) if sha.blank? |
| 18 | + return if !valid? |
| 19 | + |
| 20 | + errors.push(err('name_already_taken')) if name_taken? |
| 21 | + errors.push(err('bad_url')) unless valid_url? |
| 22 | + errors.push(err('unallowed_characters', name: name)) unless valid_name? |
| 23 | + |
| 24 | + return if !valid? |
| 25 | + |
| 26 | + validate_sha(sha) |
| 27 | + validate_sha(sha2) if sha2.present? |
| 28 | + end |
| 29 | + |
| 30 | + def valid? |
| 31 | + @errors.size == 0 |
| 32 | + end |
| 33 | + |
| 34 | + def run |
| 35 | + repo = Repo.find_or_create_by!( |
| 36 | + name: 'ruby', |
| 37 | + url: 'https://github.com/tgxworld/ruby', |
| 38 | + organization: Organization.find_or_create_by!( |
| 39 | + name: 'ruby', |
| 40 | + url: 'https://github.com/tgxworld/', |
| 41 | + ) |
| 42 | + ) |
| 43 | + BenchmarkType.create!( |
| 44 | + category: name, |
| 45 | + script_url: url, |
| 46 | + from_user: true, |
| 47 | + repo: repo |
| 48 | + ) |
| 49 | + |
| 50 | + RunUserBench.perform_later(name, url, commits.last.commit.committer.date.iso8601, commits.first.sha) |
| 51 | + end |
| 52 | + |
| 53 | + private |
| 54 | + |
| 55 | + def valid_url? |
| 56 | + uri = URI.parse(url) |
| 57 | + URI::HTTP === uri || URI::HTTPS === uri |
| 58 | + rescue URI::InvalidURIError |
| 59 | + false |
| 60 | + end |
| 61 | + |
| 62 | + def name_taken? |
| 63 | + BenchmarkType.exists?(category: name) |
| 64 | + end |
| 65 | + |
| 66 | + def valid_name? |
| 67 | + name.match?(/^[a-zA-Z0-9\-_]+$/) |
| 68 | + end |
| 69 | + |
| 70 | + def validate_sha(sha) |
| 71 | + commit = @client.commit('ruby/ruby', sha) |
| 72 | + add_commit(commit) |
| 73 | + rescue Octokit::UnprocessableEntity |
| 74 | + errors.push(err('bad_sha', sha: sha)) |
| 75 | + end |
| 76 | + |
| 77 | + def add_commit(commit) |
| 78 | + if commits.all? { |c| c.sha != commit.sha } |
| 79 | + commits.push(commit) |
| 80 | + commits.sort_by! { |c| c.commit.committer.date } |
| 81 | + end |
| 82 | + end |
| 83 | + |
| 84 | + def err(key, *args) |
| 85 | + I18n.t("user_scripts.errors.#{key}", *args) |
| 86 | + end |
| 87 | +end |
0 commit comments