UNPKG

19.7 kBMarkdownView Raw
1[![npm @latest](https://img.shields.io/npm/v/gitlab.svg)](https://www.npmjs.com/package/gitlab)
2[![npm downloads](https://img.shields.io/npm/dt/gitlab.svg)](https://www.npmjs.com/package/gitlab)
3[![dependencies Status](https://david-dm.org/jdalrymple/node-gitlab/status.svg)](https://david-dm.org/jdalrymple/node-gitlab)
4[![devDependencies Status](https://david-dm.org/jdalrymple/node-gitlab/dev-status.svg)](https://david-dm.org/jdalrymple/node-gitlab?type=dev)
5[![Greenkeeper badge](https://badges.greenkeeper.io/jdalrymple/node-gitlab.svg)](https://greenkeeper.io/)
6[![Code Climate](https://codeclimate.com/github/jdalrymple/node-gitlab/badges/gpa.svg)](https://codeclimate.com/github/jdalrymple/node-gitlab)
7[![Build Status](https://img.shields.io/travis/jdalrymple/node-gitlab/master.svg)](https://travis-ci.org/jdalrymple/node-gitlab)
8[![Coverage](https://img.shields.io/codecov/c/github/jdalrymple/node-gitlab/master.svg)](https://codecov.io/gh/jdalrymple/node-gitlab)
9[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
10[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
11[![Code Style: Prettier](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)
12[![Install Size](https://packagephobia.now.sh/badge?p=gitlab)](https://packagephobia.now.sh/result?p=gitlab)
13[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/jdalrymple/node-gitlab/blob/master/LICENSE.md)
14
15# node-gitlab
16
17🤖 [GitLab](https://gitlab.com/gitlab-org/gitlab/) API NodeJS library with full support of all the [Gitlab API](https://gitlab.com/gitlab-org/gitlab/tree/master/doc/api) services.
18
19## Table of Contents
20
21- [Install](#install)
22- [Getting Started](#getting-started)
23 - [CLI Support](#cli-support)
24 - [Browser Support](#browser-support)
25- [Docs](#docs)
26 - [Supported APIs](#supported-apis)
27 - [Bundle Imports](#bundle-imports)
28 - [Examples](#examples)
29 - [Pagination](#pagination)
30 - [Sudo](#sudo)
31 - [Custom Request Libraries](#custom-request-libraries)
32 - [Misc](#misc)
33- [Development](#development)
34- [Testing](#testing)
35- [Contributors](#contributors)
36- [License](#licence)
37- [Changelog](#changelog)
38
39## Install
40
41```bash
42# Install from npm
43npm install gitlab
44```
45
46## Getting Started
47
48Instantiate the library using a basic token created in your [Gitlab Profile](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html)
49
50```javascript
51// ES6 (>=node 10.16.0 LTS)
52import { Gitlab } from 'gitlab'; // All Resources
53import { Projects } from 'gitlab'; // Just the Project Resource
54//...etc
55
56// ES5, assuming native or polyfilled Promise is available
57const { Gitlab } = require('gitlab');
58```
59
60```javascript
61const api = new Gitlab({
62 token: 'personaltoken',
63});
64```
65
66Available instantiating options:
67
68| Name | Optional | Default | Description |
69| -------------------- | -------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
70| `host` | Yes | `https://gitlab.com` | Gitlab Instance Host URL |
71| `token` | No\* | N/A | Personal Token. Required (one of the three tokens are required) |
72| `oauthToken` | No\* | N/A | OAuth Token. Required (one of the three tokens are required) |
73| `jobToken` | No\* | N/A | CI Job Token. Required (one of the three tokens are required) |
74| `rejectUnauthorized` | Yes | `true` | Http Certificate setting, Only applies to HTTPS hosts urls |
75| `sudo` | Yes | `false` | [Sudo](https://docs.gitlab.com/ee/api/#sudo) query parameter |
76| `version` | Yes | `4` | API Version ID |
77| `camelize` | Yes | `false` | Camelizes all response body keys |
78| `requester` | Yes | [KyRequester.ts](./src/infrastructure/KyRequester.ts) | Request Library Wrapper. Currently wraps Ky. |
79| `requestTimeout` | Yes | `300000` | Request Library Timeout in ms |
80| `profileToken` | Yes | N/A | [Requests Profiles Token](https://docs.gitlab.com/ee/administration/monitoring/performance/request_profiling.html) |
81| `profileMode` | Yes | `execution` | [Requests Profiles Token](https://docs.gitlab.com/ee/administration/monitoring/performance/request_profiling.html) |
82
83### CLI Support
84
85The CLI export functions in a similar manner, following the pattern:
86
87```bash
88gitlab [service name] [method name] --arg1 --arg2 --arg3
89```
90
91Where `service name` is any of the supported API names, `method name` is any of the supported commands on that API service (See source for exceptions, but generally all, show, remove, update) and `--arg1...--arg3` are any of the arguments you would normally supply to the function. The names of the args should match the names in the method headers **EXCEPT** all the optional arguments whose names should match what the GitLab API docs request.
92
93There is one small exception with the instantiating arguments, however, which must be supplied using a `gl` prefix. ie.
94
95```bash
96# To get all the projects
97gitlab projects all --gl-token="personaltoken"
98
99# To get a project with id = 2
100gitlab projects show --gl-token="personaltoken" --projectId=2
101```
102
103To reduce the annoyance of having to pass those configuration properties each time, it is also possible to pass the token and host information through environment variables in the form of `GITLAB_[option name]` ie:
104
105```bash
106GITLAB_HOST=http://example.com
107GITLAB_TOKEN=personaltoken
108```
109
110This could be set globally or using a [.env](https://github.com/motdotla/dotenv#readme) file in the project folder.
111
112### Browser Support
113
114The library is exported as `gitlab` and can be used by simply adding this script to your html file:
115
116```html
117<script src="node_modules/gitlab/dist/index.browser.js" />
118<script>
119 const { Gitlab } = gitlab;
120
121 const api = new Gitlab({
122 token: 'personaltoken',
123 });
124
125 //etc
126</script>
127```
128
129## Docs
130
131Although there are the [official docs](https://gitlab.com/gitlab-org/gitlab/tree/master/doc/api) for the API, there are some extra goodies offered by this package! After the 3.0.0 release, the next large project will be putting together proper documentation for these goodies [#39]! Stay tuned!!
132
133### Supported APIs
134
135The API's that are currently supported are:
136
137```
138// General
139ApplicationSettings
140BroadcastMessages
141Events
142FeatureFlags
143GeoNodes
144GitignoreTemplates
145GitLabCIYMLTemplates
146Keys
147License
148LicenceTemplates
149Lint
150Markdown
151Namespaces
152NotificationSettings
153PagesDomains
154Search
155SidekiqMetrics
156Snippets
157SystemHooks
158Version
159Wikis
160
161// Groups
162Groups
163GroupAccessRequests
164GroupBadges
165GroupCustomAttributes
166GroupIssueBoards
167GroupMembers
168GroupMilestones
169GroupProjects
170GroupVariables
171GroupLabels
172Epics
173EpicIssues
174EpicNotes
175EpicDiscussions
176
177// Projects
178Branches
179Commits
180CommitDiscussions
181ContainerRegistry
182DeployKeys
183Deployments
184Environments
185Issues
186IssueAwardEmojis
187IssueNotes
188IssueDiscussions
189IssuesStatistics
190Jobs
191Labels
192MergeRequests
193MergeRequestAwardEmojis
194MergeRequestDiscussions
195MergeRequestNotes
196Packages
197Pipelines
198PipelineSchedules
199PipelineScheduleVariables
200Projects
201ProjectAccessRequests
202ProjectBadges
203ProjectCustomAttributes
204ProjectImportExport
205ProjectIssueBoards
206ProjectHooks
207ProjectMembers
208ProjectMilestones
209ProjectSnippets
210ProjectSnippetNotes
211ProjectSnippetDiscussions
212ProjectSnippetAwardEmojis
213ProtectedBranches
214ProtectedTags
215ProjectVariables
216PushRules
217Releases
218ReleaseLinks
219Repositories
220RepositoryFiles
221Runners
222Services
223Tags
224Triggers
225VulnerabilityFindings
226
227// Users
228Users
229UserEmails
230UserImpersonationTokens
231UserKeys
232UserGPGKeys
233
234```
235
236### Bundle Imports
237
238It can be annoying to have to import all the API's pertaining to a specific resource. For example, the Projects resource is composed of many API's, Projects, Issues, Labels, MergeRequests, etc. For convenience, there is a Bundle export for importing and instantiating all these related API's at once.
239
240```javascript
241import { ProjectsBundle } from 'gitlab';
242
243const services = new ProjectsBundle({
244 host: 'http://example.com',
245 token: 'personaltoken'
246})
247
248services.Projects.all()
249services.MergeRequests.all()
250etc..
251
252```
253
254Currently there are three Bundles:
255
2561. ProjectsBundle which includes:
257
258```
259Branches
260Commits
261CommitDiscussions
262Deployments
263DeployKeys
264Environments
265Issues
266IssueNotes
267IssueDiscussions
268IssueAwardEmojis
269IssuesStatistics
270Jobs
271Labels
272MergeRequests
273MergeRequestAwardEmojis
274MergeRequestDiscussions
275MergeRequestNotes
276Packages
277Pipelines
278PipelineSchedules
279PipelineScheduleVariables
280Projects
281ProjectAccessRequests
282ProjectBadges
283ProjectCustomAttributes
284ProjectImportExport
285ProjectIssueBoards
286ProjectHooks
287ProjectMembers
288ProjectMilestones
289ProjectSnippets
290ProjectSnippetNotes
291ProjectSnippetDiscussions
292ProjectSnippetAwardEmojis
293ProtectedBranches
294ProtectedTags
295ProjectVariables
296PushRules
297Repositories
298RepositoryFiles
299Runners
300Services
301Tags
302Todos
303Triggers
304VulnerabilityFindings
305```
306
3072. UsersBundle which includes:
308
309```
310Users,
311UserCustomAttributes,
312UserEmails,
313UserImpersonationTokens,
314UserKeys,
315UserGPGKeys
316```
317
3183. GroupsBundle which includes:
319
320```
321Groups
322GroupAccessRequests
323GroupBadges
324GroupCustomAttributes
325GroupIssueBoards
326GroupMembers
327GroupMilestones
328GroupProjects
329GroupVariables
330GroupLabels
331Epics
332EpicIssues
333EpicNotes
334EpicDiscussions
335```
336
337### Examples
338
339Once you have your library instantiated, you can utilize many of the API's functionality:
340
341Using the await/async method
342
343```javascript
344import { Gitlab } from 'gitlab';
345
346const api = new Gitlab({
347 host: 'http://example.com',
348 token: 'personaltoken',
349});
350
351// Listing users
352let users = await api.Users.all();
353
354// Or using Promise-Then notation
355api.Projects.all().then(projects => {
356 console.log(projects);
357});
358```
359
360A general rule about all the function parameters:
361
362- If it's a required parameter, it is a named argument in the functions
363- If it's an optional parameter, it is defined in a options object following the named arguments
364
365ie.
366
367```javascript
368import { Gitlab } from 'gitlab';
369
370const api = new Gitlab({
371 host: 'http://example.com',
372 token: 'personaltoken',
373});
374
375api.Projects.create({
376 //options defined in the Gitlab API documentation
377});
378```
379
380### Pagination
381
382For any .all() function on a resource, it will return all the items from Gitlab. This can be troublesome if there are many items, as the request itself can take a while to be fulfilled. As such, a maxPages option can be passed to limit the scope of the all function.
383
384```javascript
385import { Gitlab } from 'gitlab';
386
387const api = new Gitlab({
388 host: 'http://example.com',
389 token: 'personaltoken',
390});
391
392let projects = await api.Projects.all({ maxPages: 2 });
393```
394
395You can also use this in conjunction with the perPage argument which would override the default of 30 per page set by Gitlab:
396
397```javascript
398import { Gitlab } from 'gitlab';
399
400const api = new Gitlab({
401 host: 'http://example.com',
402 token: 'personaltoken',
403});
404
405let projects = await api.Projects.all({ maxPages: 2, perPage: 40 });
406```
407
408Additionally, if you would like to get back the pagination information, to know how many total pages there are for example, pass the pagination option `showPagination` in addition to either the
409`maxPages` or `page` properties.
410
411```javascript
412...
413const { data, pagination } = await api.Projects.all({
414 perPage:40,
415 maxPages:2,
416 showPagination: true
417});
418...
419```
420
421This will result in a response in this format:
422
423```javascript
424data: [
425...
426],
427pagination: {
428 total: 20,
429 next: 4,
430 current: 2,
431 previous: 1,
432 perPage: 3,
433 totalPages: 3,
434}
435```
436
437> Note: supplying any pagination restrictions is call intensive. Some resources will require many requests which can put a significant load on the Gitlab Server. The general best practice would be setting the page request option to only return the first page if all results are not required.
438
439### Sudo
440
441For private gitlab instances, administrators can impersonate users through the API. To do so, you have to set the 'Sudo' header on the services you want to impersonate the user for.
442
443For example, if you want to disable notifications for a specific user:
444
445```javascript
446import { NotificationSettings } from 'gitlab';
447
448const service = new NotificationSettings({
449 host: 'http://example.com',
450 token: 'personaltoken'
451 sudo: 8 // Can be the user ID or a username
452});
453
454await service.edit({
455 level: NotificationSettings.LEVELS.DISABLED
456})
457```
458
459### Custom Request Libraries
460
461There is another constructor parameter that allows the user to specify their custom request library
462as long as it has a similar API to ky. To specify the library, simply set the `requester` property when
463instatiating a service:
464
465An example can be seen in the [KyRequester.ts](./src/infrastructure/KyRequester.ts) file
466
467```javascript
468import { Gitlab } from 'gitlab';
469import YourCustomRequester from 'custom-requester';
470
471const api = new Gitlab({
472 host: 'http://example.com',
473 token: 'personaltoken',
474 requester: YourCustomRequester,
475});
476```
477
478### Misc
479
480#### Handling HTTPS certificates
481
482If your Gitlab server is running via HTTPS, the proper way to pass in your certificates is via a `NODE_EXTRA_CA_CERTS` environment key, like this:
483
484```js
485"scripts": {
486 "start": "NODE_EXTRA_CA_CERTS=./secrets/3ShapeCA.pem node bot.js"
487},
488```
489
490> **NOTE**: _Using `process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'` will not work with the `gitlab` library. The `rejectUnauthorized` key is the only way to allow insecure certificates to be bypassed._
491
492#### Non JSON/Text Responses
493
494For responses such as file data that may be returned from the API, the data is exposed as a buffer. For example, when trying to write a file, this can be done like:
495
496```javascript
497let bufferedData = await api.Jobs.downloadLatestArtifactFile(project.id, "test", "job_test");
498
499fs.writeFileSync("test.zip", bufferedData);
500
501```
502
503## Development
504
505To get this running locally rather than from your `node_modules` folder:
506
507```bash
508$ git clone https://github.com/jdalrymple/node-gitlab.git
509$ cd node-gitlab
510$ npm install
511$ npm run-script build
512```
513
514And then inside whatever project you are using `node-gitlab` in you change your references to use that repo. In your package.json of that upstream project change:
515
516```json
517"dependencies": {
518 "gitlab": "5.0.0"
519}
520```
521
522to this
523
524```json
525"dependencies": {
526 "gitlab": "<path-to-your-clone>"
527}
528```
529
530## Testing
531
532Testing is a work-in-progress right now but here is the start.
533
5341. First, run Gitlab in a docker container:
535
536```bash
537docker-compose -f docker-compose.test.yml up
538```
539
5401. Once GitLab is up on localhost:8080, get the two environment variables from the docker image could
541 either export them into environment variables locally:
542
543```bash
544export PERSONAL_ACCESS_TOKEN=$(docker exec -it gitlab bash -lc 'printf "%q" "${PERSONAL_ACCESS_TOKEN}"')
545export GITLAB_URL=$(docker exec -it gitlab bash -lc 'printf "%q" "${GITLAB_URL}"')
546```
547
5481. Now run the tests
549
550```bash
551npm run test
552
553# or, alternatively
554npm run test-with-token # sets PERSONAL_ACCESS_TOKEN and GITLAB_URL from above, before running tests
555```
556
557You can also define them in front of the npm script
558
559```
560PERSONAL_ACCESS_TOKEN='abcdefg' GITLAB_URL='http://localhost:8080' npm run test
561```
562
563> Note it may take about 3 minutes to get the variables while Gitlab is starting up in the container
564
565## Contributors
566
567This started as a fork from [node-gitlab](https://github.com/node-gitlab/node-gitlab) but I ended up rewriting much of the code. Here are the original work's [contributors](https://github.com/node-gitlab/node-gitlab#contributors).
568
569- [Dylan DesRosier](https://github.com/ddesrosier)
570- [Mike Wyatt](https://github.com/mikew)
571- [Cory Zibeill](https://github.com/coryzibell)
572- [Martin Bour](https://github.com/shadygrove)
573- [Christoph Lehmann](https://github.com/christophlehmann)
574- [Frank V](https://github.com/FrankV01)
575- [Salim Benabbou](https://github.com/Salimlou)
576- [Tamás Török-Vistai](https://github.com/tvtamas)
577- [Martin Benninger](https://github.com/MartinBenninger)
578- [Adam Dehnel](https://github.com/arsdehnel)
579- [fewieden](https://github.com/fewieden)
580- [Jeff Pelton](https://github.com/comster)
581- [Claude Abounegm](https://github.com/claude-abounegm)
582- [Stefan Hall](https://github.com/Marethyu1)
583- [Jordan Wallet](https://github.com/Mr-Wallet)
584- [Ev Haus](https://github.com/EvHaus)
585- [zhao0](https://github.com/zhao0)
586- [Joshua Grosso](https://github.com/jgrosso)
587- [Frédéric Boutin](https://github.com/fboutin-pmc)
588- [Isaac Ouellet Therrien](https://github.com/yonguelink)
589- [Pavel Birukov](https://github.com/pablobirukov)
590- [Sharma-Rajat](https://github.com/Sharma-Rajat)
591- [Joseph Petersen](https://github.com/casz)
592- [Igor Katsuba](https://github.com/IKatsuba)
593- [Giuseppe Angri](https://github.com/giuseppeangri)
594- [Michael Townsend](https://github.com/Continuities)
595- [bodtx](https://github.com/bodtx)
596- [Artem](https://github.com/arthot)
597- [Munif Tanjim](https://github.com/MunifTanjim)
598- [Max Wittig](https://github.com/max-wittig)
599- [Quentin Dreyer](https://github.com/qkdreyer)
600- [Norm MacLennan](https://github.com/maclennann)
601- [jnovick](https://github.com/jnovick)
602- [Fabian Aussems](https://github.com/mozinator)
603- [jennparise](https://github.com/jennparise)
604- [Michael Matzka](https://github.com/mimaidms)
605- [CraigAllardyce](https://github.com/CraigAllardyce)
606- [Bruno Guimarães](https://github.com/brunobastosg)
607- [Louis Cherel](https://github.com/Musinux)
608- [Lukas Eipert](https://github.com/leipert)
609- [Maximilian Krauß](https://github.com/maximilian-krauss)
610- [Evolution Gaming](https://github.com/evolution-gaming)
611- [WEBER Logan](https://github.com/Neonox31)
612- [Anton Zhukov](https://github.com/MrCheater)
613- [Nic Loomans](https://github.com/beaverusiv)
614- [Jennifer Everhart]()
615- [Carl Kittelberger](https://github.com/icedream)
616- [Patrik Votoček](https://github.com/Vrtak-CZ)
617- [Kyrylo Fedorov](https://github.com/Kyr)
618- [Claudio Vellage](https://github.com/jdalrymple/LRH539)
619- [Seb0uil](https://github.com/seb0uil)
620
621## License
622
623[MIT](https://github.com/jdalrymple/node-gitlab/blob/master/LICENSE.md)
624
625## Changelog
626
627[Here](https://github.com/jdalrymple/node-gitlab/blob/master/CHANGELOG.md)