init project

This commit is contained in:
Jasder
2020-03-09 00:40:16 +08:00
commit 2937b2a94d
6549 changed files with 7215173 additions and 0 deletions

View File

@@ -0,0 +1,37 @@
require 'gitlab/version'
require 'gitlab/objectified_hash'
require 'gitlab/configuration'
require 'gitlab/error'
require 'gitlab/request'
require 'gitlab/api'
require 'gitlab/client'
module Gitlab
extend Configuration
# Alias for Gitlab::Client.new
#
# @return [Gitlab::Client]
def self.client(options={})
Gitlab::Client.new(options)
end
# Delegate to Gitlab::Client
def self.method_missing(method, *args, &block)
return super unless client.respond_to?(method)
client.send(method, *args, &block)
end
# Delegate to Gitlab::Client
def self.respond_to?(method)
return client.respond_to?(method) || super
end
# Returns an unsorted array of available client methods.
#
# @return [Array<Symbol>]
def self.actions
hidden = /endpoint|private_token|user_agent|sudo|get|post|put|\Adelete\z|validate|set_request_defaults/
(Gitlab::Client.instance_methods - Object.methods).reject {|e| e[hidden]}
end
end

View File

@@ -0,0 +1,17 @@
module Gitlab
# @private
class API < Request
# @private
attr_accessor(*Configuration::VALID_OPTIONS_KEYS)
# Creates a new API.
# @raise [Error:MissingCredentials]
def initialize(options={})
options = Gitlab.options.merge(options)
Configuration::VALID_OPTIONS_KEYS.each do |key|
send("#{key}=", options[key])
end
set_request_defaults @endpoint, @private_token, @sudo
end
end
end

View File

@@ -0,0 +1,47 @@
require 'gitlab'
require 'terminal-table/import'
require_relative 'cli_helpers'
require_relative 'shell'
class Gitlab::CLI
extend Helpers
def self.start(args)
command = args.shift.strip rescue 'help'
run(command, args)
end
def self.run(cmd, args=[])
case cmd
when 'help'
puts actions_table
when 'info'
endpoint = Gitlab.endpoint ? Gitlab.endpoint : 'not set'
private_token = Gitlab.private_token ? Gitlab.private_token : 'not set'
puts "Gitlab endpoint is #{endpoint}"
puts "Gitlab private token is #{private_token}"
puts "Ruby Version is #{RUBY_VERSION}"
puts "Gitlab Ruby Gem #{Gitlab::VERSION}"
when '-v', '--version'
puts "Gitlab Ruby Gem #{Gitlab::VERSION}"
when 'shell'
Gitlab::Shell.start
else
unless valid_command?(cmd)
puts "Unknown command. Run `gitlab help` for a list of available commands."
exit(1)
end
if args.any? && (args.last.start_with?('--only=') || args.last.start_with?('--except='))
command_args = args[0..-2]
else
command_args = args
end
confirm_command(cmd)
data = gitlab_helper(cmd, command_args) { exit(1) }
output_table(cmd, args, data)
end
end
end

View File

@@ -0,0 +1,175 @@
class Gitlab::CLI
# Defines methods related to CLI output and formatting.
module Helpers
extend self
# Returns filtered required fields.
#
# @return [Array]
def required_fields(args)
if args.any? && args.last.start_with?('--only=')
args.last.gsub('--only=', '').split(',')
else
[]
end
end
# Returns filtered excluded fields.
#
# @return [Array]
def excluded_fields(args)
if args.any? && args.last.start_with?('--except=')
args.last.gsub('--except=', '').split(',')
else
[]
end
end
# Confirms command is valid.
#
# @return [Boolean]
def valid_command?(cmd)
command = cmd.is_a?(Symbol) ? cmd : cmd.to_sym
Gitlab.actions.include?(command)
end
# Confirms command with a desctructive action.
#
# @return [String]
def confirm_command(cmd)
if cmd.start_with?('remove_') || cmd.start_with?('delete_')
puts "Are you sure? (y/n)"
if %w(y yes).include?($stdin.gets.to_s.strip.downcase)
puts 'Proceeding..'
else
puts 'Command aborted.'
exit(1)
end
end
end
# Table with available commands.
#
# @return [String]
def actions_table
client = Gitlab::Client.new(endpoint: '')
actions = Gitlab.actions
methods = []
actions.each do |action|
methods << {
name: action,
owner: client.method(action).owner.to_s.gsub('Gitlab::Client::', '')
}
end
owners = methods.map {|m| m[:owner]}.uniq.sort
methods_c = methods.group_by {|m| m[:owner]}
methods_c = methods_c.map {|_, v| [_, v.sort_by {|hv| hv[:name]}] }
methods_c = Hash[methods_c.sort_by(&:first).map {|k, v| [k, v]}]
max_column_length = methods_c.values.max_by(&:size).size
rows = max_column_length.times.map do |i|
methods_c.keys.map do |key|
methods_c[key][i] ? methods_c[key][i][:name] : ''
end
end
table do |t|
t.title = "Available commands (#{actions.size} total)"
t.headings = owners
rows.each do |row|
t.add_row row
end
end
end
# Decides which table to use.
#
# @return [String]
def output_table(cmd, args, data)
case data
when Gitlab::ObjectifiedHash
puts single_record_table(data, cmd, args)
when Array
puts multiple_record_table(data, cmd, args)
else
puts data.inspect
end
end
# Table for a single record.
#
# @return [String]
def single_record_table(data, cmd, args)
hash = data.to_h
keys = hash.keys.sort {|x, y| x.to_s <=> y.to_s }
keys = keys & required_fields(args) if required_fields(args).any?
keys = keys - excluded_fields(args)
table do |t|
t.title = "Gitlab.#{cmd} #{args.join(', ')}"
keys.each_with_index do |key, index|
case value = hash[key]
when Hash
value = 'Hash'
when nil
value = 'null'
end
t.add_row [key, value]
t.add_separator unless keys.size - 1 == index
end
end
end
# Table for multiple records.
#
# @return [String]
def multiple_record_table(data, cmd, args)
return 'No data' if data.empty?
arr = data.map(&:to_h)
keys = arr.first.keys.sort {|x, y| x.to_s <=> y.to_s }
keys = keys & required_fields(args) if required_fields(args).any?
keys = keys - excluded_fields(args)
table do |t|
t.title = "Gitlab.#{cmd} #{args.join(', ')}"
t.headings = keys
arr.each_with_index do |hash, index|
values = []
keys.each do |key|
case value = hash[key]
when Hash
value = 'Hash'
when nil
value = 'null'
end
values << value
end
t.add_row values
t.add_separator unless arr.size - 1 == index
end
end
end
# Helper function to call Gitlab commands with args.
def gitlab_helper(cmd, args=[])
begin
data = args.any? ? Gitlab.send(cmd, *args) : Gitlab.send(cmd)
rescue => e
puts e.message
yield if block_given?
end
data
end
end
end

