From 55f322085d0507640366b7a774fe7819771ff54b Mon Sep 17 00:00:00 2001 From: Jacopo Date: Sat, 18 Nov 2017 15:06:55 +0100 Subject: Adds ordering to projects contributors in API Allows ordering in GET api/v4/projects/:project_id/repository/contributors through `order_by` and `sort` params. The available `order_by` options are: name|email|commits. The available `sort` options are: asc|desc. --- app/models/commit.rb | 14 ++++++++++++++ app/models/repository.rb | 9 +++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) (limited to 'app') diff --git a/app/models/commit.rb b/app/models/commit.rb index 307e4fcedfe..13c31111134 100644 --- a/app/models/commit.rb +++ b/app/models/commit.rb @@ -52,6 +52,20 @@ class Commit diffs.reduce(0) { |sum, d| sum + Gitlab::Git::Util.count_lines(d.diff) } end + def order_by(collection:, order_by:, sort:) + return collection unless %w[email name commits].include?(order_by) + return collection unless %w[asc desc].include?(sort) + + collection.sort do |a, b| + operands = [a, b].tap { |o| o.reverse! if sort == 'desc' } + + attr1, attr2 = operands.first.public_send(order_by), operands.second.public_send(order_by) # rubocop:disable PublicSend + + # use case insensitive comparison for string values + order_by.in?(%w[email name]) ? attr1.casecmp(attr2) : attr1 <=> attr2 + end + end + # Truncate sha to 8 characters def truncate_sha(sha) sha[0..MIN_SHA_LENGTH] diff --git a/app/models/repository.rb b/app/models/repository.rb index d1ae3304e4a..c01188315fd 100644 --- a/app/models/repository.rb +++ b/app/models/repository.rb @@ -701,10 +701,14 @@ class Repository end end - def contributors + # Params: + # + # order_by: name|email|commits + # sort: asc|desc default: 'asc' + def contributors(order_by: nil, sort: 'asc') commits = self.commits(nil, limit: 2000, offset: 0, skip_merges: true) - commits.group_by(&:author_email).map do |email, commits| + commits = commits.group_by(&:author_email).map do |email, commits| contributor = Gitlab::Contributor.new contributor.email = email @@ -718,6 +722,7 @@ class Repository contributor end + Commit.order_by(collection: commits, order_by: order_by, sort: sort) end def refs_contains_sha(ref_type, sha) -- cgit v1.2.1