Skip to content

Commit

Permalink
feat: initial release
Browse files Browse the repository at this point in the history
  • Loading branch information
pvdlg authored and gr2m committed Jan 6, 2018
1 parent 7378d8f commit ba75444
Show file tree
Hide file tree
Showing 15 changed files with 926 additions and 2 deletions.
131 changes: 131 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@

# Created by https://www.gitignore.io/api/macos,windows,linux,node

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### macOS ###
*.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env


### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db

# Folder config file
Desktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.gitignore.io/api/macos,windows,linux,node

package-lock.json
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
26 changes: 26 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
language: node_js
services:
- docker
notifications:
email: false
node_js:
- 9
- 8

# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- master
- /^greenkeeper.*$/

# Retry install on fail to avoid failing a build on network/disk/external errors
install:
- travis_retry npm install

script:
- npm run test

after_success:
- npm run codecov
- npm run semantic-release
1 change: 1 addition & 0 deletions .yarnrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--install.no-lockfile true
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
70 changes: 68 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,68 @@
# gitlab
:fox_face: Set of Semantic-release plugins for publishing a GitLab release
# @semantic-release/gitlab

Set of [Semantic-release](https://github.com/semantic-release/semantic-release) plugins for publishing a
[GitLab release](https://docs.gitlab.com/ce/workflow/releases.html).

[![Travis](https://img.shields.io/travis/semantic-release/gitlab.svg)](https://travis-ci.org/semantic-release/gitlab)
[![Codecov](https://img.shields.io/codecov/c/github/semantic-release/gitlab.svg)](https://codecov.io/gh/semantic-release/gitlab)
[![Greenkeeper badge](https://badges.greenkeeper.io/semantic-release/gitlab.svg)](https://greenkeeper.io/)

## verifyConditions

Verify the presence and the validity of the authentication (set via [environment variables](#environment-variables)).

## publish

Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html).

## Configuration

### GitLab authentication

The GitLab authentication configuration is **required** and can be set via
[environment variables](#environment-variables).

Only the [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html)
authentication is supported.

### Environment variables

| Variable | Description |
|--------------------------------|-----------------------------------------------------------|
| `GL_TOKEN` or `GITLAB_TOKEN` | **Required.** The token used to authenticate with GitLab. |
| `GL_URL` or `GITLAB_URL` | The GitLab endpoint. |
| `GL_PREFIX` or `GITLAB_PREFIX` | The GitLab API prefix. |

### Options

| Option | Description | Default |
|-----------------------|------------------------|------------------------------------------------------------------------|
| `gitlabUrl` | The GitLab endpoint. | `GL_URL` or `GITLAB_URL` environment variable or `https://gitlab.com`. |
| `gitlabApiPathPrefix` | The GitLab API prefix. | `GL_PREFIX` or `GITLAB_PREFIX` environment variable or `/api/v4`. |

### Usage

Options can be set within the plugin definition in the Semantic-release configuration file:

```json
{
"release": {
"verifyConditions": [
"@semantic-release/npm",
"@semantic-release/git",
{
"path": "@semantic-release/gitlab",
"gitlabUrl": "https://custom.gitlab.com"
}
],
"publish": [
"@semantic-release/npm",
"@semantic-release/git",
{
"path": "@semantic-release/gitlab",
"gitlabUrl": "https://custom.gitlab.com"
}
]
}
}
```
19 changes: 19 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const verifyGitLab = require('./lib/verify');
const publishGitLab = require('./lib/publish');

let verified;

async function verifyConditions(pluginConfig, {options, logger}) {
await verifyGitLab(pluginConfig, options, logger);
verified = true;
}

async function publish(pluginConfig, {nextRelease, options, logger}) {
if (!verified) {
await verifyGitLab(pluginConfig, options, logger);
verified = true;
}
await publishGitLab(pluginConfig, options, nextRelease, logger);
}

module.exports = {verifyConditions, publish};
43 changes: 43 additions & 0 deletions lib/publish.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const parseGithubUrl = require('parse-github-url');
const urlJoin = require('url-join');
const got = require('got');
const debug = require('debug')('semantic-release:github');
const resolveConfig = require('./resolve-config');

module.exports = async (pluginConfig, {repositoryUrl}, {gitHead, gitTag, notes}, logger) => {
const {gitlabToken, gitlabUrl, gitlabApiPathPrefix} = resolveConfig(pluginConfig);
const {name: repo, owner} = parseGithubUrl(repositoryUrl);

debug('release name: %o', gitTag);
debug('release ref: %o', gitHead);

try {
// Test if the tag already exists
await got.get(urlJoin(gitlabUrl, gitlabApiPathPrefix, `/projects/${owner}%2F${repo}/repository/tags/${gitTag}`), {
json: true,
headers: {'Private-Token': gitlabToken},
});
debug('The git tag %o already exists, update the release description', gitTag);
// Update the release notes
await got.post(
urlJoin(gitlabUrl, gitlabApiPathPrefix, `/projects/${owner}%2F${repo}/repository/tags/${gitTag}/release`),
{json: true, headers: {'Private-Token': gitlabToken}, body: {tag_name: gitTag, description: notes}} // eslint-disable-line camelcase
);
} catch (err) {
// If the error is 404, the tag doesn't exist, otherwise it's an error
if (err.statusCode !== 404) {
throw err;
}
debug('Create git tag %o with commit %o and release description', gitTag, gitHead);
await got.post(
urlJoin(gitlabUrl, gitlabApiPathPrefix, `/projects/${owner}%2F${repo}/repository/tags/${gitTag}/release`),
{
json: true,
headers: {'PRIVATE-TOKEN': gitlabToken},
body: {tag_name: gitTag, ref: gitHead, release_description: notes}, // eslint-disable-line camelcase
}
);
}

logger.log('Published GitLab release: %s', gitTag);
};
10 changes: 10 additions & 0 deletions lib/resolve-config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = ({gitlabUrl, gitlabApiPathPrefix}) => ({
gitlabToken: process.env.GL_TOKEN || process.env.GITLAB_TOKEN,
gitlabUrl: gitlabUrl || process.env.GL_URL || process.env.GITLAB_URL || 'https://gitlab.com',
gitlabApiPathPrefix:
typeof gitlabApiPathPrefix === 'string'
? gitlabApiPathPrefix
: null || typeof process.env.GL_PREFIX === 'string'
? process.env.GL_PREFIX
: null || typeof process.env.GITLAB_PREFIX === 'string' ? process.env.GITLAB_PREFIX : null || '/api/v4',
});
47 changes: 47 additions & 0 deletions lib/verify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const parseGithubUrl = require('parse-github-url');
const urlJoin = require('url-join');
const got = require('got');
const SemanticReleaseError = require('@semantic-release/error');
const resolveConfig = require('./resolve-config');

module.exports = async (pluginConfig, {repositoryUrl}, logger) => {
const {gitlabToken, gitlabUrl, gitlabApiPathPrefix} = resolveConfig(pluginConfig);

if (!gitlabToken) {
throw new SemanticReleaseError('No GitLab token specified.', 'ENOGLTOKEN');
}

const {name: repo, owner} = parseGithubUrl(repositoryUrl);
if (!owner || !repo) {
throw new SemanticReleaseError(
`The git repository URL ${repositoryUrl} is not a valid GitLab URL.`,
'EINVALIDGITURL'
);
}

logger.log('Verify GitLab authentication (%s)', urlJoin(gitlabUrl, gitlabApiPathPrefix));

let projectAccess;
let groupAccess;

try {
({body: {permissions: {project_access: projectAccess, group_access: groupAccess}}} = await got.get(
urlJoin(gitlabUrl, gitlabApiPathPrefix, `/projects/${owner}%2F${repo}`),
{json: true, headers: {'Private-Token': gitlabToken}}
));
} catch (err) {
if (err.statusCode === 401) {
throw new SemanticReleaseError('Invalid GitLab token.', 'EINVALIDGLTOKEN');
} else if (err.statusCode === 404) {
throw new SemanticReleaseError(`The repository ${owner}/${repo} doesn't exist.`, 'EMISSINGREPO');
}
throw err;
}

if (!((projectAccess && projectAccess.access_level >= 30) || (groupAccess && groupAccess.access_level >= 30))) {
throw new SemanticReleaseError(
`The GitLab token doesn't allow to push on the repository ${owner}/${repo}.`,
'EGHNOPERMISSION'
);
}
};
Loading

0 comments on commit ba75444

Please sign in to comment.