View File

@@ -0,0 +1,18 @@
module Gitlab
# Wrapper for the Gitlab REST API.
class Client < API
Dir[File.expand_path('../client/*.rb', __FILE__)].each {|f| require f}
include Branches
include Groups
include Issues
include MergeRequests
include Milestones
include Notes
include Projects
include Repositories
include Snippets
include SystemHooks
include Users
end
end

View File

@@ -0,0 +1,79 @@
class Gitlab::Client
# Defines methods related to repositories.
module Branches
# Gets a list of project repositiory branches.
#
# @example
# Gitlab.branches(42)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def branches(project, options={})
get("/projects/#{project}/repository/branches", :query => options)
end
alias_method :repo_branches, :branches
# Gets information about a repository branch.
#
# @example
# Gitlab.branch(3, 'api')
# Gitlab.repo_branch(5, 'master')
#
# @param [Integer] project The ID of a project.
# @param [String] branch The name of the branch.
# @return [Gitlab::ObjectifiedHash]
def branch(project, branch)
get("/projects/#{project}/repository/branches/#{branch}")
end
alias_method :repo_branch, :branch
# Protects a repository branch.
#
# @example
# Gitlab.protect_branch(3, 'api')
# Gitlab.repo_protect_branch(5, 'master')
#
# @param [Integer] project The ID of a project.
# @param [String] branch The name of the branch.
# @return [Gitlab::ObjectifiedHash]
def protect_branch(project, branch)
put("/projects/#{project}/repository/branches/#{branch}/protect")
end
alias_method :repo_protect_branch, :protect_branch
# Unprotects a repository branch.
#
# @example
# Gitlab.unprotect_branch(3, 'api')
# Gitlab.repo_unprotect_branch(5, 'master')
#
# @param [Integer] project The ID of a project.
# @param [String] branch The name of the branch.
# @return [Gitlab::ObjectifiedHash]
def unprotect_branch(project, branch)
put("/projects/#{project}/repository/branches/#{branch}/unprotect")
end
alias_method :repo_unprotect_branch, :unprotect_branch
# Creates a repository branch. Requires Gitlab >= 6.8.x
#
# @example
# Gitlab.create_branch(3, 'api')
# Gitlab.repo_create_branch(5, 'master')
#
# @param [Integer] project The ID of a project.
# @param [String] branch The name of the new branch.
# @param [String] ref Create branch from commit sha or existing branch
# @return [Gitlab::ObjectifiedHash]
def create_branch(project, branch, ref)
post("/projects/#{project}/repository/branches",:body => {:branch_name => branch, :ref => ref})
end
alias_method :repo_create_branch, :create_branch
end
end

View File

@@ -0,0 +1,88 @@
class Gitlab::Client
# Defines methods related to groups.
module Groups
# Gets a list of groups.
#
# @example
# Gitlab.groups
# Gitlab.groups(:per_page => 40)
#
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def groups(options={})
get("/groups", :query => options)
end
# Gets a single group.
#
# @example
# Gitlab.group(42)
#
# @param [Integer] id The ID of a group.
# @return [Gitlab::ObjectifiedHash]
def group(id)
get("/groups/#{id}")
end
# Creates a new group.
#
# @param [String] name The name of a group.
# @param [String] path The path of a group.
# @return [Gitlab::ObjectifiedHash] Information about created group.
def create_group(name, path)
body = {:name => name, :path => path}
post("/groups", :body => body)
end
# Get a list of group members.
#
# @example
# Gitlab.group_members(1)
# Gitlab.group_members(1, :per_page => 40)
#
# @param [Integer] id The ID of a group.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def group_members(id, options={})
get("/groups/#{id}/members", :query => options)
end
# Adds a user to group.
#
# @example
# Gitlab.add_group_member(1, 2, 40)
#
# @param [Integer] team_id The group id to add a member to.
# @param [Integer] user_id The user id of the user to add to the team.
# @param [Integer] access_level Project access level.
# @return [Gitlab::ObjectifiedHash] Information about added team member.
def add_group_member(team_id, user_id, access_level)
post("/groups/#{team_id}/members", :body => {:user_id => user_id, :access_level => access_level})
end
# Removes user from user group.
#
# @example
# Gitlab.remove_group_member(1, 2)
#
# @param [Integer] team_id The group ID.
# @param [Integer] user_id The ID of a user.
# @return [Gitlab::ObjectifiedHash] Information about removed team member.
def remove_group_member(team_id, user_id)
delete("/groups/#{team_id}/members/#{user_id}")
end
# Transfers a project to a group
#
# @param [Integer] id The ID of a group.
# @param [Integer] project_id The ID of a project.
def transfer_project_to_group(id, project_id)
body = {:id => id, :project_id => project_id}
post("/groups/#{id}/projects/#{project_id}", :body => body)
end
end
end

View File

@@ -0,0 +1,92 @@
class Gitlab::Client
# Defines methods related to issues.
module Issues
# Gets a list of user's issues.
# Will return a list of project's issues if project ID passed.
#
# @example
# Gitlab.issues
# Gitlab.issues(5)
# Gitlab.issues(:per_page => 40)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def issues(project=nil, options={})
if project.to_i.zero?
get("/issues", :query => options)
else
get("/projects/#{project}/issues", :query => options)
end
end
# Gets a single issue.
#
# @example
# Gitlab.issue(5, 42)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of an issue.
# @return [Gitlab::ObjectifiedHash]
def issue(project, id)
get("/projects/#{project}/issues/#{id}")
end
# Creates a new issue.
#
# @param [Integer] project The ID of a project.
# @param [String] title The title of an issue.
# @param [Hash] options A customizable set of options.
# @option options [String] :description The description of an issue.
# @option options [Integer] :assignee_id The ID of a user to assign issue.
# @option options [Integer] :milestone_id The ID of a milestone to assign issue.
# @option options [String] :labels Comma-separated label names for an issue.
# @return [Gitlab::ObjectifiedHash] Information about created issue.
def create_issue(project, title, options={})
body = {:title => title}.merge(options)
post("/projects/#{project}/issues", :body => body)
end
# Updates an issue.
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of an issue.
# @param [Hash] options A customizable set of options.
# @option options [String] :title The title of an issue.
# @option options [String] :description The description of an issue.
# @option options [Integer] :assignee_id The ID of a user to assign issue.
# @option options [Integer] :milestone_id The ID of a milestone to assign issue.
# @option options [String] :labels Comma-separated label names for an issue.
# @option options [String] :state_event The state event of an issue ('close' or 'reopen').
# @return [Gitlab::ObjectifiedHash] Information about updated issue.
def edit_issue(project, id, options={})
put("/projects/#{project}/issues/#{id}", :body => options)
end
# Closes an issue.
#
# @example
# Gitlab.close_issue(3, 42)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of an issue.
# @return [Gitlab::ObjectifiedHash] Information about closed issue.
def close_issue(project, id)
put("/projects/#{project}/issues/#{id}", :body => {:state_event => 'close'})
end
# Reopens an issue.
#
# @example
# Gitlab.reopen_issue(3, 42)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of an issue.
# @return [Gitlab::ObjectifiedHash] Information about reopened issue.
def reopen_issue(project, id)
put("/projects/#{project}/issues/#{id}", :body => {:state_event => 'reopen'})
end
end
end

