Merge branch 'master' into feature/ingest
4
.gitignore
vendored
|
@ -12,7 +12,9 @@ target
|
|||
.idea
|
||||
*.iml
|
||||
*.log
|
||||
/test/output
|
||||
/test/screenshots/diff
|
||||
/test/screenshots/failure
|
||||
/test/screenshots/session
|
||||
/esvm
|
||||
.htpasswd
|
||||
.eslintcache
|
||||
|
|
|
@ -69,7 +69,7 @@ module.exports = function (grunt) {
|
|||
|
||||
grunt.config.merge(config);
|
||||
|
||||
config.userScriptsDir = __dirname + '/build/userScripts';
|
||||
config.packageScriptsDir = __dirname + '/tasks/build/package_scripts';
|
||||
// ensure that these run first, other configs need them
|
||||
config.services = require('./tasks/config/services')(grunt);
|
||||
config.platforms = require('./tasks/config/platforms')(grunt);
|
||||
|
|
822
STYLEGUIDE.md
|
@ -1,767 +1,9 @@
|
|||
This is a collection of style guides for Kibana projects. The include guides for the following:
|
||||
|
||||
- [JavaScript](#javascript-style-guide)
|
||||
- [Kibana Project](#kibana-style-guide)
|
||||
- [Html](#html-style-guide)
|
||||
|
||||
# JavaScript Style Guide
|
||||
|
||||
## 2 Spaces for indention
|
||||
|
||||
Use 2 spaces for indenting your code and swear an oath to never mix tabs and
|
||||
spaces - a special kind of hell is awaiting you otherwise.
|
||||
|
||||
## Newlines
|
||||
|
||||
Use UNIX-style newlines (`\n`), and a newline character as the last character
|
||||
of a file. Windows-style newlines (`\r\n`) are forbidden inside any repository.
|
||||
|
||||
## No trailing whitespace
|
||||
|
||||
Just like you brush your teeth after every meal, you clean up any trailing
|
||||
whitespace in your JS files before committing. Otherwise the rotten smell of
|
||||
careless neglect will eventually drive away contributors and/or co-workers.
|
||||
|
||||
## Use Semicolons
|
||||
|
||||
According to [scientific research][hnsemicolons], the usage of semicolons is
|
||||
a core value of our community. Consider the points of [the opposition][], but
|
||||
be a traditionalist when it comes to abusing error correction mechanisms for
|
||||
cheap syntactic pleasures.
|
||||
|
||||
[the opposition]: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
|
||||
[hnsemicolons]: http://news.ycombinator.com/item?id=1547647
|
||||
|
||||
## 120 characters per line
|
||||
|
||||
Try to limit your lines to 80 characters. If it feels right, you can go up to 120 characters.
|
||||
|
||||
## Use single quotes
|
||||
|
||||
Use single quotes, unless you are writing JSON.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var foo = 'bar';
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var foo = "bar";
|
||||
```
|
||||
|
||||
## Opening braces go on the same line
|
||||
|
||||
Your opening braces go on the same line as the statement.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
if (true) {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (true)
|
||||
{
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
Also, notice the use of whitespace before and after the condition statement.
|
||||
|
||||
## Always use braces for multi-line code
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (err)
|
||||
return cb(err);
|
||||
```
|
||||
|
||||
## Prefer multi-line conditionals
|
||||
|
||||
But single-line conditionals are allowed for short lines
|
||||
|
||||
*Preferred:*
|
||||
|
||||
```js
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
if (err) return cb(err);
|
||||
```
|
||||
|
||||
## Declare one variable per var statement
|
||||
|
||||
Declare one variable per var statement, it makes it easier to re-order the
|
||||
lines. However, ignore [Crockford][crockfordconvention] when it comes to
|
||||
declaring variables deeper inside a function, just put the declarations wherever
|
||||
they make sense.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var keys = ['foo', 'bar'];
|
||||
var values = [23, 42];
|
||||
|
||||
var object = {};
|
||||
while (keys.length) {
|
||||
var key = keys.pop();
|
||||
object[key] = values.pop();
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var keys = ['foo', 'bar'],
|
||||
values = [23, 42],
|
||||
object = {},
|
||||
key;
|
||||
|
||||
while (keys.length) {
|
||||
key = keys.pop();
|
||||
object[key] = values.pop();
|
||||
}
|
||||
```
|
||||
|
||||
[crockfordconvention]: http://javascript.crockford.com/code.html
|
||||
|
||||
## Use lowerCamelCase for variables, properties and function names
|
||||
|
||||
Variables, properties and function names should use `lowerCamelCase`. They
|
||||
should also be descriptive. Single character variables and uncommon
|
||||
abbreviations should generally be avoided.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var adminUser = db.query('SELECT * FROM users ...');
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var admin_user = db.query('SELECT * FROM users ...');
|
||||
```
|
||||
|
||||
## Use UpperCamelCase for class names
|
||||
|
||||
Class names should be capitalized using `UpperCamelCase`.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
function BankAccount() {
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function bank_Account() {
|
||||
}
|
||||
```
|
||||
|
||||
## Use UPPERCASE for Constants
|
||||
|
||||
Constants should be declared as regular variables or static class properties,
|
||||
using all uppercase letters.
|
||||
|
||||
Node.js / V8 actually supports mozilla's [const][const] extension, but
|
||||
unfortunately that cannot be applied to class members, nor is it part of any
|
||||
ECMA standard.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var SECOND = 1 * 1000;
|
||||
|
||||
function File() {
|
||||
}
|
||||
File.FULL_PERMISSIONS = 0777;
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
const SECOND = 1 * 1000;
|
||||
|
||||
function File() {
|
||||
}
|
||||
File.fullPermissions = 0777;
|
||||
```
|
||||
|
||||
[const]: https://developer.mozilla.org/en/JavaScript/Reference/Statements/const
|
||||
|
||||
## Magic numbers
|
||||
|
||||
These are numbers (or other values) simply used in line in your code. **Do not use these**, give them a variable name so they can be understood and changed easily.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var minWidth = 300;
|
||||
|
||||
if (width < minWidth) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (width < 300) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Global definitions
|
||||
|
||||
Don't do this. Everything should be wrapped in a module that can be depended on by other modules. Even things as simple as a single value should be a module.
|
||||
|
||||
## Function definitions
|
||||
|
||||
Prefer the use of function declarations over function expressions. Function expressions are allowed, but should usually be avoided.
|
||||
|
||||
Also, keep function definitions above other code instead of relying on function hoisting.
|
||||
|
||||
*Preferred:*
|
||||
|
||||
```js
|
||||
function myFunc() {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
var myFunc = function () {
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
## Object / Array creation
|
||||
|
||||
Use trailing commas and put *short* declarations on a single line. Only quote
|
||||
keys when your interpreter complains:
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = ['hello', 'world'];
|
||||
var b = {
|
||||
good: 'code',
|
||||
'is generally': 'pretty'
|
||||
};
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var a = [
|
||||
'hello', 'world'
|
||||
];
|
||||
var b = {"good": 'code'
|
||||
, is generally: 'pretty'
|
||||
};
|
||||
```
|
||||
|
||||
## Object / Array iterations, transformations and operations
|
||||
|
||||
Use native ES5 methods to iterate and transform arrays and objects where possible. Do not use `for` and `while` loops.
|
||||
|
||||
Use descriptive variable names in the closures.
|
||||
|
||||
Use a utility library as needed and where it will make code more comprehensible.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var userNames = users.map(function (user) {
|
||||
return user.name;
|
||||
});
|
||||
|
||||
// examples where lodash makes the code more readable
|
||||
var userNames = _.pluck(users, 'name');
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var userNames = [];
|
||||
for (var i = 0; i < users.length; i++) {
|
||||
userNames.push(users[i].name);
|
||||
}
|
||||
```
|
||||
|
||||
## Use the === operator
|
||||
|
||||
Programming is not about remembering [stupid rules][comparisonoperators]. Use
|
||||
the triple equality operator as it will work just as expected.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = 0;
|
||||
if (a !== '') {
|
||||
console.log('winning');
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var a = 0;
|
||||
if (a == '') {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
[comparisonoperators]: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
|
||||
|
||||
## Only use ternary operators for small, simple code
|
||||
|
||||
And **never** use multiple ternaries together
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var foo = (a === b) ? 1 : 2;
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var foo = (a === b) ? 1 : (a === c) ? 2 : 3;
|
||||
```
|
||||
|
||||
## Do not extend built-in prototypes
|
||||
|
||||
Do not extend the prototype of native JavaScript objects. Your future self will
|
||||
be forever grateful.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = [];
|
||||
if (!a.length) {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
Array.prototype.empty = function() {
|
||||
return !this.length;
|
||||
}
|
||||
|
||||
var a = [];
|
||||
if (a.empty()) {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
## Use descriptive conditions
|
||||
|
||||
Any non-trivial conditions should be assigned to a descriptively named variables, broken into
|
||||
several names variables, or converted to be a function:
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var thing = ...;
|
||||
var isShape = thing instanceof Shape;
|
||||
var notSquare = !(thing instanceof Square);
|
||||
var largerThan10 = isShape && thing.size > 10;
|
||||
|
||||
if (isShape && notSquare && largerThan10) {
|
||||
console.log('some big polygon');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (
|
||||
thing instanceof Shape
|
||||
&& !(thing instanceof Square)
|
||||
&& thing.size > 10
|
||||
) {
|
||||
console.log('bigger than ten?? Woah!');
|
||||
}
|
||||
```
|
||||
|
||||
## Name regular expressions
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var validPasswordRE = /^(?=.*\d).{4,}$/;
|
||||
|
||||
if (password.length >= 4 && validPasswordRE.test(password)) {
|
||||
console.log('password is valid');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
## Write small functions
|
||||
|
||||
Keep your functions short. A good function fits on a slide that the people in
|
||||
the last row of a big room can comfortably read. So don't count on them having
|
||||
perfect vision and limit yourself to ~15 lines of code per function.
|
||||
|
||||
## Return early from functions
|
||||
|
||||
To avoid deep nesting of if-statements, always return a function's value as early
|
||||
as possible.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
if (val < 0) return false;
|
||||
if (val > 100) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
if (val >= 0) {
|
||||
if (val < 100) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or for this particular example it may also be fine to shorten things even
|
||||
further:
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
var isInRange = (val >= 0 && val <= 100);
|
||||
return isInRange;
|
||||
}
|
||||
```
|
||||
|
||||
## Chaining operations
|
||||
|
||||
When using a chaining syntax (jquery or promises, for example), do not indent the subsequent chained operations, unless there is a logical grouping in them.
|
||||
|
||||
Also, if the chain is long, each method should be on a new line.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
$('.someClass')
|
||||
.addClass('another-class')
|
||||
.append(someElement)
|
||||
```
|
||||
|
||||
```js
|
||||
d3.selectAll('g.bar')
|
||||
.enter()
|
||||
.append('thing')
|
||||
.data(anything)
|
||||
.exit()
|
||||
.each(function() ... )
|
||||
```
|
||||
|
||||
```js
|
||||
$http.get('/info')
|
||||
.then(({ data }) => this.transfromInfo(data))
|
||||
.then((transformed) => $http.post('/new-info', transformed))
|
||||
.then(({ data }) => console.log(data));
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
$('.someClass')
|
||||
.addClass('another-class')
|
||||
.append(someElement)
|
||||
```
|
||||
|
||||
```js
|
||||
d3.selectAll('g.bar')
|
||||
.enter().append('thing').data(anything).exit()
|
||||
.each(function() ... )
|
||||
```
|
||||
|
||||
```js
|
||||
$http.get('/info')
|
||||
.then(({ data }) => this.transfromInfo(data))
|
||||
.then((transformed) => $http.post('/new-info', transformed))
|
||||
.then(({ data }) => console.log(data));
|
||||
```
|
||||
|
||||
## Name your closures
|
||||
|
||||
Feel free to give your closures a descriptive name. It shows that you care about them, and
|
||||
will produce better stack traces, heap and cpu profiles.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
req.on('end', function onEnd() {
|
||||
console.log('winning');
|
||||
});
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
req.on('end', function() {
|
||||
console.log('losing');
|
||||
});
|
||||
```
|
||||
|
||||
## No nested closures
|
||||
|
||||
Use closures, but don't nest them. Otherwise your code will become a mess.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
setTimeout(function() {
|
||||
client.connect(afterConnect);
|
||||
}, 1000);
|
||||
|
||||
function afterConnect() {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
setTimeout(function() {
|
||||
client.connect(function() {
|
||||
console.log('losing');
|
||||
});
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
## Use slashes for comments
|
||||
|
||||
Use slashes for both single line and multi line comments. Try to write
|
||||
comments that explain higher level mechanisms or clarify difficult
|
||||
segments of your code. **Don't use comments to restate trivial things**.
|
||||
|
||||
***Exception:*** Comment blocks describing a function and its arguments (docblock) should start with `/**`, contain a single `*` at the beginning of each line, and end with `*/`.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
// 'ID_SOMETHING=VALUE' -> ['ID_SOMETHING=VALUE', 'SOMETHING', 'VALUE']
|
||||
var matches = item.match(/ID_([^\n]+)=([^\n]+)/));
|
||||
|
||||
/**
|
||||
* Fetches a user from...
|
||||
* @param {string} id - id of the user
|
||||
* @return {Promise}
|
||||
*/
|
||||
function loadUser(id) {
|
||||
// This function has a nasty side effect where a failure to increment a
|
||||
// redis counter used for statistics will cause an exception. This needs
|
||||
// to be fixed in a later iteration.
|
||||
|
||||
...
|
||||
}
|
||||
|
||||
var isSessionValid = (session.expires < Date.now());
|
||||
if (isSessionValid) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
// Execute a regex
|
||||
var matches = item.match(/ID_([^\n]+)=([^\n]+)/));
|
||||
|
||||
// Usage: loadUser(5, function() { ... })
|
||||
function loadUser(id, cb) {
|
||||
// ...
|
||||
}
|
||||
|
||||
// Check if the session is valid
|
||||
var isSessionValid = (session.expires < Date.now());
|
||||
// If the session is valid
|
||||
if (isSessionValid) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Do not comment out code
|
||||
|
||||
We use a version management system. If a line of code is no longer needed, remove it, don't simply comment it out.
|
||||
|
||||
## Classes/Constructors and Inheritance
|
||||
|
||||
While JavaScript it is not always considered an object-oriented language, it does have the building blocks for writing object oriented code. Of course, as with all things JavaScript, there are many ways this can be accomplished. Generally, we try to err on the side of readability.
|
||||
|
||||
### Capitalized function definition as Constructors
|
||||
|
||||
When Defining a Class/Constructor, use the function definition syntax.
|
||||
|
||||
*Right:*
|
||||
```js
|
||||
function ClassName() {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
```js
|
||||
var ClassName = function () {};
|
||||
```
|
||||
|
||||
### Inheritance should be done with a utility
|
||||
|
||||
While you can do it with pure JS, a utility will remove a lot of boilerplate, and be more readable and functional.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
// uses a lodash inherits mixin
|
||||
// inheritance is defined first - it's easier to read and the function will be hoisted
|
||||
_.class(Square).inherits(Shape);
|
||||
|
||||
function Square(width, height) {
|
||||
Square.Super.call(this);
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function Square(width, height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
Square.prototype = Object.create(Shape);
|
||||
```
|
||||
|
||||
### Keep Constructors Small
|
||||
|
||||
It is often the case that there are properties that can't be defined on the prototype, or work that needs to be done to completely create an object (like call its Super class). This is all that should be done within constructors.
|
||||
|
||||
Try to follow the [Write small functions](#write-small-functions) rule here too.
|
||||
|
||||
### Use the prototype
|
||||
|
||||
If a method/property *can* go on the prototype, it probably should.
|
||||
|
||||
```js
|
||||
function Square() {
|
||||
...
|
||||
}
|
||||
|
||||
/**
|
||||
* method does stuff
|
||||
* @return {undefined}
|
||||
*/
|
||||
Square.prototype.method = function () {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Handling scope and aliasing `this`
|
||||
|
||||
When creating a prototyped class, each method should almost always start with:
|
||||
|
||||
`var self = this;`
|
||||
|
||||
With the exception of very short methods (roughly 3 lines or less), `self` should always be used in place of `this`.
|
||||
|
||||
Avoid the use of `bind`
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
Square.prototype.doFancyThings = function () {
|
||||
var self = this;
|
||||
|
||||
somePromiseUtil()
|
||||
.then(function (result) {
|
||||
self.prop = result.prop;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
Square.prototype.doFancyThings = function () {
|
||||
somePromiseUtil()
|
||||
.then(function (result) {
|
||||
this.prop = result.prop;
|
||||
}).bind(this);
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
Square.prototype.area = function () {
|
||||
return this.width * this.height;
|
||||
}
|
||||
```
|
||||
|
||||
## Object.freeze, Object.preventExtensions, Object.seal, with, eval
|
||||
|
||||
Crazy shit that you will probably never need. Stay away from it.
|
||||
|
||||
## Getters and Setters
|
||||
|
||||
Feel free to use getters that are free from [side effects][sideeffect], like
|
||||
providing a length property for a collection class.
|
||||
|
||||
Do not use setters, they cause more problems for people who try to use your
|
||||
software than they can solve.
|
||||
|
||||
[sideeffect]: http://en.wikipedia.org/wiki/Side_effect_(computer_science)
|
||||
- [JavaScript](style_guides/js_style_guide.md)
|
||||
- [CSS](style_guides/css_style_guide.md)
|
||||
- [HTML](style_guides/html_style_guide.md)
|
||||
- [API](style_guides/api_style_guide.md)
|
||||
|
||||
# Kibana Style Guide
|
||||
|
||||
|
@ -866,59 +108,3 @@ require('ui/routes')
|
|||
// angular route code goes here
|
||||
});
|
||||
```
|
||||
|
||||
# Html Style Guide
|
||||
|
||||
## Multiple attribute values
|
||||
|
||||
When a node has multiple attributes that would cause it to exceed the line character limit, each attribute including the first should be on its own line with a single indent. Also, when a node that is styled in this way has child nodes, there should be a blank line between the opening parent tag and the first child tag.
|
||||
|
||||
```
|
||||
<ul
|
||||
attribute1="value1"
|
||||
attribute2="value2"
|
||||
attribute3="value3">
|
||||
|
||||
<li></li>
|
||||
<li></li>
|
||||
...
|
||||
</ul>
|
||||
```
|
||||
|
||||
# Api Style Guide
|
||||
|
||||
## Paths
|
||||
|
||||
API routes must start with the `/api/` path segment, and should be followed by the plugin id if applicable:
|
||||
|
||||
*Right:* `/api/marvel/v1/nodes`
|
||||
*Wrong:* `/marvel/api/v1/nodes`
|
||||
|
||||
## Versions
|
||||
|
||||
Kibana won't be supporting multiple API versions, so API's should not define a version.
|
||||
|
||||
*Right:* `/api/kibana/index_patterns`
|
||||
*Wrong:* `/api/kibana/v1/index_patterns`
|
||||
|
||||
## snake_case
|
||||
|
||||
Kibana uses `snake_case` for the entire API, just like Elasticsearch. All urls, paths, query string parameters, values, and bodies should be `snake_case` formatted.
|
||||
|
||||
*Right:*
|
||||
```
|
||||
POST /api/kibana/index_patterns
|
||||
{
|
||||
"id": "...",
|
||||
"time_field_name": "...",
|
||||
"fields": [
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
# Attribution
|
||||
|
||||
This JavaScript guide forked from the [node style guide](https://github.com/felixge/node-style-guide) created by [Felix Geisendörfer](http://felixge.de/) and is
|
||||
licensed under the [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/)
|
||||
license.
|
||||
|
|
|
@ -88,5 +88,5 @@
|
|||
# logging.verbose: false
|
||||
|
||||
# Set the interval in milliseconds to sample system and process performance
|
||||
# metrics. Minimum is 100ms. Defaults to 10000.
|
||||
# ops.interval: 10000
|
||||
# metrics. Minimum is 100ms. Defaults to 5000.
|
||||
# ops.interval: 5000
|
||||
|
|
|
@ -42,7 +42,7 @@ retrying.
|
|||
error messages.
|
||||
`logging.verbose`:: *Default: false* Set the value of this setting to `true` to log all events, including system usage
|
||||
information and all requests.
|
||||
`ops.interval`:: *Default: 10000* Set the interval in milliseconds to sample system and process performance metrics.
|
||||
`ops.interval`:: *Default: 5000* Set the interval in milliseconds to sample system and process performance metrics.
|
||||
The minimum value is 100.
|
||||
`status.allowAnonymous`:: *Default: false* If authentication is enabled, setting this to `true` allows
|
||||
unauthenticated users to access the Kibana server status API and status page.
|
||||
|
|
|
@ -59,7 +59,8 @@
|
|||
"makelogs": "makelogs",
|
||||
"mocha": "mocha",
|
||||
"mocha:debug": "mocha --debug-brk",
|
||||
"sterilize": "grunt sterilize"
|
||||
"sterilize": "grunt sterilize",
|
||||
"compareScreenshots": "node utilities/compareScreenshots"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
@ -168,7 +169,7 @@
|
|||
"grunt-cli": "0.1.13",
|
||||
"grunt-contrib-clean": "0.6.0",
|
||||
"grunt-contrib-copy": "0.8.1",
|
||||
"grunt-esvm": "3.1.1",
|
||||
"grunt-esvm": "3.2.1",
|
||||
"grunt-karma": "0.12.0",
|
||||
"grunt-run": "0.5.0",
|
||||
"grunt-s3": "0.2.0-alpha.3",
|
||||
|
@ -176,6 +177,7 @@
|
|||
"gruntify-eslint": "1.0.1",
|
||||
"html-entities": "1.1.3",
|
||||
"husky": "0.8.1",
|
||||
"image-diff": "1.6.0",
|
||||
"intern": "3.0.1",
|
||||
"istanbul-instrumenter-loader": "0.1.3",
|
||||
"karma": "0.13.9",
|
||||
|
|
|
@ -41,6 +41,7 @@ describe('plugins/elasticsearch', function () {
|
|||
upgradeDoc('4.0.0-rc1', '4.0.0', true);
|
||||
upgradeDoc('4.0.0-rc1-snapshot', '4.0.0', false);
|
||||
upgradeDoc('4.1.0-rc1-snapshot', '4.1.0-rc1', false);
|
||||
upgradeDoc('5.0.0-alpha1', '5.0.0', false);
|
||||
|
||||
it('should handle missing _id field', function () {
|
||||
let doc = {
|
||||
|
|
|
@ -91,10 +91,18 @@ describe('plugins/elasticsearch', function () {
|
|||
});
|
||||
});
|
||||
|
||||
it('should resolve with undefined if the nothing is upgradeable', function () {
|
||||
const response = { hits: { hits: [ { _id: '4.0.1-beta1' }, { _id: '4.0.0-snapshot1' } ] } };
|
||||
it('should create new config if the nothing is upgradeable', function () {
|
||||
get.withArgs('pkg.buildNum').returns(9833);
|
||||
client.create.returns(Promise.resolve());
|
||||
const response = { hits: { hits: [ { _id: '4.0.1-alpha3' }, { _id: '4.0.1-beta1' }, { _id: '4.0.0-snapshot1' } ] } };
|
||||
return upgrade(response).then(function (resp) {
|
||||
expect(resp).to.be(undefined);
|
||||
sinon.assert.calledOnce(client.create);
|
||||
const params = client.create.args[0][0];
|
||||
expect(params).to.have.property('body');
|
||||
expect(params.body).to.have.property('buildNum', 9833);
|
||||
expect(params).to.have.property('index', '.my-kibana');
|
||||
expect(params).to.have.property('type', 'config');
|
||||
expect(params).to.have.property('id', '4.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ const rcVersionRegex = /(\d+\.\d+\.\d+)\-rc(\d+)/i;
|
|||
|
||||
module.exports = function (server, doc) {
|
||||
const config = server.config();
|
||||
if (/beta|snapshot/i.test(doc._id)) return false;
|
||||
if (/alpha|beta|snapshot/i.test(doc._id)) return false;
|
||||
if (!doc._id) return false;
|
||||
if (doc._id === config.get('pkg.version')) return false;
|
||||
|
||||
|
|
|
@ -9,17 +9,21 @@ module.exports = function (server) {
|
|||
const client = server.plugins.elasticsearch.client;
|
||||
const config = server.config();
|
||||
|
||||
function createNewConfig() {
|
||||
return client.create({
|
||||
index: config.get('kibana.index'),
|
||||
type: 'config',
|
||||
body: { buildNum: config.get('pkg.buildNum') },
|
||||
id: config.get('pkg.version')
|
||||
});
|
||||
}
|
||||
|
||||
return function (response) {
|
||||
const newConfig = {};
|
||||
|
||||
// Check to see if there are any doc. If not then we set the build number and id
|
||||
if (response.hits.hits.length === 0) {
|
||||
return client.create({
|
||||
index: config.get('kibana.index'),
|
||||
type: 'config',
|
||||
body: { buildNum: config.get('pkg.buildNum') },
|
||||
id: config.get('pkg.version')
|
||||
});
|
||||
return createNewConfig();
|
||||
}
|
||||
|
||||
// if we already have a the current version in the index then we need to stop
|
||||
|
@ -30,9 +34,11 @@ module.exports = function (server) {
|
|||
if (devConfig) return Promise.resolve();
|
||||
|
||||
// Look for upgradeable configs. If none of them are upgradeable
|
||||
// then resolve with null.
|
||||
// then create a new one.
|
||||
const body = _.find(response.hits.hits, isUpgradeable.bind(null, server));
|
||||
if (!body) return Promise.resolve();
|
||||
if (!body) {
|
||||
return createNewConfig();
|
||||
}
|
||||
|
||||
// if the build number is still the template string (which it wil be in development)
|
||||
// then we need to set it to the max interger. Otherwise we will set it to the build num
|
||||
|
|
|
@ -68,6 +68,9 @@ app.directive('dashboardApp', function (Notifier, courier, AppState, timefilter,
|
|||
if (dash.timeRestore && dash.timeTo && dash.timeFrom && !getAppState.previouslyStored()) {
|
||||
timefilter.time.to = dash.timeTo;
|
||||
timefilter.time.from = dash.timeFrom;
|
||||
if (dash.refreshInterval) {
|
||||
timefilter.refreshInterval = dash.refreshInterval;
|
||||
}
|
||||
}
|
||||
|
||||
$scope.$on('$destroy', dash.destroy);
|
||||
|
@ -204,10 +207,12 @@ app.directive('dashboardApp', function (Notifier, courier, AppState, timefilter,
|
|||
$state.title = dash.id = dash.title;
|
||||
$state.save();
|
||||
|
||||
const timeRestoreObj = _.pick(timefilter.refreshInterval, ['display', 'pause', 'section', 'value']);
|
||||
dash.panelsJSON = angular.toJson($state.panels);
|
||||
dash.uiStateJSON = angular.toJson($uiState.getChanges());
|
||||
dash.timeFrom = dash.timeRestore ? timefilter.time.from : undefined;
|
||||
dash.timeTo = dash.timeRestore ? timefilter.time.to : undefined;
|
||||
dash.refreshInterval = dash.timeRestore ? timeRestoreObj : undefined;
|
||||
dash.optionsJSON = angular.toJson($state.options);
|
||||
|
||||
dash.save()
|
||||
|
|
|
@ -33,6 +33,7 @@ module.factory('SavedDashboard', function (courier, config) {
|
|||
timeRestore: false,
|
||||
timeTo: undefined,
|
||||
timeFrom: undefined,
|
||||
refreshInterval: undefined
|
||||
},
|
||||
|
||||
// if an indexPattern was saved with the searchsource of a SavedDashboard
|
||||
|
@ -56,6 +57,15 @@ module.factory('SavedDashboard', function (courier, config) {
|
|||
timeRestore: 'boolean',
|
||||
timeTo: 'string',
|
||||
timeFrom: 'string',
|
||||
refreshInterval: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
display: {type: 'string'},
|
||||
pause: { type: 'boolean'},
|
||||
section: { type: 'integer'},
|
||||
value: { type: 'integer'}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
SavedDashboard.searchsource = true;
|
||||
|
|
|
@ -86,7 +86,7 @@ module.exports = () => Joi.object({
|
|||
.default(),
|
||||
|
||||
ops: Joi.object({
|
||||
interval: Joi.number().default(10000),
|
||||
interval: Joi.number().default(5000),
|
||||
}),
|
||||
|
||||
plugins: Joi.object({
|
||||
|
|
|
@ -50,7 +50,7 @@ module.directive('kbnTopNav', function (Private) {
|
|||
// It will no accept any programatic way of setting its name
|
||||
// besides this because it happens so early in the digest cycle
|
||||
return `
|
||||
<navbar class="kibana-nav-options">
|
||||
<navbar ng-show="chrome.getVisible()" class="kibana-nav-options">
|
||||
<div ng-transclude></div>
|
||||
<div class="button-group kibana-nav-actions" role="toolbar">
|
||||
<button
|
||||
|
|
|
@ -38,6 +38,10 @@
|
|||
margin: 0 10px;
|
||||
border-bottom: 2px solid transparent;
|
||||
}
|
||||
// singular tabs are treated as titles
|
||||
> li:only-child > a {
|
||||
color: @kibanaGray1;
|
||||
}
|
||||
// Active, hover state for the getTabs
|
||||
> .active > a,
|
||||
> .active > a:hover,
|
||||
|
|
32
style_guides/api_style_guide.md
Normal file
|
@ -0,0 +1,32 @@
|
|||
|
||||
# API Style Guide
|
||||
|
||||
## Paths
|
||||
|
||||
API routes must start with the `/api/` path segment, and should be followed by the plugin id if applicable:
|
||||
|
||||
*Right:* `/api/marvel/nodes`
|
||||
*Wrong:* `/marvel/api/nodes`
|
||||
|
||||
## Versions
|
||||
|
||||
Kibana won't be supporting multiple API versions, so API's should not define a version.
|
||||
|
||||
*Right:* `/api/kibana/index_patterns`
|
||||
*Wrong:* `/api/kibana/v1/index_patterns`
|
||||
|
||||
## snake_case
|
||||
|
||||
Kibana uses `snake_case` for the entire API, just like Elasticsearch. All urls, paths, query string parameters, values, and bodies should be `snake_case` formatted.
|
||||
|
||||
*Right:*
|
||||
```
|
||||
POST /api/kibana/index_patterns
|
||||
{
|
||||
"id": "...",
|
||||
"time_field_name": "...",
|
||||
"fields": [
|
||||
...
|
||||
]
|
||||
}
|
||||
```
|
360
style_guides/css_style_guide.md
Normal file
|
@ -0,0 +1,360 @@
|
|||
|
||||
# CSS Style Guide
|
||||
|
||||
## Concepts
|
||||
|
||||
### Think in terms of components
|
||||
|
||||
Think in terms of everything as a component: a button, a footer with buttons in
|
||||
it, a list, a list item, the container around the list, the list title, etc.
|
||||
|
||||
Keep components as granular as possible.
|
||||
|
||||
Compose large, complex components out of smaller, simpler components.
|
||||
|
||||
### Introduce as little specificity as possible
|
||||
|
||||
Rules will need to overwrite other rules, and we can only do that via
|
||||
specificity. For that reason, it's important to avoid introducing specificity
|
||||
unless absolutely needed and that when we do so, we introduce as little as
|
||||
possible.
|
||||
|
||||
## Quick reference
|
||||
|
||||
Here are some examples of how to structure your styles. The
|
||||
rules that underly these examples are below.
|
||||
|
||||
```less
|
||||
.kbButton {
|
||||
padding: 5px;
|
||||
border: 1px solid black;
|
||||
|
||||
/**
|
||||
* 1. This button can appear in a "pressed" aka "pinned" state.
|
||||
*/
|
||||
&.is-button-pressed {
|
||||
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2); /* 1 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 1. Center icon and text vertically.
|
||||
*/
|
||||
.kbButton__icon,
|
||||
.kbButton__text {
|
||||
display: inline-block; /* 1 */
|
||||
vertical-align: middle; /* 1 */
|
||||
}
|
||||
|
||||
.kbButton__icon {
|
||||
color: gray;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.kbButton__text {
|
||||
color: black;
|
||||
}
|
||||
|
||||
.kbButton--primary {
|
||||
border-color: blue;
|
||||
|
||||
// Introduce specificity to color the descendant component.
|
||||
.kbButton__icon,
|
||||
.kbButton__text {
|
||||
color: blue;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
<button class="kbButton kbButton--primary">
|
||||
<div class="kbButton__icon">Submit</div>
|
||||
<div class="kbButton__text">Submit</div>
|
||||
</button>
|
||||
```
|
||||
|
||||
## Rules
|
||||
|
||||
### Use uniquely-named "base classes" to represent components
|
||||
|
||||
This component will be represented in the styles as a **base class**:
|
||||
|
||||
```less
|
||||
// We can use a namespace like "kb" to make sure we don't affect
|
||||
// other styles accidentally, especially when we're using a generic
|
||||
// name like "button".
|
||||
.kbButton {
|
||||
background-color: gray;
|
||||
color: black;
|
||||
border-radius: 4px;
|
||||
padding: 4px;
|
||||
}
|
||||
```
|
||||
|
||||
### Create "descendant classes" to represent child components which can't stand on their own
|
||||
|
||||
In this example, the text and the icon are very tightly coupled to the button
|
||||
component. They aren't supposed to be used outside of this component. So we
|
||||
can indicate this parent-child relationship with a double-underscore and by
|
||||
indenting the **descendant classes**.
|
||||
|
||||
```less
|
||||
.kbButton {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbButton__icon {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.kbButton__text {
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
font-weight: 300;
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
<button class="kbButton">
|
||||
<div class="kbButton__icon fa fa-trophy"></div>
|
||||
<div class="kbButton__text">Winner</div>
|
||||
</button>
|
||||
```
|
||||
|
||||
### Think of deeply-nested child components as "subcomponents" instead of descendants
|
||||
|
||||
Some components can have subcomponents that have their own subcomponents, and so on.
|
||||
In this kind of situation, using the descendant class rule above, would get
|
||||
pretty hairy. Consider a table component:
|
||||
|
||||
```less
|
||||
// ======================== Bad! ========================
|
||||
// These styles are complex and the multiple double-underscores increases noise
|
||||
// without providing much useful information.
|
||||
.kbTable {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbTable__body {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbTable__body__row {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbTable__body__row__cell {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
In this situation, it's better to create separate subcomponent base classes
|
||||
in their own files. It's important to still name the classes in a way that
|
||||
indicates their relationship, by incorporating the name of the root base class.
|
||||
|
||||
```less
|
||||
// kbTable.less
|
||||
.kbTable {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
```less
|
||||
// kbTableBody.less
|
||||
.kbTableBody {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
```less
|
||||
// kbTableRow.less
|
||||
.kbTableRow {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbTableRow__cell {
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
This is an example of how we can use files and class names to scale a component
|
||||
as it grows in complexity.
|
||||
|
||||
### Represent states with "state classes"
|
||||
|
||||
If a user interacts with a component, or a change in application state needs to
|
||||
be surfaced in the UI, then create **state classes**. These classes will be applied
|
||||
to components in response to these changes.
|
||||
|
||||
Notice that all states begin with a boolean keyword, typically "is-".
|
||||
|
||||
```less
|
||||
.kbButton {
|
||||
/* ... */
|
||||
|
||||
/**
|
||||
* 1. This button can appear in a "pressed" aka "pinned" state.
|
||||
*/
|
||||
&.is-button-pressed {
|
||||
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2); /* 1 */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Variations on a component are represented with "modifier classes"
|
||||
|
||||
If the UI calls for a component to change along a single axis of semantic
|
||||
meaning, create modifier classes. **Modifier classes** are different than states,
|
||||
in that they will not be applied to a component as a result of user interaction
|
||||
or a change in application state.
|
||||
|
||||
```less
|
||||
.kbButton {
|
||||
/* ... */
|
||||
}
|
||||
|
||||
.kbButton--primary {
|
||||
color: white;
|
||||
background-color: blue;
|
||||
}
|
||||
|
||||
.kbButton--danger {
|
||||
color: white;
|
||||
background-color: red;
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
<button class="kbButton kbButton--danger">
|
||||
Delete everything
|
||||
<button>
|
||||
```
|
||||
|
||||
### Don't use multiple modifier classes together
|
||||
|
||||
If the design calls for buttons that look like this:
|
||||
|
||||
```
|
||||
+------------+
|
||||
| |
|
||||
| Button |
|
||||
| |
|
||||
+------------+
|
||||
+------------+
|
||||
| |
|
||||
| BUTTON |
|
||||
| |
|
||||
+------------+
|
||||
```
|
||||
|
||||
It might be tempting to create modifiers that can be combined, like this:
|
||||
|
||||
```less
|
||||
// ======================== Bad! ========================
|
||||
.kbButton--large {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.kbButton--loud {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
<button class="kbButton kbButton--large">
|
||||
Button
|
||||
</button>
|
||||
<button class="kbButton kbButton--large kbButton--loud">
|
||||
Button
|
||||
</button>
|
||||
```
|
||||
|
||||
Down this path lies trouble. Each class loses its semantic meaning and essentially
|
||||
becomes an inline style. So usually trying to use multiple modifier classes
|
||||
together is a _code smell_.
|
||||
|
||||
Instead of this, it's important to **talk with the designer** and assign a semantic
|
||||
name to each of these types of buttons, which can then be reflected with
|
||||
unique base or modifier classes. Discussing use cases and defining the role of
|
||||
the component is a good way to approach this conversation.
|
||||
|
||||
```
|
||||
+---------------------+
|
||||
| |
|
||||
| Call-out button |
|
||||
| |
|
||||
+---------------------+
|
||||
+-----------------------------+
|
||||
| |
|
||||
| PRIMARY CALL-OUT BUTTON |
|
||||
| |
|
||||
+-----------------------------+
|
||||
```
|
||||
|
||||
```less
|
||||
// This button is used for calls-to-action, e.g. "Sign up for our newsletter".
|
||||
// Generally, no more than one will ever appear on a given page.
|
||||
.kbCallOutButton {
|
||||
background-color: gray;
|
||||
color: black;
|
||||
border-radius: 4px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.kbCallOutButton--primary {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
```
|
||||
|
||||
```html
|
||||
<button class="kbCallOutButton">
|
||||
Call-out button
|
||||
</button>
|
||||
<button class="kbCallOutButton kbCallOutButton--primary">
|
||||
Primary call-out button
|
||||
</button>
|
||||
```
|
||||
|
||||
### How to apply DRY
|
||||
|
||||
The above example might look counter-DRY to you, since the kbButton and
|
||||
kbCallOutButton have so many common properties.
|
||||
|
||||
In general, it's more important to keep styles tightly-scoped to clearly-defined
|
||||
components (which increases readability and maintainabilty) than it is to keep
|
||||
them DRY.
|
||||
|
||||
But if you really think there is a compelling reason to deduplicate code, then
|
||||
try using a mixin.
|
||||
|
||||
```less
|
||||
// Use the suffix "mixin" to avoid confusing this with a base class.
|
||||
.kbButtonMixin {
|
||||
background-color: gray;
|
||||
color: black;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.kbButton {
|
||||
&:extend(.kbButtonMixin all);
|
||||
}
|
||||
|
||||
.kbCallOutButton {
|
||||
&:extend(.kbButtonMixin all);
|
||||
}
|
||||
```
|
||||
|
||||
#### Compelling reasons for using mixins
|
||||
|
||||
A super-compelling reason to use mixins is if you see that a set of different
|
||||
components have a set of the same rules applied to all of them, and that it's
|
||||
likely that any change made to one of them will have to made to the rest, too
|
||||
(it might be a good idea to double-check this with the designer).
|
||||
|
||||
In this case, a mixin can be very useful because then you only need to make the
|
||||
change in one place. Consider the above `kbButtonMixin` example. Now if the
|
||||
border-radius changes for all buttons, you only need to change it there. Or if
|
||||
the designers anticipate that all new types of buttons should have the same
|
||||
border-radius, then you can just extend this mixin when you create a new button
|
||||
base class.
|
18
style_guides/html_style_guide.md
Normal file
|
@ -0,0 +1,18 @@
|
|||
|
||||
# HTML Style Guide
|
||||
|
||||
## Multiple attribute values
|
||||
|
||||
When a node has multiple attributes that would cause it to exceed the 80-character line limit, each attribute including the first should be on its own line with a single indent. Also, when a node that is styled in this way has child nodes, there should be a blank line between the opening parent tag and the first child tag.
|
||||
|
||||
```
|
||||
<ul
|
||||
attribute1="value1"
|
||||
attribute2="value2"
|
||||
attribute3="value3">
|
||||
|
||||
<li></li>
|
||||
<li></li>
|
||||
...
|
||||
</ul>
|
||||
```
|
765
style_guides/js_style_guide.md
Normal file
|
@ -0,0 +1,765 @@
|
|||
|
||||
# JavaScript Style Guide
|
||||
|
||||
## Attribution
|
||||
|
||||
This JavaScript guide forked from the [node style guide](https://github.com/felixge/node-style-guide) created by [Felix Geisendörfer](http://felixge.de/) and is
|
||||
licensed under the [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/)
|
||||
license.
|
||||
|
||||
## 2 Spaces for indention
|
||||
|
||||
Use 2 spaces for indenting your code and swear an oath to never mix tabs and
|
||||
spaces - a special kind of hell is awaiting you otherwise.
|
||||
|
||||
## Newlines
|
||||
|
||||
Use UNIX-style newlines (`\n`), and a newline character as the last character
|
||||
of a file. Windows-style newlines (`\r\n`) are forbidden inside any repository.
|
||||
|
||||
## No trailing whitespace
|
||||
|
||||
Just like you brush your teeth after every meal, you clean up any trailing
|
||||
whitespace in your JS files before committing. Otherwise the rotten smell of
|
||||
careless neglect will eventually drive away contributors and/or co-workers.
|
||||
|
||||
## Use Semicolons
|
||||
|
||||
According to [scientific research][hnsemicolons], the usage of semicolons is
|
||||
a core value of our community. Consider the points of [the opposition][], but
|
||||
be a traditionalist when it comes to abusing error correction mechanisms for
|
||||
cheap syntactic pleasures.
|
||||
|
||||
[the opposition]: http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding
|
||||
[hnsemicolons]: http://news.ycombinator.com/item?id=1547647
|
||||
|
||||
## 120 characters per line
|
||||
|
||||
Try to limit your lines to 80 characters. If it feels right, you can go up to 120 characters.
|
||||
|
||||
## Use single quotes
|
||||
|
||||
Use single quotes, unless you are writing JSON.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var foo = 'bar';
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var foo = "bar";
|
||||
```
|
||||
|
||||
## Opening braces go on the same line
|
||||
|
||||
Your opening braces go on the same line as the statement.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
if (true) {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (true)
|
||||
{
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
Also, notice the use of whitespace before and after the condition statement.
|
||||
|
||||
## Always use braces for multi-line code
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (err)
|
||||
return cb(err);
|
||||
```
|
||||
|
||||
## Prefer multi-line conditionals
|
||||
|
||||
But single-line conditionals are allowed for short lines
|
||||
|
||||
*Preferred:*
|
||||
|
||||
```js
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
if (err) return cb(err);
|
||||
```
|
||||
|
||||
## Declare one variable per var statement
|
||||
|
||||
Declare one variable per var statement, it makes it easier to re-order the
|
||||
lines. However, ignore [Crockford][crockfordconvention] when it comes to
|
||||
declaring variables deeper inside a function, just put the declarations wherever
|
||||
they make sense.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var keys = ['foo', 'bar'];
|
||||
var values = [23, 42];
|
||||
|
||||
var object = {};
|
||||
while (keys.length) {
|
||||
var key = keys.pop();
|
||||
object[key] = values.pop();
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var keys = ['foo', 'bar'],
|
||||
values = [23, 42],
|
||||
object = {},
|
||||
key;
|
||||
|
||||
while (keys.length) {
|
||||
key = keys.pop();
|
||||
object[key] = values.pop();
|
||||
}
|
||||
```
|
||||
|
||||
[crockfordconvention]: http://javascript.crockford.com/code.html
|
||||
|
||||
## Use lowerCamelCase for variables, properties and function names
|
||||
|
||||
Variables, properties and function names should use `lowerCamelCase`. They
|
||||
should also be descriptive. Single character variables and uncommon
|
||||
abbreviations should generally be avoided.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var adminUser = db.query('SELECT * FROM users ...');
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var admin_user = db.query('SELECT * FROM users ...');
|
||||
```
|
||||
|
||||
## Use UpperCamelCase for class names
|
||||
|
||||
Class names should be capitalized using `UpperCamelCase`.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
function BankAccount() {
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function bank_Account() {
|
||||
}
|
||||
```
|
||||
|
||||
## Use UPPERCASE for Constants
|
||||
|
||||
Constants should be declared as regular variables or static class properties,
|
||||
using all uppercase letters.
|
||||
|
||||
Node.js / V8 actually supports mozilla's [const][const] extension, but
|
||||
unfortunately that cannot be applied to class members, nor is it part of any
|
||||
ECMA standard.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var SECOND = 1 * 1000;
|
||||
|
||||
function File() {
|
||||
}
|
||||
File.FULL_PERMISSIONS = 0777;
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
const SECOND = 1 * 1000;
|
||||
|
||||
function File() {
|
||||
}
|
||||
File.fullPermissions = 0777;
|
||||
```
|
||||
|
||||
[const]: https://developer.mozilla.org/en/JavaScript/Reference/Statements/const
|
||||
|
||||
## Magic numbers
|
||||
|
||||
These are numbers (or other values) simply used in line in your code. **Do not use these**, give them a variable name so they can be understood and changed easily.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var minWidth = 300;
|
||||
|
||||
if (width < minWidth) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (width < 300) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
## Global definitions
|
||||
|
||||
Don't do this. Everything should be wrapped in a module that can be depended on by other modules. Even things as simple as a single value should be a module.
|
||||
|
||||
## Function definitions
|
||||
|
||||
Prefer the use of function declarations over function expressions. Function expressions are allowed, but should usually be avoided.
|
||||
|
||||
Also, keep function definitions above other code instead of relying on function hoisting.
|
||||
|
||||
*Preferred:*
|
||||
|
||||
```js
|
||||
function myFunc() {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
var myFunc = function () {
|
||||
...
|
||||
};
|
||||
```
|
||||
|
||||
## Object / Array creation
|
||||
|
||||
Use trailing commas and put *short* declarations on a single line. Only quote
|
||||
keys when your interpreter complains:
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = ['hello', 'world'];
|
||||
var b = {
|
||||
good: 'code',
|
||||
'is generally': 'pretty'
|
||||
};
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var a = [
|
||||
'hello', 'world'
|
||||
];
|
||||
var b = {"good": 'code'
|
||||
, is generally: 'pretty'
|
||||
};
|
||||
```
|
||||
|
||||
## Object / Array iterations, transformations and operations
|
||||
|
||||
Use native ES5 methods to iterate and transform arrays and objects where possible. Do not use `for` and `while` loops.
|
||||
|
||||
Use descriptive variable names in the closures.
|
||||
|
||||
Use a utility library as needed and where it will make code more comprehensible.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var userNames = users.map(function (user) {
|
||||
return user.name;
|
||||
});
|
||||
|
||||
// examples where lodash makes the code more readable
|
||||
var userNames = _.pluck(users, 'name');
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var userNames = [];
|
||||
for (var i = 0; i < users.length; i++) {
|
||||
userNames.push(users[i].name);
|
||||
}
|
||||
```
|
||||
|
||||
## Use the === operator
|
||||
|
||||
Programming is not about remembering [stupid rules][comparisonoperators]. Use
|
||||
the triple equality operator as it will work just as expected.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = 0;
|
||||
if (a !== '') {
|
||||
console.log('winning');
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var a = 0;
|
||||
if (a == '') {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
[comparisonoperators]: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
|
||||
|
||||
## Only use ternary operators for small, simple code
|
||||
|
||||
And **never** use multiple ternaries together
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var foo = (a === b) ? 1 : 2;
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
var foo = (a === b) ? 1 : (a === c) ? 2 : 3;
|
||||
```
|
||||
|
||||
## Do not extend built-in prototypes
|
||||
|
||||
Do not extend the prototype of native JavaScript objects. Your future self will
|
||||
be forever grateful.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var a = [];
|
||||
if (!a.length) {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
Array.prototype.empty = function() {
|
||||
return !this.length;
|
||||
}
|
||||
|
||||
var a = [];
|
||||
if (a.empty()) {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
## Use descriptive conditions
|
||||
|
||||
Any non-trivial conditions should be assigned to a descriptively named variables, broken into
|
||||
several names variables, or converted to be a function:
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var thing = ...;
|
||||
var isShape = thing instanceof Shape;
|
||||
var notSquare = !(thing instanceof Square);
|
||||
var largerThan10 = isShape && thing.size > 10;
|
||||
|
||||
if (isShape && notSquare && largerThan10) {
|
||||
console.log('some big polygon');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (
|
||||
thing instanceof Shape
|
||||
&& !(thing instanceof Square)
|
||||
&& thing.size > 10
|
||||
) {
|
||||
console.log('bigger than ten?? Woah!');
|
||||
}
|
||||
```
|
||||
|
||||
## Name regular expressions
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
var validPasswordRE = /^(?=.*\d).{4,}$/;
|
||||
|
||||
if (password.length >= 4 && validPasswordRE.test(password)) {
|
||||
console.log('password is valid');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
if (password.length >= 4 && /^(?=.*\d).{4,}$/.test(password)) {
|
||||
console.log('losing');
|
||||
}
|
||||
```
|
||||
|
||||
## Write small functions
|
||||
|
||||
Keep your functions short. A good function fits on a slide that the people in
|
||||
the last row of a big room can comfortably read. So don't count on them having
|
||||
perfect vision and limit yourself to ~15 lines of code per function.
|
||||
|
||||
## Return early from functions
|
||||
|
||||
To avoid deep nesting of if-statements, always return a function's value as early
|
||||
as possible.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
if (val < 0) return false;
|
||||
if (val > 100) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
if (val >= 0) {
|
||||
if (val < 100) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Or for this particular example it may also be fine to shorten things even
|
||||
further:
|
||||
|
||||
```js
|
||||
function isPercentage(val) {
|
||||
var isInRange = (val >= 0 && val <= 100);
|
||||
return isInRange;
|
||||
}
|
||||
```
|
||||
|
||||
## Chaining operations
|
||||
|
||||
When using a chaining syntax (jquery or promises, for example), do not indent the subsequent chained operations, unless there is a logical grouping in them.
|
||||
|
||||
Also, if the chain is long, each method should be on a new line.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
$('.someClass')
|
||||
.addClass('another-class')
|
||||
.append(someElement)
|
||||
```
|
||||
|
||||
```js
|
||||
d3.selectAll('g.bar')
|
||||
.enter()
|
||||
.append('thing')
|
||||
.data(anything)
|
||||
.exit()
|
||||
.each(function() ... )
|
||||
```
|
||||
|
||||
```js
|
||||
$http.get('/info')
|
||||
.then(({ data }) => this.transfromInfo(data))
|
||||
.then((transformed) => $http.post('/new-info', transformed))
|
||||
.then(({ data }) => console.log(data));
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
$('.someClass')
|
||||
.addClass('another-class')
|
||||
.append(someElement)
|
||||
```
|
||||
|
||||
```js
|
||||
d3.selectAll('g.bar')
|
||||
.enter().append('thing').data(anything).exit()
|
||||
.each(function() ... )
|
||||
```
|
||||
|
||||
```js
|
||||
$http.get('/info')
|
||||
.then(({ data }) => this.transfromInfo(data))
|
||||
.then((transformed) => $http.post('/new-info', transformed))
|
||||
.then(({ data }) => console.log(data));
|
||||
```
|
||||
|
||||
## Name your closures
|
||||
|
||||
Feel free to give your closures a descriptive name. It shows that you care about them, and
|
||||
will produce better stack traces, heap and cpu profiles.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
req.on('end', function onEnd() {
|
||||
console.log('winning');
|
||||
});
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
req.on('end', function() {
|
||||
console.log('losing');
|
||||
});
|
||||
```
|
||||
|
||||
## No nested closures
|
||||
|
||||
Use closures, but don't nest them. Otherwise your code will become a mess.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
setTimeout(function() {
|
||||
client.connect(afterConnect);
|
||||
}, 1000);
|
||||
|
||||
function afterConnect() {
|
||||
console.log('winning');
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
setTimeout(function() {
|
||||
client.connect(function() {
|
||||
console.log('losing');
|
||||
});
|
||||
}, 1000);
|
||||
```
|
||||
|
||||
## Use slashes for comments
|
||||
|
||||
Use slashes for both single line and multi line comments. Try to write
|
||||
comments that explain higher level mechanisms or clarify difficult
|
||||
segments of your code. **Don't use comments to restate trivial things**.
|
||||
|
||||
***Exception:*** Comment blocks describing a function and its arguments (docblock) should start with `/**`, contain a single `*` at the beginning of each line, and end with `*/`.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
// 'ID_SOMETHING=VALUE' -> ['ID_SOMETHING=VALUE', 'SOMETHING', 'VALUE']
|
||||
var matches = item.match(/ID_([^\n]+)=([^\n]+)/));
|
||||
|
||||
/**
|
||||
* Fetches a user from...
|
||||
* @param {string} id - id of the user
|
||||
* @return {Promise}
|
||||
*/
|
||||
function loadUser(id) {
|
||||
// This function has a nasty side effect where a failure to increment a
|
||||
// redis counter used for statistics will cause an exception. This needs
|
||||
// to be fixed in a later iteration.
|
||||
|
||||
...
|
||||
}
|
||||
|
||||
var isSessionValid = (session.expires < Date.now());
|
||||
if (isSessionValid) {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
// Execute a regex
|
||||
var matches = item.match(/ID_([^\n]+)=([^\n]+)/));
|
||||
|
||||
// Usage: loadUser(5, function() { ... })
|
||||
function loadUser(id, cb) {
|
||||
// ...
|
||||
}
|
||||
|
||||
// Check if the session is valid
|
||||
var isSessionValid = (session.expires < Date.now());
|
||||
// If the session is valid
|
||||
if (isSessionValid) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
## Do not comment out code
|
||||
|
||||
We use a version management system. If a line of code is no longer needed, remove it, don't simply comment it out.
|
||||
|
||||
## Classes/Constructors and Inheritance
|
||||
|
||||
While JavaScript it is not always considered an object-oriented language, it does have the building blocks for writing object oriented code. Of course, as with all things JavaScript, there are many ways this can be accomplished. Generally, we try to err on the side of readability.
|
||||
|
||||
### Capitalized function definition as Constructors
|
||||
|
||||
When Defining a Class/Constructor, use the function definition syntax.
|
||||
|
||||
*Right:*
|
||||
```js
|
||||
function ClassName() {
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
```js
|
||||
var ClassName = function () {};
|
||||
```
|
||||
|
||||
### Inheritance should be done with a utility
|
||||
|
||||
While you can do it with pure JS, a utility will remove a lot of boilerplate, and be more readable and functional.
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
// uses a lodash inherits mixin
|
||||
// inheritance is defined first - it's easier to read and the function will be hoisted
|
||||
_.class(Square).inherits(Shape);
|
||||
|
||||
function Square(width, height) {
|
||||
Square.Super.call(this);
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
function Square(width, height) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
Square.prototype = Object.create(Shape);
|
||||
```
|
||||
|
||||
### Keep Constructors Small
|
||||
|
||||
It is often the case that there are properties that can't be defined on the prototype, or work that needs to be done to completely create an object (like call its Super class). This is all that should be done within constructors.
|
||||
|
||||
Try to follow the [Write small functions](#write-small-functions) rule here too.
|
||||
|
||||
### Use the prototype
|
||||
|
||||
If a method/property *can* go on the prototype, it probably should.
|
||||
|
||||
```js
|
||||
function Square() {
|
||||
...
|
||||
}
|
||||
|
||||
/**
|
||||
* method does stuff
|
||||
* @return {undefined}
|
||||
*/
|
||||
Square.prototype.method = function () {
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Handling scope and aliasing `this`
|
||||
|
||||
When creating a prototyped class, each method should almost always start with:
|
||||
|
||||
`var self = this;`
|
||||
|
||||
With the exception of very short methods (roughly 3 lines or less), `self` should always be used in place of `this`.
|
||||
|
||||
Avoid the use of `bind`
|
||||
|
||||
*Right:*
|
||||
|
||||
```js
|
||||
Square.prototype.doFancyThings = function () {
|
||||
var self = this;
|
||||
|
||||
somePromiseUtil()
|
||||
.then(function (result) {
|
||||
self.prop = result.prop;
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
*Wrong:*
|
||||
|
||||
```js
|
||||
Square.prototype.doFancyThings = function () {
|
||||
somePromiseUtil()
|
||||
.then(function (result) {
|
||||
this.prop = result.prop;
|
||||
}).bind(this);
|
||||
}
|
||||
```
|
||||
|
||||
*Allowed:*
|
||||
|
||||
```js
|
||||
Square.prototype.area = function () {
|
||||
return this.width * this.height;
|
||||
}
|
||||
```
|
||||
|
||||
## Object.freeze, Object.preventExtensions, Object.seal, with, eval
|
||||
|
||||
Crazy shit that you will probably never need. Stay away from it.
|
||||
|
||||
## Getters and Setters
|
||||
|
||||
Feel free to use getters that are free from [side effects][sideeffect], like
|
||||
providing a length property for a collection class.
|
||||
|
||||
Do not use setters, they cause more problems for people who try to use your
|
||||
software than they can solve.
|
||||
|
||||
[sideeffect]: http://en.wikipedia.org/wiki/Side_effect_(computer_science)
|
|
@ -1,55 +1,74 @@
|
|||
module.exports = function (grunt) {
|
||||
const { resolve } = require('path');
|
||||
const { indexBy } = require('lodash');
|
||||
import { resolve } from 'path';
|
||||
import { indexBy } from 'lodash';
|
||||
import exec from '../utils/exec';
|
||||
|
||||
const { config } = grunt;
|
||||
const exec = require('../utils/exec');
|
||||
const targetDir = config.get('target');
|
||||
const version = config.get('pkg.version');
|
||||
const userScriptsDir = config.get('userScriptsDir');
|
||||
const servicesByName = indexBy(config.get('services'), 'name');
|
||||
export default (grunt) => {
|
||||
const targetDir = grunt.config.get('target');
|
||||
const packageScriptsDir = grunt.config.get('packageScriptsDir');
|
||||
const servicesByName = indexBy(grunt.config.get('services'), 'name');
|
||||
const config = grunt.config.get('packages');
|
||||
const fpm = args => exec('fpm', args);
|
||||
|
||||
grunt.registerTask('_build:osPackages', function () {
|
||||
grunt.config.get('platforms').forEach(({ name, buildDir }) => {
|
||||
// TODO(sissel): Check if `fpm` is available
|
||||
if (!(/linux-x(86|64)$/.test(name))) return;
|
||||
|
||||
const arch = /x64$/.test(name) ? 'x86_64' : 'i386';
|
||||
const fpm = args => exec('fpm', args);
|
||||
|
||||
const args = [
|
||||
grunt.config.get('platforms')
|
||||
.filter(({ name }) => /linux-x(86|64)$/.test(name))
|
||||
.map(({ name, buildDir }) => {
|
||||
const architecture = /x64$/.test(name) ? 'x86_64' : 'i386';
|
||||
return {
|
||||
buildDir,
|
||||
architecture
|
||||
};
|
||||
})
|
||||
.forEach(({ buildDir, architecture }) => {
|
||||
const baseOptions = [
|
||||
'--force',
|
||||
'--package', targetDir,
|
||||
'-s', 'dir', // input type
|
||||
'--name', 'kibana',
|
||||
'--description', 'Explore\ and\ visualize\ your\ Elasticsearch\ data.',
|
||||
'--version', version,
|
||||
'--url', 'https://www.elastic.co',
|
||||
'--vendor', 'Elasticsearch,\ Inc.',
|
||||
'--maintainer', 'Kibana Team\ \<info@elastic.co\>',
|
||||
'--license', 'Apache\ 2.0',
|
||||
'--after-install', resolve(userScriptsDir, 'installer.sh'),
|
||||
'--after-remove', resolve(userScriptsDir, 'remover.sh'),
|
||||
'--config-files', '/opt/kibana/config/kibana.yml'
|
||||
'--architecture', architecture,
|
||||
'--name', config.name,
|
||||
'--description', config.description,
|
||||
'--version', config.version,
|
||||
'--url', config.site,
|
||||
'--vendor', config.vendor,
|
||||
'--maintainer', config.maintainer,
|
||||
'--license', config.license,
|
||||
'--after-install', resolve(packageScriptsDir, 'post_install.sh'),
|
||||
'--before-install', resolve(packageScriptsDir, 'pre_install.sh'),
|
||||
'--before-remove', resolve(packageScriptsDir, 'pre_remove.sh'),
|
||||
'--after-remove', resolve(packageScriptsDir, 'post_remove.sh'),
|
||||
'--config-files', config.path.kibanaConfig,
|
||||
'--template-value', `user=${config.user}`,
|
||||
'--template-value', `group=${config.group}`,
|
||||
'--template-value', `optimizeDir=${config.path.home}/optimize`,
|
||||
|
||||
//config folder is moved to path.conf, exclude {path.home}/config
|
||||
//uses relative path to --prefix, strip the leading /
|
||||
'--exclude', `${config.path.home.slice(1)}/config`
|
||||
];
|
||||
const debOptions = [
|
||||
'-t', 'deb',
|
||||
'--deb-priority', 'optional'
|
||||
];
|
||||
const rpmOptions = [
|
||||
'-t', 'rpm',
|
||||
'--rpm-os', 'linux'
|
||||
];
|
||||
const args = [
|
||||
`${buildDir}/=${config.path.home}/`,
|
||||
`${buildDir}/config/=${config.path.conf}/`,
|
||||
`${servicesByName.sysv.outputDir}/etc/=/etc/`,
|
||||
`${servicesByName.systemd.outputDir}/lib/=/lib/`
|
||||
];
|
||||
|
||||
const files = buildDir + '/=/opt/kibana';
|
||||
const sysv = servicesByName.sysv.outputDir + '/etc/=/etc/';
|
||||
const systemd = servicesByName.systemd.outputDir + '/lib/=/lib/';
|
||||
|
||||
//Manually find flags, multiple args without assignment are not entirely parsed
|
||||
var flags = grunt.option.flags().join(',');
|
||||
|
||||
const buildDeb = !!flags.match('deb');
|
||||
const buildRpm = !!flags.match('rpm');
|
||||
const noneSpecified = !buildRpm && !buildDeb;
|
||||
|
||||
grunt.file.mkdir(targetDir);
|
||||
if (buildDeb || noneSpecified) {
|
||||
fpm(args.concat('-t', 'deb', '--deb-priority', 'optional', '-a', arch, files, sysv, systemd));
|
||||
const flags = grunt.option.flags().filter(flag => /deb|rpm/.test(flag)).join(',');
|
||||
const buildDeb = flags.includes('deb') || !flags.length;
|
||||
const buildRpm = flags.includes('rpm') || !flags.length;
|
||||
if (buildDeb) {
|
||||
fpm([...baseOptions, ...debOptions, ...args]);
|
||||
}
|
||||
if (buildRpm || noneSpecified) {
|
||||
fpm(args.concat('-t', 'rpm', '-a', arch, '--rpm-os', 'linux', files, sysv, systemd));
|
||||
if (buildRpm) {
|
||||
fpm([...baseOptions, ...rpmOptions, ...args]);
|
||||
}
|
||||
|
||||
});
|
||||
|
|
17
tasks/build/package_scripts/post_install.sh
Normal file
|
@ -0,0 +1,17 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
user_check() {
|
||||
getent passwd "$1" > /dev/null 2>&1
|
||||
}
|
||||
|
||||
user_create() {
|
||||
# Create a system user. A system user is one within the system uid range and
|
||||
# has no expiration
|
||||
useradd -r "$1"
|
||||
}
|
||||
|
||||
if ! user_check "<%= user %>" ; then
|
||||
user_create "<%= user %>"
|
||||
fi
|
||||
chown -R <%= user %>:<%= group %> <%= optimizeDir %>
|
42
tasks/build/package_scripts/post_remove.sh
Normal file
|
@ -0,0 +1,42 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
user_check() {
|
||||
getent passwd "$1" > /dev/null 2>&1
|
||||
}
|
||||
|
||||
user_remove() {
|
||||
userdel "$1"
|
||||
}
|
||||
|
||||
REMOVE_USER=false
|
||||
|
||||
case $1 in
|
||||
# Includes cases for all valid arguments, exit 1 otherwise
|
||||
# Debian
|
||||
purge)
|
||||
REMOVE_USER=true
|
||||
;;
|
||||
|
||||
remove|failed-upgrade|abort-install|abort-upgrade|disappear|upgrade|disappear)
|
||||
;;
|
||||
|
||||
# Red Hat
|
||||
0)
|
||||
REMOVE_USER=true
|
||||
;;
|
||||
|
||||
1)
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "post remove script called with unknown argument \`$1'" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ "$REMOVE_USER" = "true" ]; then
|
||||
if user_check "<%= user %>" ; then
|
||||
user_remove "<%= user %>"
|
||||
fi
|
||||
fi
|
14
tasks/build/package_scripts/pre_install.sh
Normal file
|
@ -0,0 +1,14 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
if command -v systemctl >/dev/null && systemctl is-active kibana.service >/dev/null; then
|
||||
systemctl --no-reload stop kibana.service
|
||||
elif [ -x /etc/init.d/kibana ]; then
|
||||
if command -v invoke-rc.d >/dev/null; then
|
||||
invoke-rc.d kibana stop
|
||||
elif command -v service >/dev/null; then
|
||||
service kibana stop
|
||||
else
|
||||
/etc/init.d/kibana stop
|
||||
fi
|
||||
fi
|
16
tasks/build/package_scripts/pre_remove.sh
Normal file
|
@ -0,0 +1,16 @@
|
|||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
echo -n "Stopping kibana service..."
|
||||
if command -v systemctl >/dev/null && systemctl is-active kibana.service >/dev/null; then
|
||||
systemctl --no-reload stop kibana.service
|
||||
elif [ -x /etc/init.d/kibana ]; then
|
||||
if command -v invoke-rc.d >/dev/null; then
|
||||
invoke-rc.d kibana stop
|
||||
elif command -v service >/dev/null; then
|
||||
service kibana stop
|
||||
else
|
||||
/etc/init.d/kibana stop
|
||||
fi
|
||||
fi
|
||||
echo " OK"
|
|
@ -1,31 +1,29 @@
|
|||
module.exports = function createServices(grunt) {
|
||||
const { resolve } = require('path');
|
||||
const { appendFileSync } = require('fs');
|
||||
const exec = require('../utils/exec');
|
||||
import { resolve } from 'path';
|
||||
import { appendFileSync } from 'fs';
|
||||
import exec from '../utils/exec';
|
||||
|
||||
export default (grunt) => {
|
||||
const userScriptsDir = grunt.config.get('userScriptsDir');
|
||||
const { path, user, group, name, description } = grunt.config.get('packages');
|
||||
|
||||
grunt.registerTask('_build:pleaseRun', function () {
|
||||
// TODO(sissel): Detect if 'pleaserun' is found, and provide a useful error
|
||||
// to the user if it is missing.
|
||||
|
||||
grunt.config.get('services').forEach(function (service) {
|
||||
grunt.config.get('services').forEach((service) => {
|
||||
grunt.file.mkdir(service.outputDir);
|
||||
exec('pleaserun', [
|
||||
'--install',
|
||||
'--no-install-actions',
|
||||
'--install-prefix', service.outputDir,
|
||||
'--overwrite',
|
||||
'--user', 'kibana',
|
||||
'--group', 'kibana',
|
||||
'--sysv-log-path', '/var/log/kibana/',
|
||||
'--name', name,
|
||||
'--description', description,
|
||||
'--user', user,
|
||||
'--group', group,
|
||||
'--sysv-log-path', path.logs,
|
||||
'-p', service.name,
|
||||
'-v', service.version,
|
||||
'/opt/kibana/bin/kibana'
|
||||
path.kibanaBin,
|
||||
`-c ${path.kibanaConfig}`
|
||||
]);
|
||||
});
|
||||
|
||||
grunt.file.mkdir(userScriptsDir);
|
||||
exec('please-manage-user', ['--output', userScriptsDir, 'kibana']);
|
||||
appendFileSync(resolve(userScriptsDir, 'installer.sh'), 'chown kibana:kibana /opt/kibana/optimize');
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,20 +1,52 @@
|
|||
export default (grunt) => {
|
||||
const version = grunt.config.get('pkg.version');
|
||||
const productionPath = `kibana/${version.match(/\d\.\d/)[0]}`;
|
||||
const stagingPath = `kibana/staging/${version.match(/\d\.\d\.\d/)[0]}-XXXXXXX/repos/${version.match(/\d\./)[0]}x`;
|
||||
const rpmFolder = 'centos';
|
||||
const debFolder = 'debian';
|
||||
const VERSION = grunt.config.get('pkg.version');
|
||||
|
||||
const FOLDER_STAGING = `kibana/staging/${VERSION.match(/\d\.\d\.\d/)[0]}-XXXXXXX/repos/${VERSION.match(/\d\./)[0]}x`;
|
||||
const FOLDER_PRODUCTION = `kibana/${VERSION.match(/\d\.\d/)[0]}`;
|
||||
|
||||
const FOLDERNAME_DEB = 'debian';
|
||||
const FOLDERNAME_RPM = 'centos';
|
||||
|
||||
const PREFIX_STAGING_DEB = `${FOLDER_STAGING}/${FOLDERNAME_DEB}`;
|
||||
const PREFIX_STAGING_RPM = `${FOLDER_STAGING}/${FOLDERNAME_RPM}`;
|
||||
const PREFIX_PRODUCTION_DEB = `${FOLDER_PRODUCTION}/${FOLDERNAME_DEB}`;
|
||||
const PREFIX_PRODUCTION_RPM = `${FOLDER_PRODUCTION}/${FOLDERNAME_RPM}`;
|
||||
|
||||
const FOLDER_CONFIG = '/etc/kibana';
|
||||
const FOLDER_LOGS = '/var/log/kibana';
|
||||
const FOLDER_HOME = '/usr/share/kibana';
|
||||
|
||||
const FILE_KIBANA_CONF = `${FOLDER_CONFIG}/kibana.yml`;
|
||||
const FILE_KIBANA_BINARY = `${FOLDER_HOME}/bin/kibana`;
|
||||
|
||||
return {
|
||||
staging: {
|
||||
bucket: 'download.elasticsearch.org',
|
||||
debPrefix: `${stagingPath}/${debFolder}`,
|
||||
rpmPrefix: `${stagingPath}/${rpmFolder}`
|
||||
publish: {
|
||||
staging: {
|
||||
bucket: 'download.elasticsearch.org',
|
||||
debPrefix: PREFIX_STAGING_DEB,
|
||||
rpmPrefix: PREFIX_STAGING_RPM
|
||||
},
|
||||
production: {
|
||||
bucket: 'packages.elasticsearch.org',
|
||||
debPrefix: PREFIX_STAGING_DEB,
|
||||
rpmPrefix: PREFIX_STAGING_RPM
|
||||
}
|
||||
},
|
||||
production: {
|
||||
bucket: 'packages.elasticsearch.org',
|
||||
debPrefix: `${productionPath}/${debFolder}`,
|
||||
rpmPrefix: `${productionPath}/${rpmFolder}`
|
||||
user: 'kibana',
|
||||
group: 'kibana',
|
||||
name: 'kibana',
|
||||
description: 'Explore\ and\ visualize\ your\ Elasticsearch\ data',
|
||||
site: 'https://www.elastic.co',
|
||||
vendor: 'Elasticsearch,\ Inc.',
|
||||
maintainer: 'Kibana Team\ \<info@elastic.co\>',
|
||||
license: 'Apache\ 2.0',
|
||||
version: VERSION,
|
||||
path: {
|
||||
conf: FOLDER_CONFIG,
|
||||
logs: FOLDER_LOGS,
|
||||
home: FOLDER_HOME,
|
||||
kibanaBin: FILE_KIBANA_BINARY,
|
||||
kibanaConfig: FILE_KIBANA_CONF
|
||||
}
|
||||
};
|
||||
};
|
||||
|
|
|
@ -4,7 +4,7 @@ import { promisify } from 'bluebird';
|
|||
import readline from 'readline';
|
||||
|
||||
export default (grunt) => {
|
||||
const packages = grunt.config.get('packages');
|
||||
const publishConfig = grunt.config.get('packages').publish;
|
||||
const platforms = grunt.config.get('platforms');
|
||||
|
||||
function debS3(deb) {
|
||||
|
@ -87,8 +87,8 @@ export default (grunt) => {
|
|||
if (platform.debPath) {
|
||||
debS3({
|
||||
filePath: platform.debPath,
|
||||
bucket: packages[environment].bucket,
|
||||
prefix: packages[environment].debPrefix.replace('XXXXXXX', trimmedHash),
|
||||
bucket: publishConfig[environment].bucket,
|
||||
prefix: publishConfig[environment].debPrefix.replace('XXXXXXX', trimmedHash),
|
||||
signatureKeyId: signature.id,
|
||||
arch: platform.name.match('x64') ? 'amd64' : 'i386',
|
||||
awsKey: aws.key,
|
||||
|
@ -99,8 +99,8 @@ export default (grunt) => {
|
|||
if (platform.rpmPath) {
|
||||
rpmS3({
|
||||
filePath: platform.rpmPath,
|
||||
bucket: packages[environment].bucket,
|
||||
prefix: packages[environment].rpmPrefix.replace('XXXXXXX', trimmedHash),
|
||||
bucket: publishConfig[environment].bucket,
|
||||
prefix: publishConfig[environment].rpmPrefix.replace('XXXXXXX', trimmedHash),
|
||||
signingKeyName: signature.name,
|
||||
awsKey: aws.key,
|
||||
awsSecret: aws.secret
|
||||
|
|
|
@ -18,12 +18,8 @@ import {
|
|||
|
||||
common.debug('Starting dashboard before method');
|
||||
var logstash = scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
return esClient.delete('.kibana')
|
||||
.then(function () {
|
||||
return common.try(function () {
|
||||
return esClient.updateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'});
|
||||
});
|
||||
})
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
// and load a set of makelogs data
|
||||
.then(function loadkibanaVisualizations() {
|
||||
common.debug('load kibana index with visualizations');
|
||||
|
|
|
@ -5,6 +5,8 @@ import {
|
|||
headerPage,
|
||||
scenarioManager,
|
||||
settingsPage,
|
||||
esClient,
|
||||
elasticDump
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -18,20 +20,16 @@ import {
|
|||
var fromTime = '2015-09-19 06:31:44.000';
|
||||
var toTime = '2015-09-23 18:31:44.000';
|
||||
|
||||
// start each test with an empty kibana index
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
.then(function loadkibanaIndexPattern() {
|
||||
common.debug('load kibana index with default index pattern');
|
||||
return elasticDump.elasticLoad('visualize','.kibana');
|
||||
})
|
||||
// and load a set of makelogs data
|
||||
.then(function loadIfEmptyMakelogs() {
|
||||
return scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('navigateTo');
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('createIndexPattern');
|
||||
return settingsPage.createIndexPattern();
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('discover');
|
||||
return common.navigateToApp('discover');
|
||||
|
|
|
@ -5,6 +5,8 @@ import {
|
|||
discoverPage,
|
||||
settingsPage,
|
||||
headerPage,
|
||||
esClient,
|
||||
elasticDump
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -16,20 +18,16 @@ import {
|
|||
var fromTime = '2015-09-19 06:31:44.000';
|
||||
var toTime = '2015-09-23 18:31:44.000';
|
||||
|
||||
// start each test with an empty kibana index
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
.then(function loadkibanaIndexPattern() {
|
||||
common.debug('load kibana index with default index pattern');
|
||||
return elasticDump.elasticLoad('visualize','.kibana');
|
||||
})
|
||||
// and load a set of makelogs data
|
||||
.then(function loadIfEmptyMakelogs() {
|
||||
return scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
})
|
||||
.then(function (navigateTo) {
|
||||
common.debug('navigateTo');
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('createIndexPattern');
|
||||
return settingsPage.createIndexPattern();
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('discover');
|
||||
return common.navigateToApp('discover');
|
||||
|
|
|
@ -4,7 +4,9 @@ import {
|
|||
discoverPage,
|
||||
headerPage,
|
||||
scenarioManager,
|
||||
settingsPage
|
||||
settingsPage,
|
||||
esClient,
|
||||
elasticDump
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -16,20 +18,16 @@ import {
|
|||
var fromTime = '2015-09-19 06:31:44.000';
|
||||
var toTime = '2015-09-23 18:31:44.000';
|
||||
|
||||
// start each test with an empty kibana index
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
.then(function loadkibanaIndexPattern() {
|
||||
common.debug('load kibana index with default index pattern');
|
||||
return elasticDump.elasticLoad('visualize','.kibana');
|
||||
})
|
||||
// and load a set of makelogs data
|
||||
.then(function loadIfEmptyMakelogs() {
|
||||
return scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
})
|
||||
.then(function (navigateTo) {
|
||||
common.debug('navigateTo');
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('createIndexPattern');
|
||||
return settingsPage.createIndexPattern();
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('discover');
|
||||
return common.navigateToApp('discover');
|
||||
|
|
|
@ -1,4 +1,13 @@
|
|||
import { bdd, common, discoverPage, headerPage, settingsPage, scenarioManager } from '../../../support';
|
||||
import {
|
||||
bdd,
|
||||
common,
|
||||
discoverPage,
|
||||
headerPage,
|
||||
settingsPage,
|
||||
scenarioManager,
|
||||
esClient,
|
||||
elasticDump
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
var expect = require('expect.js');
|
||||
|
@ -18,20 +27,16 @@ import { bdd, common, discoverPage, headerPage, settingsPage, scenarioManager }
|
|||
var fromTime = '2015-09-19 06:31:44.000';
|
||||
var toTime = '2015-09-23 18:31:44.000';
|
||||
|
||||
// start each test with an empty kibana index
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
.then(function loadkibanaIndexPattern() {
|
||||
common.debug('load kibana index with default index pattern');
|
||||
return elasticDump.elasticLoad('visualize','.kibana');
|
||||
})
|
||||
// and load a set of makelogs data
|
||||
.then(function loadIfEmptyMakelogs() {
|
||||
return scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
})
|
||||
.then(function (navigateTo) {
|
||||
common.debug('navigateTo');
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('createIndexPattern');
|
||||
return settingsPage.createIndexPattern();
|
||||
})
|
||||
.then(function () {
|
||||
common.debug('discover');
|
||||
return common.navigateToApp('discover');
|
||||
|
|
|
@ -2,7 +2,8 @@ import {
|
|||
bdd,
|
||||
common,
|
||||
settingsPage,
|
||||
scenarioManager
|
||||
scenarioManager,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -11,7 +12,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('creating and deleting default index', function describeIndexTests() {
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc()
|
||||
.then(function () {
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
});
|
||||
|
@ -25,7 +27,7 @@ import {
|
|||
bdd.it('should allow setting advanced settings', function () {
|
||||
return settingsPage.clickAdvancedTab()
|
||||
.then(function TestCallSetAdvancedSettingsForTimezone() {
|
||||
common.log('calling setAdvancedSetting');
|
||||
common.debug('calling setAdvancedSetting');
|
||||
return settingsPage.setAdvancedSettings('dateFormat:tz', 'America/Phoenix');
|
||||
})
|
||||
.then(function GetAdvancedSetting() {
|
||||
|
|
|
@ -3,6 +3,7 @@ import {
|
|||
common,
|
||||
settingsPage,
|
||||
scenarioManager,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -11,7 +12,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('user input reactions', function () {
|
||||
bdd.beforeEach(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc()
|
||||
.then(function () {
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
});
|
||||
|
|
|
@ -3,7 +3,8 @@ import {
|
|||
common,
|
||||
remote,
|
||||
scenarioManager,
|
||||
settingsPage
|
||||
settingsPage,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -12,7 +13,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('creating and deleting default index', function describeIndexTests() {
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc()
|
||||
.then(function () {
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
});
|
||||
|
|
|
@ -2,7 +2,8 @@ import {
|
|||
bdd,
|
||||
common,
|
||||
scenarioManager,
|
||||
settingsPage
|
||||
settingsPage,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -11,7 +12,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('index result popularity', function describeIndexTests() {
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc()
|
||||
.then(function () {
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
});
|
||||
|
|
|
@ -4,6 +4,7 @@ import {
|
|||
defaultTimeout,
|
||||
settingsPage,
|
||||
scenarioManager,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -12,7 +13,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('index result field sort', function describeIndexTests() {
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana');
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc();
|
||||
});
|
||||
|
||||
var columns = [{
|
||||
|
|
|
@ -2,7 +2,8 @@ import {
|
|||
bdd,
|
||||
common,
|
||||
scenarioManager,
|
||||
settingsPage
|
||||
settingsPage,
|
||||
esClient
|
||||
} from '../../../support';
|
||||
|
||||
(function () {
|
||||
|
@ -11,7 +12,8 @@ import {
|
|||
(function () {
|
||||
bdd.describe('initial state', function () {
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
// delete .kibana index and then wait for Kibana to re-create it
|
||||
return esClient.deleteAndUpdateConfigDoc()
|
||||
.then(function () {
|
||||
return settingsPage.navigateTo().then(settingsPage.clickExistingIndicesAddDataLink);
|
||||
});
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { bdd, defaultTimeout, scenarioManager } from '../../../support';
|
||||
import { bdd, defaultTimeout, scenarioManager, esClient, common } from '../../../support';
|
||||
|
||||
(function () {
|
||||
bdd.describe('settings app', function () {
|
||||
|
@ -7,16 +7,13 @@ import { bdd, defaultTimeout, scenarioManager } from '../../../support';
|
|||
// on setup, we create an settingsPage instance
|
||||
// that we will use for all the tests
|
||||
bdd.before(function () {
|
||||
return scenarioManager.reload('emptyKibana')
|
||||
.then(function () {
|
||||
return scenarioManager.loadIfEmpty('makelogs');
|
||||
});
|
||||
return scenarioManager.loadIfEmpty('makelogs');
|
||||
});
|
||||
|
||||
bdd.after(function () {
|
||||
return scenarioManager.unload('makelogs')
|
||||
.then(function () {
|
||||
scenarioManager.unload('emptyKibana');
|
||||
return esClient.delete('.kibana');
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
@ -18,12 +18,8 @@ import {
|
|||
|
||||
common.debug('Starting visualize before method');
|
||||
var logstash = scenarioManager.loadIfEmpty('logstashFunctional');
|
||||
return esClient.delete('.kibana')
|
||||
.then(function () {
|
||||
return common.try(function () {
|
||||
return esClient.updateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'});
|
||||
});
|
||||
})
|
||||
// delete .kibana index and update configDoc
|
||||
return esClient.deleteAndUpdateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'})
|
||||
.then(function loadkibanaIndexPattern() {
|
||||
common.debug('load kibana index with default index pattern');
|
||||
return elasticDump.elasticLoad('visualize','.kibana');
|
||||
|
|
BIN
test/screenshots/baseline/screenshot-AreaChart.png
Normal file
After Width: | Height: | Size: 62 KiB |
BIN
test/screenshots/baseline/screenshot-Dashboard Test 1.png
Normal file
After Width: | Height: | Size: 162 KiB |
BIN
test/screenshots/baseline/screenshot-DataTable.png
Normal file
After Width: | Height: | Size: 44 KiB |
BIN
test/screenshots/baseline/screenshot-LineChart.png
Normal file
After Width: | Height: | Size: 41 KiB |
BIN
test/screenshots/baseline/screenshot-PieChart.png
Normal file
After Width: | Height: | Size: 70 KiB |
BIN
test/screenshots/baseline/screenshot-TileMap.png
Normal file
After Width: | Height: | Size: 675 KiB |
BIN
test/screenshots/baseline/screenshot-VerticalBarChart.png
Normal file
After Width: | Height: | Size: 48 KiB |
|
@ -42,16 +42,12 @@ export default (function () {
|
|||
});
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Add fields to the config doc (like setting timezone and defaultIndex)
|
||||
* @return {Promise} A promise that is resolved when elasticsearch has a response
|
||||
/*
|
||||
** Gets configId which is needed when we're going to update the config doc.
|
||||
** Also used after deleting .kibana index to know Kibana has recreated it.
|
||||
*/
|
||||
updateConfigDoc: function (docMap) {
|
||||
// first we need to get the config doc's id so we can use it in our _update call
|
||||
var self = this;
|
||||
getConfigId: function () {
|
||||
var configId;
|
||||
var docMapString = JSON.stringify(docMap);
|
||||
|
||||
return this.client.search({
|
||||
index: '.kibana',
|
||||
|
@ -70,11 +66,25 @@ export default (function () {
|
|||
} else {
|
||||
configId = response.hits.hits[0]._id;
|
||||
common.debug('config._id =' + configId);
|
||||
return configId;
|
||||
}
|
||||
})
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Add fields to the config doc (like setting timezone and defaultIndex)
|
||||
* @return {Promise} A promise that is resolved when elasticsearch has a response
|
||||
*/
|
||||
updateConfigDoc: function (docMap) {
|
||||
// first we need to get the config doc's id so we can use it in our _update call
|
||||
var self = this;
|
||||
var configId;
|
||||
var docMapString = JSON.stringify(docMap);
|
||||
|
||||
return this.getConfigId()
|
||||
// now that we have the id, we can update
|
||||
// return scenarioManager.updateConfigDoc({'dateFormat:tz':'UTC', 'defaultIndex':'logstash-*'});
|
||||
.then(function (response) {
|
||||
.then(function (configId) {
|
||||
common.debug('updating config with ' + docMapString);
|
||||
return self.client.update({
|
||||
index: '.kibana',
|
||||
|
@ -89,7 +99,35 @@ export default (function () {
|
|||
.catch(function (err) {
|
||||
throw err;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Wrap the common 'delete index', 'updateConfigDoc' into one.
|
||||
* [docMap] is optional.
|
||||
* @return {Promise} A promise that is resolved when elasticsearch has a response
|
||||
*/
|
||||
deleteAndUpdateConfigDoc: function (docMap) {
|
||||
var self = this;
|
||||
var configId;
|
||||
|
||||
return this.delete('.kibana')
|
||||
.then(function () {
|
||||
if (!docMap) {
|
||||
return common.try(function () {
|
||||
return self.getConfigId();
|
||||
});
|
||||
} else {
|
||||
var docMapString = JSON.stringify(docMap);
|
||||
return common.try(function () {
|
||||
return self.updateConfigDoc(docMap);
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(function (err) {
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return EsClient;
|
||||
|
|
|
@ -1,11 +1,16 @@
|
|||
import { config, defaultTryTimeout, defaultFindTimeout, remote, shieldPage } from '../';
|
||||
import fs from 'fs';
|
||||
import mkdirp from 'mkdirp';
|
||||
import { promisify } from 'bluebird';
|
||||
|
||||
const mkdirpAsync = promisify(mkdirp);
|
||||
const writeFileAsync = promisify(fs.writeFile);
|
||||
|
||||
export default (function () {
|
||||
var Promise = require('bluebird');
|
||||
var moment = require('moment');
|
||||
var testSubjSelector = require('@spalger/test-subj-selector');
|
||||
var getUrl = require('../../utils/get_url');
|
||||
var fs = require('fs');
|
||||
var _ = require('lodash');
|
||||
var parse = require('url').parse;
|
||||
var format = require('url').format;
|
||||
|
@ -244,34 +249,32 @@ export default (function () {
|
|||
.then(function () { self.debug('... sleep(' + sleepMilliseconds + ') end'); });
|
||||
},
|
||||
|
||||
handleError: function (testObj) {
|
||||
var self = this;
|
||||
var testName = (testObj.parent) ? [testObj.parent.name, testObj.name].join('_') : testObj.name;
|
||||
handleError(testObj) {
|
||||
const testName = (testObj.parent) ? [testObj.parent.name, testObj.name].join('_') : testObj.name;
|
||||
return reason => {
|
||||
const now = Date.now();
|
||||
const fileName = `failure_${now}_${testName}.png`;
|
||||
|
||||
return function (reason) {
|
||||
var now = Date.now();
|
||||
var filename = ['failure', now, testName].join('_') + '.png';
|
||||
|
||||
return self.saveScreenshot(filename)
|
||||
.finally(function () {
|
||||
return this.saveScreenshot(fileName, true)
|
||||
.then(function () {
|
||||
throw reason;
|
||||
});
|
||||
};
|
||||
},
|
||||
|
||||
saveScreenshot: function saveScreenshot(filename) {
|
||||
var self = this;
|
||||
var outDir = path.resolve('test', 'output');
|
||||
async saveScreenshot(fileName, isFailure = false) {
|
||||
try {
|
||||
const directoryName = isFailure ? 'failure' : 'session';
|
||||
const directoryPath = path.resolve(`test/screenshots/${directoryName}`);
|
||||
const filePath = path.resolve(directoryPath, fileName);
|
||||
this.debug(`Taking screenshot "${filePath}"`);
|
||||
|
||||
return self.remote.takeScreenshot()
|
||||
.then(function writeScreenshot(data) {
|
||||
var filepath = path.resolve(outDir, filename);
|
||||
self.debug('Taking screenshot "' + filepath + '"');
|
||||
fs.writeFileSync(filepath, data);
|
||||
})
|
||||
.catch(function (err) {
|
||||
self.log('SCREENSHOT FAILED: ' + err);
|
||||
});
|
||||
const screenshot = await this.remote.takeScreenshot();
|
||||
await mkdirpAsync(directoryPath);
|
||||
await writeFileAsync(filePath, screenshot);
|
||||
} catch (err) {
|
||||
this.log(`SCREENSHOT FAILED: ${err}`);
|
||||
}
|
||||
},
|
||||
|
||||
findTestSubject: function findTestSubject(selector) {
|
||||
|
|
43
utilities/compareScreenshots.js
Normal file
|
@ -0,0 +1,43 @@
|
|||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const imageDiff = require('image-diff');
|
||||
const mkdirp = require('mkdirp');
|
||||
|
||||
function compareScreenshots() {
|
||||
const SCREENSHOTS_DIR = 'test/screenshots';
|
||||
const BASELINE_SCREENSHOTS_DIR = path.resolve(SCREENSHOTS_DIR, 'baseline');
|
||||
const DIFF_SCREENSHOTS_DIR = path.resolve(SCREENSHOTS_DIR, 'diff');
|
||||
const SESSION_SCREENSHOTS_DIR = path.resolve(SCREENSHOTS_DIR, 'session');
|
||||
|
||||
// We don't need to create the baseline dir because it's committed.
|
||||
mkdirp.sync(DIFF_SCREENSHOTS_DIR);
|
||||
mkdirp.sync(SESSION_SCREENSHOTS_DIR);
|
||||
|
||||
fs.readdir(SESSION_SCREENSHOTS_DIR, (readDirError, files) => {
|
||||
const screenshots = files.filter(file => file.indexOf('.png') !== -1);
|
||||
|
||||
screenshots.forEach(screenshot => {
|
||||
const sessionImagePath = path.resolve(SESSION_SCREENSHOTS_DIR, screenshot);
|
||||
const baselineImagePath = path.resolve(BASELINE_SCREENSHOTS_DIR, screenshot);
|
||||
const diffImagePath = path.resolve(DIFF_SCREENSHOTS_DIR, screenshot);
|
||||
|
||||
imageDiff.getFullResult({
|
||||
actualImage: sessionImagePath,
|
||||
expectedImage: baselineImagePath,
|
||||
diffImage: diffImagePath,
|
||||
shadow: true,
|
||||
}, (comparisonError, result) => {
|
||||
if (comparisonError) {
|
||||
throw comparisonError;
|
||||
}
|
||||
|
||||
const change = result.percentage;
|
||||
const changePercentage = (change * 100).toFixed(2);
|
||||
console.log(`${screenshot} has changed by ${changePercentage}%`);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
compareScreenshots();
|