Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enables service installation with a name #2616

Merged
merged 20 commits into from
Jan 2, 2017
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/providers/aws/cli-reference/install.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ serverless install --url https://github.com/some/service

## Options
- `--url` or `-u` The services GitHub URL. **Required**.
- `--name` or `-n` Name for the service.

## Provided lifecycle events
- `install:install`
Expand All @@ -34,6 +35,14 @@ serverless install --url https://github.com/pmuens/serverless-crud

This example will download the .zip file of the `serverless-crud` service from GitHub, create a new directory with the name `serverless-crud` in the current working directory and unzips the files in this directory.

### Installing a service from a GitHub URL with a new service name

```bash
serverless install --url https://github.com/pmuens/serverless-crud --name my-crud
```

This example will download the .zip file of the `serverless-crud` service from GitHub, create a new directory with the name `my-crud` in the current working directory and unzips the files in this directory and renames the service to `my-crud` if `serverless.yml` exists in the service root.

### Installing a service from a directory in a GitHub URL

```bash
Expand Down
68 changes: 56 additions & 12 deletions lib/plugins/install/install.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const BbPromise = require('bluebird');
const path = require('path');
const URL = require('url');
const download = require('download');
const os = require('os');
const fse = require('fs-extra');
const os = require('os');

class Install {
constructor(serverless, options) {
Expand All @@ -24,6 +24,10 @@ class Install {
required: true,
shortcut: 'u',
},
name: {
usage: 'Name for the service',
shortcut: 'n',
},
},
},
};
Expand All @@ -32,6 +36,36 @@ class Install {
'install:install': () => BbPromise.bind(this)
.then(this.install),
};

this.renameService = (name, servicePath) => {
const serviceFile = path.join(servicePath, 'serverless.yml');
const packageFile = path.join(servicePath, 'package.json');

if (!this.serverless.utils.fileExistsSync(serviceFile)) {
const errorMessage = [
'serverless.yml not found in',
` ${servicePath}`,
].join('');
throw new this.serverless.classes.Error(errorMessage);
}

const serverlessYml =
fse.readFileSync(serviceFile, 'utf-8')
.replace(/service\s*:.+/gi, (match) => {
const fractions = match.split('#');
fractions[0] = `service: ${name}`;
return fractions.join(' #');
});

fse.writeFileSync(serviceFile, serverlessYml);

if (this.serverless.utils.fileExistsSync(packageFile)) {
const json = this.serverless.utils.readFileSync(packageFile);
this.serverless.utils.writeFile(packageFile, Object.assign(json, { name }));
}

return ` as "${name}"`;
};
}

install() {
Expand All @@ -48,6 +82,7 @@ class Install {
repo: parts[2],
branch: parts[4] || 'master',
};

// validate if given url is a valid GitHub url
if (url.hostname !== 'github.com' || !parsedGitHubUrl.owner || !parsedGitHubUrl.repo) {
const errorMessage = [
Expand All @@ -69,18 +104,21 @@ class Install {

const endIndex = parts.length - 1;
let dirName;
let servicePath;
let downloadServicePath;

// check if it's a directory or the whole repository
if (parts.length > 4) {
dirName = parts[endIndex];
dirName = this.options.name || parts[endIndex];
// download the repo into a temporary directory
servicePath = path.join(os.tmpdir(), parsedGitHubUrl.repo);
downloadServicePath = path.join(os.tmpdir(), parsedGitHubUrl.repo);
} else {
dirName = parsedGitHubUrl.repo;
servicePath = path.join(process.cwd(), dirName);
dirName = this.options.name || parsedGitHubUrl.repo;
downloadServicePath = path.join(process.cwd(), dirName);
}

const servicePath = path.join(process.cwd(), dirName);
const renamed = dirName !== (parts.length > 4 ? parts[endIndex] : parsedGitHubUrl.repo);

if (this.serverless.utils.dirExistsSync(path.join(process.cwd(), dirName))) {
const errorMessage = `A folder named "${dirName}" already exists.`;
throw new this.serverless.classes.Error(errorMessage);
Expand All @@ -93,20 +131,26 @@ class Install {
// download service
return download(
downloadUrl,
servicePath,
downloadServicePath,
{ timeout: 30000, extract: true, strip: 1, mode: '755' }
).then(() => {
// if it's a directory inside of git
// if it's a directory inside of git
if (parts.length > 4) {
let directory = servicePath;
let directory = downloadServicePath;
for (let i = 5; i <= endIndex; i++) {
directory = path.join(directory, parts[i]);
}
that.serverless.utils
.copyDirContentsSync(directory, path.join(process.cwd(), parts[endIndex]));
fse.removeSync(servicePath);
.copyDirContentsSync(directory, servicePath);
fse.removeSync(downloadServicePath);
}
}).then(() => {
if (!renamed) {
return '';
}
that.serverless.cli.log(`Successfully installed service "${dirName}".`);
return this.renameService(dirName, servicePath);
}).then((extraInfo) => {
that.serverless.cli.log(`Successfully installed "${parsedGitHubUrl.repo}"${extraInfo}.`);
});
}
}
Expand Down
160 changes: 146 additions & 14 deletions lib/plugins/install/install.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,28 @@ const fse = require('fs-extra');
const path = require('path');
const proxyquire = require('proxyquire');

const remove = BbPromise.promisify(fse.remove);

describe('Install', () => {
let install;
let serverless;
let downloadStub;
let Install;
let cwd;

let servicePath;
let newServicePath;

beforeEach(() => {
const tmpDir = testUtils.getTmpDirPath();
cwd = process.cwd();

fse.mkdirsSync(tmpDir);
process.chdir(tmpDir);

servicePath = tmpDir;
newServicePath = path.join(servicePath, 'new-service-name');

downloadStub = sinon.stub().returns(BbPromise.resolve());
Install = proxyquire('./install.js', {
download: downloadStub,
Expand All @@ -25,6 +40,11 @@ describe('Install', () => {
serverless.init();
});

afterEach(() => {
// change back to the old cwd
process.chdir(cwd);
});

describe('#constructor()', () => {
it('should have commands', () => expect(install.commands).to.be.not.empty);

Expand All @@ -40,10 +60,82 @@ describe('Install', () => {
install.install.restore();
});
});

it('should set new service in serverless.yml and name in package.json', () => {
const defaultServiceYml =
'service: service-name\n\nprovider:\n name: aws\n';
const newServiceYml =
'service: new-service-name\n\nprovider:\n name: aws\n';

const defaultServiceName = 'service-name';
const newServiceName = 'new-service-name';

const packageFile = path.join(servicePath, 'package.json');
const serviceFile = path.join(servicePath, 'serverless.yml');

serverless.utils.writeFileSync(packageFile, { name: defaultServiceName });
fse.writeFileSync(serviceFile, defaultServiceYml);

install.renameService(newServiceName, servicePath);
const serviceYml = fse.readFileSync(serviceFile, 'utf-8');
const packageJson = serverless.utils.readFileSync(packageFile);
expect(serviceYml).to.equal(newServiceYml);
expect(packageJson.name).to.equal(newServiceName);
});

it('should set new service in commented serverless.yml and name in package.json', () => {
const defaultServiceYml =
'# comment\nservice: service-name #comment\n\nprovider:\n name: aws\n# comment';
const newServiceYml =
'# comment\nservice: new-service-name #comment\n\nprovider:\n name: aws\n# comment';

const defaultServiceName = 'service-name';
const newServiceName = 'new-service-name';

const packageFile = path.join(servicePath, 'package.json');
const serviceFile = path.join(servicePath, 'serverless.yml');

serverless.utils.writeFileSync(packageFile, { name: defaultServiceName });
fse.writeFileSync(serviceFile, defaultServiceYml);

install.renameService(newServiceName, servicePath);
const serviceYml = fse.readFileSync(serviceFile, 'utf-8');
const packageJson = serverless.utils.readFileSync(packageFile);
expect(serviceYml).to.equal(newServiceYml);
expect(packageJson.name).to.equal(newServiceName);
});

it('should set new service in commented serverless.yml without existing package.json', () => {
const defaultServiceYml =
'# comment\nservice: service-name #comment\n\nprovider:\n name: aws\n# comment';
const newServiceYml =
'# comment\nservice: new-service-name #comment\n\nprovider:\n name: aws\n# comment';

const serviceFile = path.join(servicePath, 'serverless.yml');

serverless.utils.writeFileDir(serviceFile);
fse.writeFileSync(serviceFile, defaultServiceYml);

install.renameService('new-service-name', servicePath);
const serviceYml = fse.readFileSync(serviceFile, 'utf-8');
expect(serviceYml).to.equal(newServiceYml);
});

it('should fail to set new service name in serverless.yml', () => {
const defaultServiceYml =
'# comment\nservice: service-name #comment\n\nprovider:\n name: aws\n# comment';

const serviceFile = path.join(servicePath, 'serverledss.yml');

serverless.utils.writeFileDir(serviceFile);
fse.writeFileSync(serviceFile, defaultServiceYml);

expect(() => install.renameService('new-service-name', servicePath)).to.throw(Error);
});
});

describe('#install()', () => {
it('shold throw an error if the passed URL option is not a valid URL', () => {
it('should throw an error if the passed URL option is not a valid URL', () => {
install.options = { url: 'invalidUrl' };

expect(() => install.install()).to.throw(Error);
Expand All @@ -58,16 +150,10 @@ describe('Install', () => {
it('should throw an error if a directory with the same service name is already present', () => {
install.options = { url: 'https://github.com/johndoe/existing-service' };

const tmpDir = testUtils.getTmpDirPath();
const serviceDirName = path.join(tmpDir, 'existing-service');
const serviceDirName = path.join(servicePath, 'existing-service');
fse.mkdirsSync(serviceDirName);

const cwd = process.cwd();
process.chdir(tmpDir);

expect(() => install.install()).to.throw(Error);

process.chdir(cwd);
});

it('should download the service based on the GitHub URL', () => {
Expand Down Expand Up @@ -97,15 +183,61 @@ describe('Install', () => {

it('should throw an error if the same service name exists as directory in Github', () => {
install.options = { url: 'https://github.com/serverless/examples/tree/master/rest-api-with-dynamodb' };
const tmpDir = testUtils.getTmpDirPath();
const serviceDirName = path.join(tmpDir, 'rest-api-with-dynamodb');
const serviceDirName = path.join(servicePath, 'rest-api-with-dynamodb');
fse.mkdirsSync(serviceDirName);

const cwd = process.cwd();
process.chdir(tmpDir);

expect(() => install.install()).to.throw(Error);
process.chdir(cwd);
});

it('should download and rename the service based on the GitHub URL', () => {
install.options = {
url: 'https://github.com/johndoe/service-to-be-downloaded',
name: 'new-service-name',
};

downloadStub.returns(
remove(newServicePath)
.then(() => {
const sp = downloadStub.args[0][1];
const slsYml = path.join(
sp,
'serverless.yml');
serverless
.utils.writeFileSync(slsYml, 'service: service-name');
}));

return install.install().then(() => {
expect(downloadStub.calledOnce).to.equal(true);
expect(downloadStub.args[0][1]).to.contain(install.options.name);
expect(downloadStub.args[0][0]).to.equal(`${install.options.url}/archive/master.zip`);
const yml = serverless.utils.readFileSync(path.join(newServicePath, 'serverless.yml'));
expect(yml.service).to.equal(install.options.name);
});
});

it('should download and rename the service based directories in the GitHub URL', () => {
install.options = {
url: 'https://github.com/serverless/examples/tree/master/rest-api-with-dynamodb',
name: 'new-service-name',
};

downloadStub.returns(
remove(newServicePath)
.then(() => {
const sp = downloadStub.args[0][1];
const slsYml = path.join(
sp,
'rest-api-with-dynamodb',
'serverless.yml');
serverless
.utils.writeFileSync(slsYml, 'service: service-name');
}));

return install.install().then(() => {
expect(downloadStub.calledOnce).to.equal(true);
const yml = serverless.utils.readFileSync(path.join(newServicePath, 'serverless.yml'));
expect(yml.service).to.equal(install.options.name);
});
});
});
});