View File

@@ -0,0 +1,135 @@
class Gitlab::Client
# Defines methods related to merge requests.
module MergeRequests
# Gets a list of project merge requests.
#
# @example
# Gitlab.merge_requests(5)
# Gitlab.merge_requests(:per_page => 40)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def merge_requests(project, options={})
get("/projects/#{project}/merge_requests", :query => options)
end
# Gets a single merge request.
#
# @example
# Gitlab.merge_request(5, 36)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @return <Gitlab::ObjectifiedHash]
def merge_request(project, id)
get("/projects/#{project}/merge_request/#{id}")
end
# Creates a merge request.
#
# @example
# Gitlab.create_merge_request(5, 'New merge request',
# :source_branch => 'source_branch', :target_branch => 'target_branch')
# Gitlab.create_merge_request(5, 'New merge request',
# :source_branch => 'source_branch', :target_branch => 'target_branch', :assignee_id => 42)
#
# @param [Integer] project The ID of a project.
# @param [String] title The title of a merge request.
# @param [Hash] options A customizable set of options.
# @option options [String] :source_branch (required) The source branch name.
# @option options [String] :target_branch (required) The target branch name.
# @option options [Integer] :assignee_id (optional) The ID of a user to assign merge request.
# @return [Gitlab::ObjectifiedHash] Information about created merge request.
def create_merge_request(project, title, gid, options={})
check_attributes!(options, [:source_branch, :target_branch])
body = {:title => title}.merge(options)
post("/projects/#{project}/merge_requests?user_id=#{gid}", :body => body)
end
# Updates a merge request.
#
# @example
# Gitlab.update_merge_request(5, 42, :title => 'New title')
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @param [Hash] options A customizable set of options.
# @option options [String] :title The title of a merge request.
# @option options [String] :source_branch The source branch name.
# @option options [String] :target_branch The target branch name.
# @option options [Integer] :assignee_id The ID of a user to assign merge request.
# @option options [String] :state_event New state (close|reopen|merge).
# @return [Gitlab::ObjectifiedHash] Information about updated merge request.
def update_merge_request(project, id, gid, options={})
put("/projects/#{project}/merge_request/#{id}?user_id=#{gid}", :body => options)
end
# Adds a comment to a merge request.
#
# @example
# Gitlab.create_merge_request_comment(5, 1, "Awesome merge!")
# Gitlab.create_merge_request_comment('gitlab', 1, "Awesome merge!")
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @param [String] note The content of a comment.
# @return [Gitlab::ObjectifiedHash] Information about created merge request comment.
def create_merge_request_comment(project, id, note, gid)
post("/projects/#{project}/merge_request/#{id}/comments?user_id=#{gid}", :body => {:note => note})
end
# Get a list of merge request commits.
# Parameters:
# id (required) - The ID of a project
# merge_request_id (required) - The ID of MR
def merge_request_commits(project, id)
get("/projects/#{project}/merge_request/#{id}/commits")
end
# Shows information about the merge request including its files and changes. With GitLab 8.2 the return fields upvotes and downvotes are deprecated and always return 0.
# Parameters:
# id (required) - The ID of a project
# merge_request_id (required) - The ID of MR
def merge_request_changes(project, id)
get("/projects/#{project}/merge_request/#{id}/changes")
end
# Gets the comments on a merge request.
#
# @example
# Gitlab.merge_request_comments(5, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @return [Gitlab::ObjectifiedHash] The merge request's comments.
def merge_request_comments(project, id)
get("/projects/#{project}/merge_request/#{id}/comments")
end
# Accept a merge request.
#
# @example
# Gitlab.accept_pull_rquest(5, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a merge request.
# @return [Gitlab::ObjectifiedHash]
def accept_merge_rquest(project, id, gid)
put("/projects/#{project}/merge_request/#{id}/merge?user_id=#{gid}")
end
private
def check_attributes!(options, attrs)
attrs.each do |attr|
unless options.has_key?(attr) || options.has_key?(attr.to_s)
raise Gitlab::Error::MissingAttributes.new("Missing '#{attr}' parameter")
end
end
end
end
end

View File

@@ -0,0 +1,57 @@
class Gitlab::Client
# Defines methods related to milestones.
module Milestones
# Gets a list of project's milestones.
#
# @example
# Gitlab.milestones(5)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def milestones(project, options={})
get("/projects/#{project}/milestones", :query => options)
end
# Gets a single milestone.
#
# @example
# Gitlab.milestone(5, 36)
#
# @param [Integer, String] project The ID of a project.
# @param [Integer] id The ID of a milestone.
# @return [Gitlab::ObjectifiedHash]
def milestone(project, id)
get("/projects/#{project}/milestones/#{id}")
end
# Creates a new milestone.
#
# @param [Integer] project The ID of a project.
# @param [String] title The title of a milestone.
# @param [Hash] options A customizable set of options.
# @option options [String] :description The description of a milestone.
# @option options [String] :due_date The due date of a milestone.
# @return [Gitlab::ObjectifiedHash] Information about created milestone.
def create_milestone(project, title, options={})
body = {:title => title}.merge(options)
post("/projects/#{project}/milestones", :body => body)
end
# Updates a milestone.
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a milestone.
# @param [Hash] options A customizable set of options.
# @option options [String] :title The title of a milestone.
# @option options [String] :description The description of a milestone.
# @option options [String] :due_date The due date of a milestone.
# @option options [String] :state_event The state of a milestone ('close' or 'activate').
# @return [Gitlab::ObjectifiedHash] Information about updated milestone.
def edit_milestone(project, id, options={})
put("/projects/#{project}/milestones/#{id}", :body => options)
end
end
end

View File

