1package gerrit
2
3import (
4	"fmt"
5)
6
7// ConfigService contains Config related REST endpoints
8//
9// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html
10type ConfigService struct {
11	client *Client
12}
13
14// TopMenuItemInfo entity contains information about a menu item in a top menu entry.
15type TopMenuItemInfo struct {
16	URL    string `json:"url"`
17	Name   string `json:"name"`
18	Target string `json:"target"`
19	ID     string `json:"id,omitempty"`
20}
21
22// AuthInfo entity contains information about the authentication configuration of the Gerrit server.
23type AuthInfo struct {
24	Type                     string   `json:"type"`
25	UseContributorAgreements bool     `json:"use_contributor_agreements,omitempty"`
26	EditableAccountFields    []string `json:"editable_account_fields"`
27	LoginURL                 string   `json:"login_url,omitempty"`
28	LoginText                string   `json:"login_text,omitempty"`
29	SwitchAccountURL         string   `json:"switch_account_url,omitempty"`
30	RegisterURL              string   `json:"register_url,omitempty"`
31	RegisterText             string   `json:"register_text,omitempty"`
32	EditFullNameURL          string   `json:"edit_full_name_url,omitempty"`
33	HTTPPasswordURL          string   `json:"http_password_url,omitempty"`
34	IsGitBasicAuth           bool     `json:"is_git_basic_auth,omitempty"`
35}
36
37// CacheInfo entity contains information about a cache.
38type CacheInfo struct {
39	Name       string       `json:"name,omitempty"`
40	Type       string       `json:"type"`
41	Entries    EntriesInfo  `json:"entries"`
42	AverageGet string       `json:"average_get,omitempty"`
43	HitRatio   HitRatioInfo `json:"hit_ratio"`
44}
45
46// CacheOperationInput entity contains information about an operation that should be executed on caches.
47type CacheOperationInput struct {
48	Operation string   `json:"operation"`
49	Caches    []string `json:"caches,omitempty"`
50}
51
52// ConfigCapabilityInfo entity contains information about a capability.type
53type ConfigCapabilityInfo struct {
54	ID   string `json:"id"`
55	Name string `json:"name"`
56}
57
58// HitRatioInfo entity contains information about the hit ratio of a cache.
59type HitRatioInfo struct {
60	Mem  int `json:"mem"`
61	Disk int `json:"disk,omitempty"`
62}
63
64// EntriesInfo entity contains information about the entries in a cache.
65type EntriesInfo struct {
66	Mem   int    `json:"mem,omitempty"`
67	Disk  int    `json:"disk,omitempty"`
68	Space string `json:"space,omitempty"`
69}
70
71// UserConfigInfo entity contains information about Gerrit configuration from the user section.
72type UserConfigInfo struct {
73	AnonymousCowardName string `json:"anonymous_coward_name"`
74}
75
76// TopMenuEntryInfo entity contains information about a top menu entry.
77type TopMenuEntryInfo struct {
78	Name  string            `json:"name"`
79	Items []TopMenuItemInfo `json:"items"`
80}
81
82// ThreadSummaryInfo entity contains information about the current threads.
83type ThreadSummaryInfo struct {
84	CPUs    int                       `json:"cpus"`
85	Threads int                       `json:"threads"`
86	Counts  map[string]map[string]int `json:"counts"`
87}
88
89// TaskSummaryInfo entity contains information about the current tasks.
90type TaskSummaryInfo struct {
91	Total    int `json:"total,omitempty"`
92	Running  int `json:"running,omitempty"`
93	Ready    int `json:"ready,omitempty"`
94	Sleeping int `json:"sleeping,omitempty"`
95}
96
97// TaskInfo entity contains information about a task in a background work queue.
98type TaskInfo struct {
99	ID         string `json:"id"`
100	State      string `json:"state"`
101	StartTime  string `json:"start_time"`
102	Delay      int    `json:"delay"`
103	Command    string `json:"command"`
104	RemoteName string `json:"remote_name,omitempty"`
105	Project    string `json:"project,omitempty"`
106}
107
108// SummaryInfo entity contains information about the current state of the server.
109type SummaryInfo struct {
110	TaskSummary   TaskSummaryInfo `json:"task_summary"`
111	MemSummary    MemSummaryInfo  `json:"mem_summary"`
112	ThreadSummary ThemeInfo       `json:"thread_summary"`
113	JVMSummary    JvmSummaryInfo  `json:"jvm_summary,omitempty"`
114}
115
116// SuggestInfo entity contains information about Gerrit configuration from the suggest section.
117type SuggestInfo struct {
118	From int `json:"from"`
119}
120
121// SSHdInfo entity contains information about Gerrit configuration from the sshd section.
122type SSHdInfo struct{}
123
124// ServerInfo entity contains information about the configuration of the Gerrit server.
125type ServerInfo struct {
126	Auth       AuthInfo          `json:"auth"`
127	Change     ChangeConfigInfo  `json:"change"`
128	Download   DownloadInfo      `json:"download"`
129	Gerrit     Info              `json:"gerrit"`
130	Gitweb     map[string]string `json:"gitweb,omitempty"`
131	Plugin     PluginConfigInfo  `json:"plugin"`
132	Receive    ReceiveInfo       `json:"receive,omitempty"`
133	SSHd       SSHdInfo          `json:"sshd,omitempty"`
134	Suggest    SuggestInfo       `json:"suggest"`
135	URLAliases map[string]string `json:"url_aliases,omitempty"`
136	User       UserConfigInfo    `json:"user"`
137}
138
139// ReceiveInfo entity contains information about the configuration of git-receive-pack behavior on the server.
140type ReceiveInfo struct {
141	EnableSignedPush bool `json:"enableSignedPush,omitempty"`
142}
143
144// PluginConfigInfo entity contains information about Gerrit extensions by plugins.
145type PluginConfigInfo struct {
146	// HasAvatars reports whether an avatar provider is registered.
147	HasAvatars bool `json:"has_avatars,omitempty"`
148}
149
150// MemSummaryInfo entity contains information about the current memory usage.
151type MemSummaryInfo struct {
152	Total     string `json:"total"`
153	Used      string `json:"used"`
154	Free      string `json:"free"`
155	Buffers   string `json:"buffers"`
156	Max       string `json:"max"`
157	OpenFiles int    `json:"open_files,omitempty"`
158}
159
160// JvmSummaryInfo entity contains information about the JVM.
161type JvmSummaryInfo struct {
162	VMVendor                string `json:"vm_vendor"`
163	VMName                  string `json:"vm_name"`
164	VMVersion               string `json:"vm_version"`
165	OSName                  string `json:"os_name"`
166	OSVersion               string `json:"os_version"`
167	OSArch                  string `json:"os_arch"`
168	User                    string `json:"user"`
169	Host                    string `json:"host,omitempty"`
170	CurrentWorkingDirectory string `json:"current_working_directory"`
171	Site                    string `json:"site"`
172}
173
174// Info entity contains information about Gerrit configuration from the gerrit section.
175type Info struct {
176	AllProjectsName string `json:"all_projects_name"`
177	AllUsersName    string `json:"all_users_name"`
178	DocURL          string `json:"doc_url,omitempty"`
179	ReportBugURL    string `json:"report_bug_url,omitempty"`
180	ReportBugText   string `json:"report_bug_text,omitempty"`
181}
182
183// GitwebInfo entity contains information about the gitweb configuration.
184type GitwebInfo struct {
185	URL  string         `json:"url"`
186	Type GitwebTypeInfo `json:"type"`
187}
188
189// GitwebTypeInfo entity contains information about the gitweb configuration.
190type GitwebTypeInfo struct {
191	Name          string `json:"name"`
192	Revision      string `json:"revision,omitempty"`
193	Project       string `json:"project,omitempty"`
194	Branch        string `json:"branch,omitempty"`
195	RootTree      string `json:"root_tree,omitempty"`
196	File          string `json:"file,omitempty"`
197	FileHistory   string `json:"file_history,omitempty"`
198	PathSeparator string `json:"path_separator"`
199	LinkDrafts    bool   `json:"link_drafts,omitempty"`
200	URLEncode     bool   `json:"url_encode,omitempty"`
201}
202
203// EmailConfirmationInput entity contains information for confirming an email address.
204type EmailConfirmationInput struct {
205	Token string `json:"token"`
206}
207
208// DownloadSchemeInfo entity contains information about a supported download scheme and its commands.
209type DownloadSchemeInfo struct {
210	URL             string            `json:"url"`
211	IsAuthRequired  bool              `json:"is_auth_required,omitempty"`
212	IsAuthSupported bool              `json:"is_auth_supported,omitempty"`
213	Commands        map[string]string `json:"commands"`
214	CloneCommands   map[string]string `json:"clone_commands"`
215}
216
217// DownloadInfo entity contains information about supported download options.
218type DownloadInfo struct {
219	Schemes  map[string]DownloadSchemeInfo `json:"schemes"`
220	Archives []string                      `json:"archives"`
221}
222
223// ChangeConfigInfo entity contains information about Gerrit configuration from the change section.
224type ChangeConfigInfo struct {
225	AllowDrafts      bool   `json:"allow_drafts,omitempty"`
226	LargeChange      int    `json:"large_change"`
227	ReplyLabel       string `json:"reply_label"`
228	ReplyTooltip     string `json:"reply_tooltip"`
229	UpdateDelay      int    `json:"update_delay"`
230	SubmitWholeTopic bool   `json:"submit_whole_topic"`
231}
232
233// ListCachesOptions specifies the different output formats.
234//
235// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-caches
236type ListCachesOptions struct {
237	// Format specifies the different output formats.
238	Format string `url:"format,omitempty"`
239}
240
241// SummaryOptions specifies the different options for the GetSummary call.
242//
243// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-summary
244type SummaryOptions struct {
245	// JVM includes a JVM summary.
246	JVM bool `url:"jvm,omitempty"`
247	// GC requests a Java garbage collection before computing the information about the Java memory heap.
248	GC bool `url:"gc,omitempty"`
249}
250
251// GetVersion returns the version of the Gerrit server.
252//
253// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-version
254func (s *ConfigService) GetVersion() (string, *Response, error) {
255	u := "config/server/version"
256	return getStringResponseWithoutOptions(s.client, u)
257}
258
259// GetServerInfo returns the information about the Gerrit server configuration.
260//
261// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-info
262func (s *ConfigService) GetServerInfo() (*ServerInfo, *Response, error) {
263	u := "config/server/info"
264
265	req, err := s.client.NewRequest("GET", u, nil)
266	if err != nil {
267		return nil, nil, err
268	}
269
270	v := new(ServerInfo)
271	resp, err := s.client.Do(req, v)
272	if err != nil {
273		return nil, resp, err
274	}
275
276	return v, resp, err
277}
278
279// ListCaches lists the caches of the server. Caches defined by plugins are included.
280// The caller must be a member of a group that is granted one of the following capabilities:
281// * View Caches
282// * Maintain Server
283// * Administrate Server
284// The entries in the map are sorted by cache name.
285//
286// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-caches
287func (s *ConfigService) ListCaches(opt *ListCachesOptions) (*map[string]CacheInfo, *Response, error) {
288	u := "config/server/caches/"
289
290	u, err := addOptions(u, opt)
291	if err != nil {
292		return nil, nil, err
293	}
294
295	req, err := s.client.NewRequest("GET", u, nil)
296	if err != nil {
297		return nil, nil, err
298	}
299
300	v := new(map[string]CacheInfo)
301	resp, err := s.client.Do(req, v)
302	if err != nil {
303		return nil, resp, err
304	}
305
306	return v, resp, err
307}
308
309// GetCache retrieves information about a cache.
310// The caller must be a member of a group that is granted one of the following capabilities:
311// * View Caches
312// * Maintain Server
313// * Administrate Server
314//
315// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-cache
316func (s *ConfigService) GetCache(cacheName string) (*CacheInfo, *Response, error) {
317	u := fmt.Sprintf("config/server/caches/%s", cacheName)
318
319	req, err := s.client.NewRequest("GET", u, nil)
320	if err != nil {
321		return nil, nil, err
322	}
323
324	v := new(CacheInfo)
325	resp, err := s.client.Do(req, v)
326	if err != nil {
327		return nil, resp, err
328	}
329
330	return v, resp, err
331}
332
333// GetSummary retrieves a summary of the current server state.
334// The caller must be a member of a group that is granted the Administrate Server capability.
335//
336// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-summary
337func (s *ConfigService) GetSummary(opt *SummaryOptions) (*SummaryInfo, *Response, error) {
338	u := "config/server/summary"
339
340	u, err := addOptions(u, opt)
341	if err != nil {
342		return nil, nil, err
343	}
344
345	req, err := s.client.NewRequest("GET", u, nil)
346	if err != nil {
347		return nil, nil, err
348	}
349
350	v := new(SummaryInfo)
351	resp, err := s.client.Do(req, v)
352	if err != nil {
353		return nil, resp, err
354	}
355
356	return v, resp, err
357}
358
359// ListCapabilities lists the capabilities that are available in the system.
360// There are two kinds of capabilities: core and plugin-owned capabilities.
361// The entries in the map are sorted by capability ID.
362//
363// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-capabilities
364func (s *ConfigService) ListCapabilities() (*map[string]ConfigCapabilityInfo, *Response, error) {
365	u := "config/server/capabilities"
366
367	req, err := s.client.NewRequest("GET", u, nil)
368	if err != nil {
369		return nil, nil, err
370	}
371
372	v := new(map[string]ConfigCapabilityInfo)
373	resp, err := s.client.Do(req, v)
374	if err != nil {
375		return nil, resp, err
376	}
377
378	return v, resp, err
379}
380
381// ListTasks lists the tasks from the background work queues that the Gerrit daemon is currently performing, or will perform in the near future.
382// Gerrit contains an internal scheduler, similar to cron, that it uses to queue and dispatch both short and long term tasks.
383// Tasks that are completed or canceled exit the queue very quickly once they enter this state, but it can be possible to observe tasks in these states.
384// End-users may see a task only if they can also see the project the task is associated with.
385// Tasks operating on other projects, or that do not have a specific project, are hidden.
386//
387// The caller must be a member of a group that is granted one of the following capabilities:
388// * View Queue
389// * Maintain Server
390// * Administrate Server
391//
392// The entries in the list are sorted by task state, remaining delay and command.
393//
394// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#list-tasks
395func (s *ConfigService) ListTasks() (*[]TaskInfo, *Response, error) {
396	u := "config/server/tasks"
397
398	req, err := s.client.NewRequest("GET", u, nil)
399	if err != nil {
400		return nil, nil, err
401	}
402
403	v := new([]TaskInfo)
404	resp, err := s.client.Do(req, v)
405	if err != nil {
406		return nil, resp, err
407	}
408
409	return v, resp, err
410}
411
412// GetTask retrieves a task from the background work queue that the Gerrit daemon is currently performing, or will perform in the near future.
413// End-users may see a task only if they can also see the project the task is associated with.
414// Tasks operating on other projects, or that do not have a specific project, are hidden.
415//
416// The caller must be a member of a group that is granted one of the following capabilities:
417// * View Queue
418// * Maintain Server
419// * Administrate Server
420//
421// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-task
422func (s *ConfigService) GetTask(taskID string) (*TaskInfo, *Response, error) {
423	u := fmt.Sprintf("config/server/tasks/%s", taskID)
424
425	req, err := s.client.NewRequest("GET", u, nil)
426	if err != nil {
427		return nil, nil, err
428	}
429
430	v := new(TaskInfo)
431	resp, err := s.client.Do(req, v)
432	if err != nil {
433		return nil, resp, err
434	}
435
436	return v, resp, err
437}
438
439// GetTopMenus returns the list of additional top menu entries.
440//
441// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#get-top-menus
442func (s *ConfigService) GetTopMenus() (*[]TopMenuEntryInfo, *Response, error) {
443	u := "config/server/top-menus"
444
445	req, err := s.client.NewRequest("GET", u, nil)
446	if err != nil {
447		return nil, nil, err
448	}
449
450	v := new([]TopMenuEntryInfo)
451	resp, err := s.client.Do(req, v)
452	if err != nil {
453		return nil, resp, err
454	}
455
456	return v, resp, err
457}
458
459// ConfirmEmail confirms that the user owns an email address.
460// The email token must be provided in the request body inside an EmailConfirmationInput entity.
461//
462// The response is “204 No Content”.
463// If the token is invalid or if it’s the token of another user the request fails and the response is “422 Unprocessable Entity”.
464//
465// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#confirm-email
466func (s *ConfigService) ConfirmEmail(input *EmailConfirmationInput) (*Response, error) {
467	u := "config/server/email.confirm"
468
469	req, err := s.client.NewRequest("PUT", u, input)
470	if err != nil {
471		return nil, err
472	}
473
474	return s.client.Do(req, nil)
475}
476
477// CacheOperations executes a cache operation that is specified in the request body in a CacheOperationInput entity.
478//
479// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#cache-operations
480func (s *ConfigService) CacheOperations(input *CacheOperationInput) (*Response, error) {
481	u := "config/server/caches/"
482
483	req, err := s.client.NewRequest("POST", u, input)
484	if err != nil {
485		return nil, err
486	}
487
488	return s.client.Do(req, nil)
489}
490
491// FlushCache flushes a cache.
492// The caller must be a member of a group that is granted one of the following capabilities:
493//
494// * Flush Caches (any cache except "web_sessions")
495// * Maintain Server (any cache including "web_sessions")
496// * Administrate Server (any cache including "web_sessions")
497//
498// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#flush-cache
499func (s *ConfigService) FlushCache(cacheName string, input *CacheOperationInput) (*Response, error) {
500	u := fmt.Sprintf("config/server/caches/%s/flush", cacheName)
501
502	req, err := s.client.NewRequest("POST", u, input)
503	if err != nil {
504		return nil, err
505	}
506
507	return s.client.Do(req, nil)
508}
509
510// DeleteTask kills a task from the background work queue that the Gerrit daemon is currently performing, or will perform in the near future.
511// The caller must be a member of a group that is granted one of the following capabilities:
512//
513// * Kill Task
514// * Maintain Server
515// * Administrate Server
516//
517// End-users may see a task only if they can also see the project the task is associated with.
518// Tasks operating on other projects, or that do not have a specific project, are hidden.
519// Members of a group granted one of the following capabilities may view all tasks:
520//
521// * View Queue
522// * Maintain Server
523// * Administrate Server
524//
525// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-config.html#delete-task
526func (s *ConfigService) DeleteTask(taskID string) (*Response, error) {
527	u := fmt.Sprintf("config/server/tasks/%s", taskID)
528	return s.client.DeleteRequest(u, nil)
529}
530