chore: add code formatting and linting (#952)

This commit is contained in:
Caleb
2018-08-07 14:46:54 -06:00
committed by Shawn Erquhart
parent 32e0a9b2b5
commit f801b19221
265 changed files with 5988 additions and 4481 deletions

View File

@ -8,7 +8,7 @@ import {
shadows,
colors,
colorsRaw,
lengths
lengths,
} from 'netlify-cms-ui-default';
const LoginButton = styled.button`
@ -21,12 +21,12 @@ const LoginButton = styled.button`
display: block;
margin-top: 20px;
margin-left: auto;
`
`;
const AuthForm = styled.form`
width: 350px;
margin-top: -80px;
`
`;
const AuthInput = styled.input`
background-color: ${colorsRaw.white};
@ -44,16 +44,16 @@ const AuthInput = styled.input`
outline: none;
box-shadow: inset 0 0 0 2px ${colors.active};
}
`
`;
const ErrorMessage = styled.p`
color: ${colors.errorText};
`
`;
let component = null;
if (window.netlifyIdentity) {
window.netlifyIdentity.on('login', (user) => {
window.netlifyIdentity.on('login', user => {
component && component.handleIdentityLogin(user);
});
window.netlifyIdentity.on('logout', () => {
@ -78,14 +78,14 @@ export default class GitGatewayAuthenticationPage extends React.Component {
component = null;
}
handleIdentityLogin = (user) => {
handleIdentityLogin = user => {
this.props.onLogin(user);
window.netlifyIdentity.close();
}
};
handleIdentityLogout = () => {
window.netlifyIdentity.open();
}
};
handleIdentity = () => {
const user = window.netlifyIdentity.currentUser();
@ -94,20 +94,20 @@ export default class GitGatewayAuthenticationPage extends React.Component {
} else {
window.netlifyIdentity.open();
}
}
};
static propTypes = {
onLogin: PropTypes.func.isRequired,
inProgress: PropTypes.bool.isRequired,
};
state = { email: "", password: "", errors: {} };
state = { email: '', password: '', errors: {} };
handleChange = (name, e) => {
this.setState({ ...this.state, [name]: e.target.value });
};
handleLogin = (e) => {
handleLogin = e => {
e.preventDefault();
const { email, password } = this.state;
@ -124,13 +124,17 @@ export default class GitGatewayAuthenticationPage extends React.Component {
return;
}
AuthenticationPage.authClient.login(this.state.email, this.state.password, true)
.then((user) => {
this.props.onLogin(user);
})
.catch((error) => {
this.setState({ errors: { server: error.description || error.msg || error }, loggingIn: false });
});
AuthenticationPage.authClient
.login(this.state.email, this.state.password, true)
.then(user => {
this.props.onLogin(user);
})
.catch(error => {
this.setState({
errors: { server: error.description || error.msg || error },
loggingIn: false,
});
});
};
render() {
@ -147,29 +151,33 @@ export default class GitGatewayAuthenticationPage extends React.Component {
}
return (
<AuthenticationPage renderPageContent={() => (
<AuthForm onSubmit={this.handleLogin}>
{!error ? null : <ErrorMessage>{error}</ErrorMessage>}
{!errors.server ? null : <ErrorMessage>{errors.server}</ErrorMessage>}
<ErrorMessage>{errors.email || null}</ErrorMessage>
<AuthInput
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={partial(this.handleChange, 'email')}
/>
<ErrorMessage>{errors.password || null}</ErrorMessage>
<AuthInput
type="password"
name="password"
placeholder="Password"
value={this.state.password}
onChange={partial(this.handleChange, 'password')}
/>
<LoginButton disabled={inProgress}>{inProgress ? 'Logging in...' : 'Login'}</LoginButton>
</AuthForm>
)}/>
<AuthenticationPage
renderPageContent={() => (
<AuthForm onSubmit={this.handleLogin}>
{!error ? null : <ErrorMessage>{error}</ErrorMessage>}
{!errors.server ? null : <ErrorMessage>{errors.server}</ErrorMessage>}
<ErrorMessage>{errors.email || null}</ErrorMessage>
<AuthInput
type="text"
name="email"
placeholder="Email"
value={this.state.email}
onChange={partial(this.handleChange, 'email')}
/>
<ErrorMessage>{errors.password || null}</ErrorMessage>
<AuthInput
type="password"
name="password"
placeholder="Password"
value={this.state.password}
onChange={partial(this.handleChange, 'password')}
/>
<LoginButton disabled={inProgress}>
{inProgress ? 'Logging in...' : 'Login'}
</LoginButton>
</AuthForm>
)}
/>
);
}
}

View File

@ -1,5 +1,5 @@
import { API as GithubAPI } from "netlify-cms-backend-github";
import { APIError } from "netlify-cms-lib-util";
import { API as GithubAPI } from 'netlify-cms-backend-github';
import { APIError } from 'netlify-cms-lib-util';
export default class API extends GithubAPI {
constructor(config) {
@ -7,7 +7,7 @@ export default class API extends GithubAPI {
this.api_root = config.api_root;
this.tokenPromise = config.tokenPromise;
this.commitAuthor = config.commitAuthor;
this.repoURL = "";
this.repoURL = '';
}
hasWriteAccess() {
@ -15,26 +15,36 @@ export default class API extends GithubAPI {
.then(() => true)
.catch(error => {
if (error.status === 401) {
if (error.message === "Bad credentials") {
throw new APIError("Git Gateway Error: Please ask your site administrator to reissue the Git Gateway token.", error.status, 'Git Gateway');
if (error.message === 'Bad credentials') {
throw new APIError(
'Git Gateway Error: Please ask your site administrator to reissue the Git Gateway token.',
error.status,
'Git Gateway',
);
} else {
return false;
}
} else if (error.status === 404 && (error.message === undefined || error.message === "Unable to locate site configuration")) {
throw new APIError(`Git Gateway Error: Please make sure Git Gateway is enabled on your site.`, error.status, 'Git Gateway');
} else if (
error.status === 404 &&
(error.message === undefined || error.message === 'Unable to locate site configuration')
) {
throw new APIError(
`Git Gateway Error: Please make sure Git Gateway is enabled on your site.`,
error.status,
'Git Gateway',
);
} else {
console.error("Problem fetching repo data from Git Gateway");
console.error('Problem fetching repo data from Git Gateway');
throw error;
}
});
}
getRequestHeaders(headers = {}) {
return this.tokenPromise()
.then((jwtToken) => {
return this.tokenPromise().then(jwtToken => {
const baseHeader = {
"Authorization": `Bearer ${ jwtToken }`,
"Content-Type": "application/json",
Authorization: `Bearer ${jwtToken}`,
'Content-Type': 'application/json',
...headers,
};
@ -42,17 +52,16 @@ export default class API extends GithubAPI {
});
}
urlFor(path, options) {
const cacheBuster = new Date().getTime();
const params = [`ts=${ cacheBuster }`];
const params = [`ts=${cacheBuster}`];
if (options.params) {
for (const key in options.params) {
params.push(`${ key }=${ encodeURIComponent(options.params[key]) }`);
params.push(`${key}=${encodeURIComponent(options.params[key])}`);
}
}
if (params.length) {
path += `?${ params.join("&") }`;
path += `?${params.join('&')}`;
}
return this.api_root + path;
}
@ -65,22 +74,22 @@ export default class API extends GithubAPI {
const url = this.urlFor(path, options);
let responseStatus;
return this.getRequestHeaders(options.headers || {})
.then(headers => fetch(url, { ...options, headers }))
.then((response) => {
responseStatus = response.status;
const contentType = response.headers.get("Content-Type");
if (contentType && contentType.match(/json/)) {
return this.parseJsonResponse(response);
}
const text = response.text();
if (!response.ok) {
return Promise.reject(text);
}
return text;
})
.catch(error => {
throw new APIError((error.message || error.msg), responseStatus, 'Git Gateway');
});
.then(headers => fetch(url, { ...options, headers }))
.then(response => {
responseStatus = response.status;
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.match(/json/)) {
return this.parseJsonResponse(response);
}
const text = response.text();
if (!response.ok) {
return Promise.reject(text);
}
return text;
})
.catch(error => {
throw new APIError(error.message || error.msg, responseStatus, 'Git Gateway');
});
}
commit(message, changeTree) {
@ -97,10 +106,9 @@ export default class API extends GithubAPI {
};
}
return this.request("/git/commits", {
method: "POST",
return this.request('/git/commits', {
method: 'POST',
body: JSON.stringify(commitParams),
});
}
}

View File

@ -1,24 +1,25 @@
import { flow } from "lodash";
import { API as GitlabAPI } from "netlify-cms-backend-gitlab";
import { unsentRequest, then } from "netlify-cms-lib-util";
import { flow } from 'lodash';
import { API as GitlabAPI } from 'netlify-cms-backend-gitlab';
import { unsentRequest, then } from 'netlify-cms-lib-util';
export default class API extends GitlabAPI {
constructor(config) {
super(config);
this.tokenPromise = config.tokenPromise;
this.commitAuthor = config.commitAuthor;
this.repoURL = "";
this.repoURL = '';
}
authenticateRequest = async req => unsentRequest.withHeaders({
Authorization: `Bearer ${ await this.tokenPromise() }`,
}, req);
authenticateRequest = async req =>
unsentRequest.withHeaders(
{
Authorization: `Bearer ${await this.tokenPromise()}`,
},
req,
);
request = async req => flow([
this.buildRequest,
this.authenticateRequest,
then(unsentRequest.performRequest),
])(req);
request = async req =>
flow([this.buildRequest, this.authenticateRequest, then(unsentRequest.performRequest)])(req);
hasWriteAccess = () => Promise.resolve(true)
hasWriteAccess = () => Promise.resolve(true);
}

View File

@ -1,13 +1,13 @@
import GoTrue from "gotrue-js";
import GoTrue from 'gotrue-js';
import jwtDecode from 'jwt-decode';
import { get, pick, intersection } from "lodash";
import { unsentRequest } from "netlify-cms-lib-util";
import { GitHubBackend } from "netlify-cms-backend-github";
import { GitLabBackend } from "netlify-cms-backend-gitlab";
import { BitBucketBackend, API as BitBucketAPI } from "netlify-cms-backend-bitbucket";
import GitHubAPI from "./GitHubAPI";
import GitLabAPI from "./GitLabAPI";
import AuthenticationPage from "./AuthenticationPage";
import { get, pick, intersection } from 'lodash';
import { unsentRequest } from 'netlify-cms-lib-util';
import { GitHubBackend } from 'netlify-cms-backend-github';
import { GitLabBackend } from 'netlify-cms-backend-gitlab';
import { BitBucketBackend, API as BitBucketAPI } from 'netlify-cms-backend-bitbucket';
import GitHubAPI from './GitHubAPI';
import GitLabAPI from './GitLabAPI';
import AuthenticationPage from './AuthenticationPage';
const localHosts = {
localhost: true,
@ -20,14 +20,20 @@ const defaults = {
};
function getEndpoint(endpoint, netlifySiteURL) {
if (localHosts[document.location.host.split(":").shift()] && netlifySiteURL && endpoint.match(/^\/\.netlify\//)) {
if (
localHosts[document.location.host.split(':').shift()] &&
netlifySiteURL &&
endpoint.match(/^\/\.netlify\//)
) {
const parts = [];
if (netlifySiteURL) {
parts.push(netlifySiteURL);
if (!netlifySiteURL.match(/\/$/)) { parts.push("/"); }
if (!netlifySiteURL.match(/\/$/)) {
parts.push('/');
}
}
parts.push(endpoint.replace(/^\//, ''));
return parts.join("");
return parts.join('');
}
return endpoint;
}
@ -40,46 +46,58 @@ export default class GitGateway {
...options,
};
this.config = config;
this.branch = config.getIn(["backend", "branch"], "master").trim();
this.squash_merges = config.getIn(["backend", "squash_merges"]);
this.branch = config.getIn(['backend', 'branch'], 'master').trim();
this.squash_merges = config.getIn(['backend', 'squash_merges']);
const netlifySiteURL = localStorage.getItem("netlifySiteURL");
const APIUrl = getEndpoint(config.getIn(["backend", "identity_url"], defaults.identity), netlifySiteURL);
this.gatewayUrl = getEndpoint(config.getIn(["backend", "gateway_url"], defaults.gateway), netlifySiteURL);
const netlifySiteURL = localStorage.getItem('netlifySiteURL');
const APIUrl = getEndpoint(
config.getIn(['backend', 'identity_url'], defaults.identity),
netlifySiteURL,
);
this.gatewayUrl = getEndpoint(
config.getIn(['backend', 'gateway_url'], defaults.gateway),
netlifySiteURL,
);
const backendTypeRegex = /\/(github|gitlab|bitbucket)\/?$/;
const backendTypeMatches = this.gatewayUrl.match(backendTypeRegex);
if (backendTypeMatches) {
this.backendType = backendTypeMatches[1];
this.gatewayUrl = this.gatewayUrl.replace(backendTypeRegex, "/");
this.gatewayUrl = this.gatewayUrl.replace(backendTypeRegex, '/');
} else {
this.backendType = null;
}
this.authClient = window.netlifyIdentity ? window.netlifyIdentity.gotrue : new GoTrue({ APIUrl });
this.authClient = window.netlifyIdentity
? window.netlifyIdentity.gotrue
: new GoTrue({ APIUrl });
AuthenticationPage.authClient = this.authClient;
this.backend = null;
}
requestFunction = req => this.tokenPromise()
.then(token => unsentRequest.withHeaders({ Authorization: `Bearer ${ token }` }, req))
.then(unsentRequest.performRequest);
requestFunction = req =>
this.tokenPromise()
.then(token => unsentRequest.withHeaders({ Authorization: `Bearer ${token}` }, req))
.then(unsentRequest.performRequest);
authenticate(user) {
this.tokenPromise = user.jwt.bind(user);
return this.tokenPromise().then(async token => {
if (!this.backendType) {
const { github_enabled, gitlab_enabled, bitbucket_enabled, roles } = await fetch(`${ this.gatewayUrl }/settings`, {
headers: { Authorization: `Bearer ${ token }` },
}).then(res => res.json());
const { github_enabled, gitlab_enabled, bitbucket_enabled, roles } = await fetch(
`${this.gatewayUrl}/settings`,
{
headers: { Authorization: `Bearer ${token}` },
},
).then(res => res.json());
this.acceptRoles = roles;
if (github_enabled) {
this.backendType = "github";
this.backendType = 'github';
} else if (gitlab_enabled) {
this.backendType = "gitlab";
this.backendType = 'gitlab';
} else if (bitbucket_enabled) {
this.backendType = "bitbucket";
this.backendType = 'bitbucket';
}
}
@ -98,21 +116,21 @@ export default class GitGateway {
metadata: user.user_metadata,
};
const apiConfig = {
api_root: `${ this.gatewayUrl }/${ this.backendType }`,
api_root: `${this.gatewayUrl}/${this.backendType}`,
branch: this.branch,
tokenPromise: this.tokenPromise,
commitAuthor: pick(userData, ["name", "email"]),
commitAuthor: pick(userData, ['name', 'email']),
squash_merges: this.squash_merges,
initialWorkflowStatus: this.options.initialWorkflowStatus,
};
if (this.backendType === "github") {
if (this.backendType === 'github') {
this.api = new GitHubAPI(apiConfig);
this.backend = new GitHubBackend(this.config, { ...this.options, API: this.api });
} else if (this.backendType === "gitlab") {
} else if (this.backendType === 'gitlab') {
this.api = new GitLabAPI(apiConfig);
this.backend = new GitLabBackend(this.config, { ...this.options, API: this.api });
} else if (this.backendType === "bitbucket") {
} else if (this.backendType === 'bitbucket') {
this.api = new BitBucketAPI({
...apiConfig,
requestFunction: this.requestFunction,
@ -145,18 +163,46 @@ export default class GitGateway {
return this.tokenPromise();
}
entriesByFolder(collection, extension) { return this.backend.entriesByFolder(collection, extension); }
entriesByFiles(collection) { return this.backend.entriesByFiles(collection); }
fetchFiles(files) { return this.backend.fetchFiles(files); }
getEntry(collection, slug, path) { return this.backend.getEntry(collection, slug, path); }
getMedia() { return this.backend.getMedia(); }
persistEntry(entry, mediaFiles, options) { return this.backend.persistEntry(entry, mediaFiles, options); }
persistMedia(mediaFile, options) { return this.backend.persistMedia(mediaFile, options); }
deleteFile(path, commitMessage, options) { return this.backend.deleteFile(path, commitMessage, options); }
unpublishedEntries() { return this.backend.unpublishedEntries(); }
unpublishedEntry(collection, slug) { return this.backend.unpublishedEntry(collection, slug); }
updateUnpublishedEntryStatus(collection, slug, newStatus) { return this.backend.updateUnpublishedEntryStatus(collection, slug, newStatus); }
deleteUnpublishedEntry(collection, slug) { return this.backend.deleteUnpublishedEntry(collection, slug); }
publishUnpublishedEntry(collection, slug) { return this.backend.publishUnpublishedEntry(collection, slug); }
traverseCursor(cursor, action) { return this.backend.traverseCursor(cursor, action); }
entriesByFolder(collection, extension) {
return this.backend.entriesByFolder(collection, extension);
}
entriesByFiles(collection) {
return this.backend.entriesByFiles(collection);
}
fetchFiles(files) {
return this.backend.fetchFiles(files);
}
getEntry(collection, slug, path) {
return this.backend.getEntry(collection, slug, path);
}
getMedia() {
return this.backend.getMedia();
}
persistEntry(entry, mediaFiles, options) {
return this.backend.persistEntry(entry, mediaFiles, options);
}
persistMedia(mediaFile, options) {
return this.backend.persistMedia(mediaFile, options);
}
deleteFile(path, commitMessage, options) {
return this.backend.deleteFile(path, commitMessage, options);
}
unpublishedEntries() {
return this.backend.unpublishedEntries();
}
unpublishedEntry(collection, slug) {
return this.backend.unpublishedEntry(collection, slug);
}
updateUnpublishedEntryStatus(collection, slug, newStatus) {
return this.backend.updateUnpublishedEntryStatus(collection, slug, newStatus);
}
deleteUnpublishedEntry(collection, slug) {
return this.backend.deleteUnpublishedEntry(collection, slug);
}
publishUnpublishedEntry(collection, slug) {
return this.backend.publishUnpublishedEntry(collection, slug);
}
traverseCursor(cursor, action) {
return this.backend.traverseCursor(cursor, action);
}
}

View File

@ -1,3 +1,2 @@
export GitGatewayBackend from './implementation';
export AuthenticationPage from './AuthenticationPage';