@@ -0,0 +1,106 @@
class Gitlab::Client
# Defines methods related to notes.
module Notes
# Gets a list of projects notes.
#
# @example
# Gitlab.notes(5)
#
# @param [Integer] project The ID of a project.
# @return [Array<Gitlab::ObjectifiedHash>]
def notes(project)
get("/projects/#{project}/notes")
end
# Gets a list of notes for a issue.
#
# @example
# Gitlab.issue_notes(5, 10)
#
# @param [Integer] project The ID of a project.
# @param [Integer] issue The ID of an issue.
# @return [Array<Gitlab::ObjectifiedHash>]
def issue_notes(project, issue)
get("/projects/#{project}/issues/#{issue}/notes")
end
# Gets a list of notes for a snippet.
#
# @example
# Gitlab.snippet_notes(5, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] snippet The ID of a snippet.
# @return [Array<Gitlab::ObjectifiedHash>]
def snippet_notes(project, snippet)
get("/projects/#{project}/snippets/#{snippet}/notes")
end
# Gets a single wall note.
#
# @example
# Gitlab.note(5, 15)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a note.
# @return [Gitlab::ObjectifiedHash]
def note(project, id)
get("/projects/#{project}/notes/#{id}")
end
# Gets a single issue note.
#
# @example
# Gitlab.issue_note(5, 10, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] issue The ID of an issue.
# @param [Integer] id The ID of a note.
# @return [Gitlab::ObjectifiedHash]
def issue_note(project, issue, id)
get("/projects/#{project}/issues/#{issue}/notes/#{id}")
end
# Gets a single snippet note.
#
# @example
# Gitlab.snippet_note(5, 11, 3)
#
# @param [Integer] project The ID of a project.
# @param [Integer] snippet The ID of a snippet.
# @param [Integer] id The ID of an note.
# @return [Gitlab::ObjectifiedHash]
def snippet_note(project, snippet, id)
get("/projects/#{project}/snippets/#{snippet}/notes/#{id}")
end
# Creates a new wall note.
#
# @param [Integer] project The ID of a project.
# @param [String] body The body of a note.
# @return [Gitlab::ObjectifiedHash] Information about created note.
def create_note(project, body)
post("/projects/#{project}/notes", :body => {:body => body})
end
# Creates a new issue note.
#
# @param [Integer] project The ID of a project.
# @param [Integer] issue The ID of an issue.
# @param [String] body The body of a note.
# @return [Gitlab::ObjectifiedHash] Information about created note.
def create_issue_note(project, issue, body)
post("/projects/#{project}/issues/#{issue}/notes", :body => {:body => body})
end
# Creates a new snippet note.
#
# @param [Integer] project The ID of a project.
# @param [Integer] snippet The ID of a snippet.
# @param [String] body The body of a note.
# @return [Gitlab::ObjectifiedHash] Information about created note.
def create_snippet_note(project, snippet, body)
post("/projects/#{project}/snippets/#{snippet}/notes", :body => {:body => body})
end
end
end

View File

@@ -0,0 +1,328 @@
class Gitlab::Client
# Defines methods related to projects.
module Projects
# Gets a list of projects owned by the authenticated user.
#
# @example
# Gitlab.projects
#
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @option options [String] :scope Scope of projects. 'owned' for list of projects owned by the authenticated user, 'all' to get all projects (admin only)
# @return [Array<Gitlab::ObjectifiedHash>]
def projects(options={})
if (options[:scope])
get("/projects/#{options[:scope]}", :query => options)
else
get("/projects", :query => options)
end
end
def current_user_project(user_id, project_name)
get("/projects/current_user_projects?user_id=#{user_id}&project_name=#{project_name}")
end
# Gets information about a project.
#
# @example
# Gitlab.project(3)
# Gitlab.project('gitlab')
#
# @param [Integer, String] id The ID or name of a project.
# @return [Gitlab::ObjectifiedHash]
def project(id)
get("/projects/#{id}")
end
# Gets a list of project events.
#
# @example
# Gitlab.project_events(42)
# Gitlab.project_events('gitlab')
#
# @param [Integer, String] project The ID or name of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def project_events(project, options={})
get("/projects/#{project}/events", :query => options)
end
# Creates a new project.
#
# @example
# Gitlab.create_project('gitlab')
# Gitlab.create_project('viking', :description => 'Awesome project')
# Gitlab.create_project('Red', :wall_enabled => false)
#
# @param [String] name The name of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :description The description of a project.
# @option options [String] :default_branch The default branch of a project.
# @option options [String] :group_id The group in which to create a project.
# @option options [String] :namespace_id The namespace in which to create a project.
# @option options [Boolean] :wiki_enabled The wiki integration for a project (0 = false, 1 = true).
# @option options [Boolean] :wall_enabled The wall functionality for a project (0 = false, 1 = true).
# @option options [Boolean] :issues_enabled The issues integration for a project (0 = false, 1 = true).
# @option options [Boolean] :snippets_enabled The snippets integration for a project (0 = false, 1 = true).
# @option options [Boolean] :merge_requests_enabled The merge requests functionality for a project (0 = false, 1 = true).
# @option options [Boolean] :public The setting for making a project public (0 = false, 1 = true).
# @option options [Integer] :user_id The user/owner id of a project.
# @return [Gitlab::ObjectifiedHash] Information about created project.
def create_project(name, options={})
url = options[:user_id] ? "/projects/user/#{options[:user_id]}" : "/projects"
post(url, :body => {:name => name}.merge(options))
end
# Updates a project team member to a specified access level.
# id (required) - The ID of a project
# name (optional) - project name
# path (optional) - repository name for project
# description (optional) - short project description
# default_branch (optional)
# issues_enabled (optional)
# merge_requests_enabled (optional)
# wiki_enabled (optional)
# snippets_enabled (optional)
# public (optional) - if true same as setting visibility_level = 20
# visibility_level (optional)
def edit_project(id, name, path)
put("/projects/#{id}", :body => {:name => name, :path => path})
end
# Deletes a project.
#
# @example
# Gitlab.delete_project(4)
#
# @param [Integer, String] id The ID or name of a project.
# @return [Gitlab::ObjectifiedHash] Information about deleted project.
def delete_project(id)
delete("/projects/#{id}")
end
# Gets a list of project team members.
#
# @example
# Gitlab.team_members(42)
# Gitlab.team_members('gitlab')
#
# @param [Integer, String] project The ID or name of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :query The search query.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def team_members(project, options={})
get("/projects/#{project}/members", :query => options)
end
# Gets a project team member.
#
# @example
# Gitlab.team_member('gitlab', 2)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of a project team member.
# @return [Gitlab::ObjectifiedHash]
def team_member(project, id)
get("/projects/#{project}/members/#{id}")
end
# Adds a user to project team.
#
# @example
# Gitlab.add_team_member('gitlab', 2, 40)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of a user.
# @param [Integer] access_level The access level to project.
# @param [Hash] options A customizable set of options.
# @return [Gitlab::ObjectifiedHash] Information about added team member.
def add_team_member(project, id, access_level)
post("/projects/#{project}/members", :body => {:user_id => id, :access_level => access_level})
end
# Updates a team member's project access level.
#
# @example
# Gitlab.edit_team_member('gitlab', 3, 20)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of a user.
# @param [Integer] access_level The access level to project.
# @param [Hash] options A customizable set of options.
# @return [Array<Gitlab::ObjectifiedHash>] Information about updated team member.
def edit_team_member(project, id, access_level)
put("/projects/#{project}/members/#{id}", :body => {:access_level => access_level})
end
# Removes a user from project team.
#
# @example
# Gitlab.remove_team_member('gitlab', 2)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of a user.
# @param [Hash] options A customizable set of options.
# @return [Gitlab::ObjectifiedHash] Information about removed team member.
def remove_team_member(project, id)
delete("/projects/#{project}/members/#{id}")
end
# Gets a list of project hooks.
#
# @example
# Gitlab.project_hooks(42)
# Gitlab.project_hooks('gitlab')
#
# @param [Integer, String] project The ID or name of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def project_hooks(project, options={})
get("/projects/#{project}/hooks", :query => options)
end
# Gets a project hook.
#
# @example
# Gitlab.project_hook(42, 5)
# Gitlab.project_hook('gitlab', 5)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of a hook.
# @return [Gitlab::ObjectifiedHash]
def project_hook(project, id)
get("/projects/#{project}/hooks/#{id}")
end
# Adds a new hook to the project.
#
# @example
# Gitlab.add_project_hook(42, 'https://api.example.net/v1/webhooks/ci')
#
# @param [Integer, String] project The ID or name of a project.
# @param [String] url The hook URL.
# @param [Hash] options Events list (`{push_events: true, merge_requests_events: false}`).
# @return [Gitlab::ObjectifiedHash] Information about added hook.
def add_project_hook(project, url, options = {})
available_events = [:push_events, :merge_requests_events, :issues_events]
passed_events = available_events.select { |event| options[event] }
events = Hash[passed_events.map { |event| [event, options[event]] }]
post("/projects/#{project}/hooks", :body => {:url => url}.merge(events))
end
# Updates a project hook URL.
#
# @example
# Gitlab.edit_project_hook(42, 1, 'https://api.example.net/v1/webhooks/ci')
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of the hook.
# @param [String] url The hook URL.
# @return [Gitlab::ObjectifiedHash] Information about updated hook.
def edit_project_hook(project, id, url)
put("/projects/#{project}/hooks/#{id}", :body => {:url => url})
end
# Deletes a hook from project.
#
# @example
# Gitlab.delete_project_hook('gitlab', 4)
#
# @param [Integer, String] project The ID or name of a project.
# @param [String] id The ID of the hook.
# @return [Gitlab::ObjectifiedHash] Information about deleted hook.
def delete_project_hook(project, id)
delete("/projects/#{project}/hooks/#{id}")
end
# Forks a project into the user namespace of the authenticated user.
# @param [Integer] - The ID of the project to be forked
def fork(gpid, gid)
post ("/projects/fork/#{gpid}?user_id=#{gid}")
# post("/projects/fork/#{id}")
end
# Mark this project as forked from the other
#
# @example
# Gitlab.make_forked(42, 24)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] id The ID of the project it is forked from.
# @return [Gitlab::ObjectifiedHash] Information about the forked project.
def make_forked_from(project, id)
post("/projects/#{project}/fork/#{id}")
end
# Remove a forked_from relationship for a project.
#
# @example
# Gitlab.remove_forked(42)
#
# @param [Integer, String] project The ID or name of a project.
# @param [Integer] project The ID of the project it is forked from
# @return [Gitlab::ObjectifiedHash] Information about the forked project.
def remove_forked(project)
delete("/projects/#{project}/fork")
end
# Gets a project deploy keys.
#
# @example
# Gitlab.deploy_keys(42)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def deploy_keys(project, options={})
get("/projects/#{project}/keys", :query => options)
end
# Gets a single project deploy key.
#
# @example
# Gitlab.deploy_key(42, 1)
#
# @param [Integer, String] project The ID of a project.
# @param [Integer] id The ID of a deploy key.
# @return [Gitlab::ObjectifiedHash]
def deploy_key(project, id)
get("/projects/#{project}/keys/#{id}")
end
# Creates a new deploy key.
#
# @example
# Gitlab.create_deploy_key(42, 'My Key', 'Key contents')
#
# @param [Integer] project The ID of a project.
# @param [String] title The title of a deploy key.
# @param [String] key The content of a deploy key.
# @return [Gitlab::ObjectifiedHash] Information about created deploy key.
def create_deploy_key(project, title, key)
post("/projects/#{project}/keys", body: {title: title, key: key})
end
# Deletes a deploy key from project.
#
# @example
# Gitlab.delete_deploy_key(42, 1)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a deploy key.
# @return [Gitlab::ObjectifiedHash] Information about deleted deploy key.
def delete_deploy_key(project, id)
delete("/projects/#{project}/keys/#{id}")
end
end
end

View File

@@ -0,0 +1,213 @@
class Gitlab::Client
# Defines methods related to repositories.
module Repositories
def trees(project, options={})
get "/projects/#{project}/repository/tree", query: options
end
alias_method :repo_trees, :trees
def files(project, file_path, ref)
get "/projects/#{project}/repository/files", query: {file_path: file_path, ref: ref}
end
alias_method :repo_files, :files
def file_blob(project, options={})
get("/projects/#{project}/repository/blobs", query: options)
end
# Gets a list of project repository tags.
#
# @example
# Gitlab.tags(42)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def tags(project, options={})
get("/projects/#{project}/repository/tags", :query => options)
end
alias_method :repo_tags, :tags
# Creates a new project repository tag.
#
# @example
# Gitlab.create_tag(42,'new_tag','master')
#
# @param [Integer] project The ID of a project.
# @param [String] tag_name The name of the new tag.
# @param [String] ref The ref (commit sha, branch name, or another tag) the tag will point to.
# @return [Gitlab::ObjectifiedHash]
def create_tag(project, tag_name, ref)
post("/projects/#{project}/repository/tags", body: {tag_name: tag_name, ref: ref})
end
alias_method :repo_create_tag, :create_tag
# Gets a list of project commits.
#
# @example
# Gitlab.commits('viking')
# Gitlab.repo_commits('gitlab', :ref_name => 'api')
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :ref_name The branch or tag name of a project repository.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @option options [String] :search The obj of results's search value.
# @return [Array<Gitlab::ObjectifiedHash>]
def commits(project, options={})
get("/projects/#{project}/repository/commits", :query => options)
end
alias_method :repo_commits, :commits
# Gets a list of project commits.
#
# @example
# Gitlab.commits('viking')
# Gitlab.repo_commits('gitlab', :ref_name => 'api')
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :ref_name The branch or tag name of a project repository.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def commits_total_count(project, options={})
get("/projects/#{project}/repository/commits_total_count", :query => options)
end
alias_method :repo_commits, :commits_total_count
# Gets total project commits.
#
# @example
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :rev The branch or tag name of a project repository.
# @return [Hash<Gitlab::ObjectifiedHash>]
def user_static(project, options={})
get("/projects/#{project}/repository/user_static", :query => options)
end
def get_branch_commit_id(project, git_tree, ref_name)
get("/projects/#{project}/repository/get_branch_commit_id?git_tree=#{git_tree}&ref_name=#{ref_name}")
end
# Gets a specific commit identified by the commit hash or name of a branch or tag.
#
# @example
# Gitlab.commit(42, '6104942438c14ec7bd21c6cd5bd995272b3faff6')
# Gitlab.repo_commit(3, 'ed899a2f4b50b4370feeea94676502b42383c746')
#
# @param [Integer] project The ID of a project.
# @param [String] sha The commit hash or name of a repository branch or tag
# @return [Gitlab::ObjectifiedHash]
def commit(project, sha)
get("/projects/#{project}/repository/commits/#{sha}")
end
alias_method :repo_commit, :commit
# Gets a statics of project repository.
#
# @example
# Gitlab.commits('viking')
# Gitlab.repo_commits('gitlab', :ref_name => 'api')
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :ref_name The branch or tag name of a project repository.
# @option options [String] :creator The user name of a project repository.
# @option options [Integer] :period Statistics over time. 1:total 2one month 3one week
# @return [Array<Gitlab::ObjectifiedHash>]
def rep_stats(project, options={})
get("/projects/#{project}/repository/rep_stats", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
def rep_stats_week(project, options={})
get("/projects/#{project}/repository/rep_stats_week", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
def rep_stats_month(project, options={})
get("/projects/#{project}/repository/rep_stats_month", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
def rep_user_stats(project, options={})
get("/projects/#{project}/repository/rep_user_stats", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
# static all users
def admin_rep_stats_week(project, options={})
get("/projects/#{project}/repository/admin_rep_stats_week", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
def admin_rep_stats_month(project, options={})
get("/projects/#{project}/repository/admin_rep_stats_month", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
def admin_rep_stats_all(project, options={})
get("/projects/#{project}/repository/admin_rep_stats_all", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
# Gets a tree activities of project repository.
#
# @example
# Gitlab.commits('viking')
# Gitlab.repo_commits('gitlab', :ref_name => 'api')
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :ref_name The branch or tag name of a project repository.
# @option options [String] :creator The user name of a project repository.
# @option options [Integer] :period Statistics over time. 1:total 2one month 3one week
# @return [Array<Gitlab::ObjectifiedHash>]
def rep_last_changes(project, options={})
get("/projects/#{project}/repository/rep_last_changes", :query => options)
end
alias_method :repo_rep_stats, :rep_stats
# Get the diff of a commit in a project.
#
# @example
# Gitlab.commit_diff(42, '6104942438c14ec7bd21c6cd5bd995272b3faff6')
# Gitlab.repo_commit_diff(3, 'ed899a2f4b50b4370feeea94676502b42383c746')
#
# @param [Integer] project The ID of a project.
# @param [String] sha The name of a repository branch or tag or if not given the default branch.
# @return [Gitlab::ObjectifiedHash]
def commit_diff(project, sha)
get("/projects/#{project}/repository/commits/#{sha}/diff")
end
alias_method :repo_commit_diff, :commit_diff
# Get the commits count of each contributor in a project
# @param [Integer] project the ID fo a project.
# @return [Gitlab::ObjectifiedHash]
def contributors(project)
get("/projects/#{project}/repository/contributors")
end
# Get an archive of the repository
# @param [Integer] project the ID fo a project.
# sha (optional) - The commit SHA to download defaults to the tip of the default branch
# @return [Gitlab::ObjectifiedHash]
def project_archive(project, sha)
get("/projects/#{project}/repository/archive?sha=#{sha}")
end
# update file
def edit_file(project, username, options={})
put("/projects/#{project}/repository/files?username=#{username}", :body => options)
end
alias_method :repo_project_archive, :project_archive
end
end

View File

@@ -0,0 +1,86 @@
class Gitlab::Client
# Defines methods related to snippets.
module Snippets
# Gets a list of project's snippets.
#
# @example
# Gitlab.snippets(42)
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Gitlab::ObjectifiedHash]
def snippets(project, options={})
get("/projects/#{project}/snippets", :query => options)
end
# Gets information about a snippet.
#
# @example
# Gitlab.snippet(2, 14)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a snippet.
# @return [Gitlab::ObjectifiedHash]
def snippet(project, id)
get("/projects/#{project}/snippets/#{id}")
end
# Creates a new snippet.
#
# @example
# Gitlab.create_snippet(42, {:title => 'REST', :file_name => 'api.rb', :code => 'some code'})
#
# @param [Integer] project The ID of a project.
# @param [Hash] options A customizable set of options.
# @option options [String] :title (required) The title of a snippet.
# @option options [String] :file_name (required) The name of a snippet file.
# @option options [String] :code (required) The content of a snippet.
# @option options [String] :lifetime (optional) The expiration date of a snippet.
# @return [Gitlab::ObjectifiedHash] Information about created snippet.
def create_snippet(project, options={})
check_attributes!(options, [:title, :file_name, :code])
post("/projects/#{project}/snippets", :body => options)
end
# Updates a snippet.
#
# @example
# Gitlab.edit_snippet(42, 34, :file_name => 'README.txt')
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a snippet.
# @param [Hash] options A customizable set of options.
# @option options [String] :title The title of a snippet.
# @option options [String] :file_name The name of a snippet file.
# @option options [String] :code The content of a snippet.
# @option options [String] :lifetime The expiration date of a snippet.
# @return [Gitlab::ObjectifiedHash] Information about updated snippet.
def edit_snippet(project, id, options={})
put("/projects/#{project}/snippets/#{id}", :body => options)
end
# Deletes a snippet.
#
# @example
# Gitlab.delete_snippet(2, 14)
#
# @param [Integer] project The ID of a project.
# @param [Integer] id The ID of a snippet.
# @return [Gitlab::ObjectifiedHash] Information about deleted snippet.
def delete_snippet(project, id)
delete("/projects/#{project}/snippets/#{id}")
end
private
def check_attributes!(options, attrs)
attrs.each do |attr|
unless options.has_key?(attr) || options.has_key?(attr.to_s)
raise Gitlab::Error::MissingAttributes.new("Missing '#{attr}' parameter")
end
end
end
end
end

View File

@@ -0,0 +1,58 @@
class Gitlab::Client
# Defines methods related to system hooks.
module SystemHooks
# Gets a list of system hooks.
#
# @example
# Gitlab.hooks
# Gitlab.system_hooks
#
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def hooks(options={})
get("/hooks", query: options)
end
alias_method :system_hooks, :hooks
# Adds a new system hook.
#
# @example
# Gitlab.add_hook('http://example.com/hook')
# Gitlab.add_system_hook('https://api.example.net/v1/hook')
#
# @param [String] url The hook URL.
# @return [Gitlab::ObjectifiedHash]
def add_hook(url)
post("/hooks", :body => {:url => url})
end
alias_method :add_system_hook, :add_hook
# Tests a system hook.
#
# @example
# Gitlab.hook(3)
# Gitlab.system_hook(12)
#
# @param [Integer] id The ID of a system hook.
# @return [Array<Gitlab::ObjectifiedHash>]
def hook(id)
get("/hooks/#{id}")
end
alias_method :system_hook, :hook
# Deletes a new system hook.
#
# @example
# Gitlab.delete_hook(3)
# Gitlab.delete_system_hook(12)
#
# @param [Integer] id The ID of a system hook.
# @return [Gitlab::ObjectifiedHash]
def delete_hook(id)
delete("/hooks/#{id}")
end
alias_method :delete_system_hook, :delete_hook
end
end

View File

@@ -0,0 +1,131 @@
class Gitlab::Client
# Defines methods related to users.
module Users
# Gets a list of users.
#
# @example
# Gitlab.users
#
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def users(options={})
get("/users", :query => options)
end
# Gets information about a user.
# Will return information about an authorized user if no ID passed.
#
# @example
# Gitlab.user
# Gitlab.user(2)
#
# @param [Integer] id The ID of a user.
# @return [Gitlab::ObjectifiedHash]
def user(id=nil)
id.to_i.zero? ? get("/user") : get("/users/#{id}")
end
# Creates a new user.
# Requires authentication from an admin account.
#
# @param [String] email The email of a user.
# @param [String] password The password of a user.
# @param [Hash] options A customizable set of options.
# @option options [String] :name The name of a user. Defaults to email.
# @option options [String] :skype The skype of a user.
# @option options [String] :linkedin The linkedin of a user.
# @option options [String] :twitter The twitter of a user.
# @option options [Integer] :projects_limit The limit of projects for a user.
# @return [Gitlab::ObjectifiedHash] Information about created user.
def create_user(email, password, options={})
body = {:email => email, :password => password, :name => email}.merge(options)
post("/users", :body => body)
end
# Updates a user.
#
# @param [Integer] id The ID of a user.
# @param [Hash] options A customizable set of options.
# @option options [String] email The email of a user.
# @option options [String] password The password of a user.
# @option options [String] :name The name of a user. Defaults to email.
# @option options [String] :skype The skype of a user.
# @option options [String] :linkedin The linkedin of a user.
# @option options [String] :twitter The twitter of a user.
# @option options [Integer] :projects_limit The limit of projects for a user.
# @return [Gitlab::ObjectifiedHash] Information about created user.
def edit_user(user_id, options={})
put("/users/#{user_id}", :body => options)
end
def edit_user_email(user_id, options={})
put("/users/#{user_id}/email", :body => options)
end
def delete_user(user_id)
delete("/users/#{user_id}")
end
# Creates a new user session.
#
# @example
# Gitlab.session('jack@example.com', 'secret12345')
#
# @param [String] email The email of a user.
# @param [String] password The password of a user.
# @return [Gitlab::ObjectifiedHash]
# @note This method doesn't require private_token to be set.
def session(email, password)
post("/session", :body => {:email => email, :password => password})
end
# Gets a list of user's SSH keys.
#
# @example
# Gitlab.ssh_keys
#
# @param [Hash] options A customizable set of options.
# @option options [Integer] :page The page number.
# @option options [Integer] :per_page The number of results per page.
# @return [Array<Gitlab::ObjectifiedHash>]
def ssh_keys(options={})
get("/user/keys", :query => options)
end
# Gets information about SSH key.
#
# @example
# Gitlab.ssh_key(1)
#
# @param [Integer] id The ID of a user's SSH key.
# @return [Gitlab::ObjectifiedHash]
def ssh_key(id)
get("/user/keys/#{id}")
end
# Creates a new SSH key.
#
# @example
# Gitlab.create_ssh_key('key title', 'key body')
#
# @param [String] title The title of an SSH key.
# @param [String] key The SSH key body.
# @return [Gitlab::ObjectifiedHash] Information about created SSH key.
def create_ssh_key(title, key)
post("/user/keys", :body => {:title => title, :key => key})
end
# Deletes an SSH key.
#
# @example
# Gitlab.delete_ssh_key(1)
#
# @param [Integer] id The ID of a user's SSH key.
# @return [Gitlab::ObjectifiedHash] Information about deleted SSH key.
def delete_ssh_key(id)
delete("/user/keys/#{id}")
end
end
end

View File

@@ -0,0 +1,39 @@
module Gitlab
# Defines constants and methods related to configuration.
module Configuration
# An array of valid keys in the options hash when configuring a Gitlab::API.
VALID_OPTIONS_KEYS = [:endpoint, :private_token, :user_agent, :sudo, :httparty].freeze
# The user agent that will be sent to the API endpoint if none is set.
DEFAULT_USER_AGENT = "Gitlab Ruby Gem #{Gitlab::VERSION}".freeze
# @private
attr_accessor(*VALID_OPTIONS_KEYS)
# Sets all configuration options to their default values
# when this module is extended.
def self.extended(base)
base.reset
end
# Convenience method to allow configuration options to be set in a block.
def configure
yield self
end
# Creates a hash of options and their values.
def options
VALID_OPTIONS_KEYS.inject({}) do |option, key|
option.merge!(key => send(key))
end
end
# Resets all configuration options to the defaults.
def reset
self.endpoint = ENV['GITLAB_API_ENDPOINT']
self.private_token = ENV['GITLAB_API_PRIVATE_TOKEN']
self.sudo = nil
self.user_agent = DEFAULT_USER_AGENT
end
end
end

View File

@@ -0,0 +1,45 @@
module Gitlab
module Error
# Custom error class for rescuing from all Gitlab errors.
class Error < StandardError; end
# Raise when attributes are missing.
class MissingAttributes < Error; end
# Raised when API endpoint credentials not configured.
class MissingCredentials < Error; end
# Raised when impossible to parse response body.
class Parsing < Error; end
# Raised when API endpoint returns the HTTP status code 400.
class BadRequest < Error; end
# Raised when API endpoint returns the HTTP status code 401.
class Unauthorized < Error; end
# Raised when API endpoint returns the HTTP status code 403.
class Forbidden < Error; end
# Raised when API endpoint returns the HTTP status code 404.
class NotFound < Error; end
# Raised when API endpoint returns the HTTP status code 405.
class MethodNotAllowed < Error; end
# Raised when API endpoint returns the HTTP status code 406.
class DataNotAccepted < Error; end
# Raised when API endpoint returns the HTTP status code 409.
class Conflict < Error; end
# Raised when API endpoint returns the HTTP status code 500.
class InternalServerError < Error; end
# Raised when API endpoint returns the HTTP status code 502.
class BadGateway < Error; end
# Raised when API endpoint returns the HTTP status code 503.
class ServiceUnavailable < Error; end
end
end

View File

@@ -0,0 +1,44 @@
require 'gitlab'
require 'gitlab/cli_helpers'
module Gitlab::Help
extend Gitlab::CLI::Helpers
def self.get_help(methods,cmd=nil)
help = ''
if cmd.nil? || cmd == 'help'
help = actions_table
else
ri_cmd = `which ri`.chomp
if $? == 0
namespace = methods.select {|m| m[:name] === cmd }.map {|m| m[:owner]+'.'+m[:name] }.shift
if namespace
begin
ri_output = `#{ri_cmd} -T #{namespace} 2>&1`.chomp
if $? == 0
ri_output.gsub!(/#{cmd}\((.*?)\)/, cmd+' \1')
ri_output.gsub!(/Gitlab\./, 'gitlab> ')
ri_output.gsub!(/Gitlab\..+$/, '')
ri_output.gsub!(/\,\s?/, ' ')
help = ri_output
else
help = "Ri docs not found for #{namespace}, please install the docs to use 'help'"
end
rescue => e
puts e.message
end
else
help = "Unknown command: #{cmd}"
end
else
help = "'ri' tool not found in your PATH, please install it to use the help."
end
end
puts help
end
end

View File

@@ -0,0 +1,24 @@
module Gitlab
# Converts hashes to the objects.
class ObjectifiedHash
# Creates a new ObjectifiedHash object.
def initialize(hash)
@hash = hash
@data = hash.inject({}) do |data, (key,value)|
value = ObjectifiedHash.new(value) if value.is_a? Hash
data[key.to_s] = value
data
end
end
def to_hash
@hash
end
alias_method :to_h, :to_hash
# Delegate to ObjectifiedHash.
def method_missing(key)
@data.key?(key.to_s) ? @data[key.to_s] : nil
end
end
end

View File

@@ -0,0 +1,116 @@
require 'httparty'
require 'json'
module Gitlab
# @private
class Request
include HTTParty
format :json
headers 'Accept' => 'application/json'
parser Proc.new { |body, _| parse(body) }
attr_accessor :private_token
# Converts the response body to an ObjectifiedHash.
def self.parse(body)
body = decode(body)
if body.is_a? Hash
ObjectifiedHash.new body
elsif body.is_a? Array
body.collect! { |e| ObjectifiedHash.new(e) }
elsif body == true
body
else
raise Error::Parsing.new "Couldn't parse a response body"
end
end
# Decodes a JSON response into Ruby object.
def self.decode(response)
begin
JSON.load response
rescue JSON::ParserError
raise Error::Parsing.new "The response is not a valid JSON"
end
end
def get(path, options={})
set_httparty_config(options)
set_private_token_header(options)
validate self.class.get(path, options)
end
def post(path, options={})
set_httparty_config(options)
set_private_token_header(options, path)
validate self.class.post(path, options)
end
def put(path, options={})
set_httparty_config(options)
set_private_token_header(options)
validate self.class.put(path, options)
end
def delete(path, options={})
set_httparty_config(options)
set_private_token_header(options)
validate self.class.delete(path, options)
end
# Checks the response code for common errors.
# Returns parsed response for successful requests.
def validate(response)
# case response.code
# when 400; raise Error::BadRequest.new error_message(response)
# when 401; raise Error::Unauthorized.new error_message(response)
# when 403; raise Error::Forbidden.new error_message(response)
# when 404; raise Error::NotFound.new error_message(response)
# when 405; raise Error::MethodNotAllowed.new error_message(response)
# when 406; raise Error::DataNotAccepted.new error_message(response)
# when 409; raise Error::Conflict.new error_message(response)
# when 500; raise Error::InternalServerError.new error_message(response)
# when 502; raise Error::BadGateway.new error_message(response)
# when 503; raise Error::ServiceUnavailable.new error_message(response)
# end
response.parsed_response
end
# Sets a base_uri and default_params for requests.
# @raise [Error::MissingCredentials] if endpoint not set.
def set_request_defaults(endpoint, private_token, sudo=nil)
raise Error::MissingCredentials.new("Please set an endpoint to API") unless endpoint
@private_token = private_token
self.class.base_uri endpoint
self.class.default_params :sudo => sudo
self.class.default_params.delete(:sudo) if sudo.nil?
end
private
# Sets a PRIVATE-TOKEN header for requests.
# @raise [Error::MissingCredentials] if private_token not set.
def set_private_token_header(options, path=nil)
unless path == '/session'
raise Error::MissingCredentials.new("Please set a private_token for user") unless @private_token
options[:headers] = {'PRIVATE-TOKEN' => @private_token}
end
end
# Set HTTParty configuration
# @see https://github.com/jnunemaker/httparty
def set_httparty_config(options)
if self.httparty
options.merge!(self.httparty)
end
end
def error_message(response)
"Server responded with code #{response.code}, message: #{response.parsed_response.message}. " \
"Request URI: #{response.request.base_uri}#{response.request.path}"
end
end
end

View File

@@ -0,0 +1,51 @@
require 'gitlab'
require 'gitlab/help'
require 'gitlab/cli_helpers'
require 'readline'
class Gitlab::Shell
extend Gitlab::CLI::Helpers
def self.start
actions = Gitlab.actions
comp = proc { |s| actions.map(&:to_s).grep(/^#{Regexp.escape(s)}/) }
Readline.completion_proc = comp
Readline.completion_append_character = ' '
client = Gitlab::Client.new(endpoint: '')
while buf = Readline.readline('gitlab> ', true)
next if buf.nil? || buf.empty?
break if buf == 'exit'
buf = buf.scan(/["][^"]+["]|\S+/).map { |word| word.gsub(/^['"]|['"]$/,'') }
cmd = buf.shift
args = buf.count > 0 ? buf : []
if cmd == 'help'
methods = []
actions.each do |action|
methods << {
name: action.to_s,
owner: client.method(action).owner.to_s
}
end
args[0].nil? ? Gitlab::Help.get_help(methods) : Gitlab::Help.get_help(methods, args[0])
next
end
data = if actions.include?(cmd.to_sym)
confirm_command(cmd)
gitlab_helper(cmd, args)
else
"'#{cmd}' is not a valid command. See the 'help' for a list of valid commands."
end
output_table(cmd, args, data)
end
end
end

View File

@@ -0,0 +1,3 @@
module Gitlab
VERSION = "3.2.0"
end