merge with branch 2.0.0-m3

This commit is contained in:
Sebastian Sdorra
2018-10-24 11:50:29 +02:00
80 changed files with 3465 additions and 1148 deletions

View File

@@ -0,0 +1,30 @@
//@flow
import React from "react";
import type { Repository } from "@scm-manager/ui-types";
import { NavLink } from "@scm-manager/ui-components";
type Props = {
repository: Repository,
to: string,
label: string,
linkName: string,
activeWhenMatch?: (route: any) => boolean,
activeOnlyWhenExact: boolean
};
/**
* Component renders only if the repository contains the link with the given name.
*/
class RepositoryNavLink extends React.Component<Props> {
render() {
const { repository, linkName } = this.props;
if (!repository._links[linkName]) {
return null;
}
return <NavLink {...this.props} />;
}
}
export default RepositoryNavLink;

View File

@@ -0,0 +1,49 @@
// @flow
import React from "react";
import { shallow, mount } from "enzyme";
import "../../tests/enzyme";
import "../../tests/i18n";
import ReactRouterEnzymeContext from "react-router-enzyme-context";
import RepositoryNavLink from "./RepositoryNavLink";
describe("RepositoryNavLink", () => {
const options = new ReactRouterEnzymeContext();
it("should render nothing, if the sources link is missing", () => {
const repository = {
_links: {}
};
const navLink = shallow(
<RepositoryNavLink
repository={repository}
linkName="sources"
to="/sources"
label="Sources"
/>,
options.get()
);
expect(navLink.text()).toBe("");
});
it("should render the navLink", () => {
const repository = {
_links: {
sources: {
href: "/sources"
}
}
};
const navLink = mount(
<RepositoryNavLink
repository={repository}
linkName="sources"
to="/sources"
label="Sources"
/>,
options.get()
);
expect(navLink.text()).toBe("Sources");
});
});

View File

@@ -0,0 +1,32 @@
//@flow
import React from "react";
import { binder } from "@scm-manager/ui-extensions";
import type { Changeset } from "@scm-manager/ui-types";
import { Image } from "@scm-manager/ui-components";
type Props = {
changeset: Changeset
};
class AvatarImage extends React.Component<Props> {
render() {
const { changeset } = this.props;
const avatarFactory = binder.getExtension("changeset.avatar-factory");
if (avatarFactory) {
const avatar = avatarFactory(changeset);
return (
<Image
className="has-rounded-border"
src={avatar}
alt={changeset.author.name}
/>
);
}
return null;
}
}
export default AvatarImage;

View File

@@ -0,0 +1,18 @@
//@flow
import * as React from "react";
import { binder } from "@scm-manager/ui-extensions";
type Props = {
children: React.Node
};
class AvatarWrapper extends React.Component<Props> {
render() {
if (binder.hasExtension("changeset.avatar-factory")) {
return <>{this.props.children}</>;
}
return null;
}
}
export default AvatarWrapper;

View File

@@ -1,30 +0,0 @@
//@flow
import React from "react";
import { ExtensionPoint } from "@scm-manager/ui-extensions";
import type { Changeset } from "@scm-manager/ui-types";
type Props = {
changeset: Changeset
};
class ChangesetAvatar extends React.Component<Props> {
render() {
const { changeset } = this.props;
return (
<ExtensionPoint
name="repos.changeset-table.information"
renderAll={true}
props={{ changeset }}
>
{/* extension should render something like this: */}
{/* <div className="image is-64x64"> */}
{/* <figure className="media-left"> */}
{/* <Image src="/some/image.jpg" alt="Logo" /> */}
{/* </figure> */}
{/* </div> */}
</ExtensionPoint>
);
}
}
export default ChangesetAvatar;

View File

@@ -0,0 +1,100 @@
//@flow
import React from "react";
import type {
Changeset,
Repository
} from "../../../../../scm-ui-components/packages/ui-types/src/index";
import { Interpolate, translate } from "react-i18next";
import injectSheet from "react-jss";
import ChangesetTag from "./ChangesetTag";
import ChangesetAuthor from "./ChangesetAuthor";
import { parseDescription } from "./changesets";
import { DateFromNow } from "../../../../../scm-ui-components/packages/ui-components/src/index";
import AvatarWrapper from "./AvatarWrapper";
import AvatarImage from "./AvatarImage";
import classNames from "classnames";
import ChangesetId from "./ChangesetId";
import type { Tag } from "@scm-manager/ui-types";
const styles = {
spacing: {
marginRight: "1em"
}
};
type Props = {
changeset: Changeset,
repository: Repository,
t: string => string,
classes: any
};
class ChangesetDetails extends React.Component<Props> {
render() {
const { changeset, repository, classes } = this.props;
const description = parseDescription(changeset.description);
const id = (
<ChangesetId repository={repository} changeset={changeset} link={false} />
);
const date = <DateFromNow date={changeset.date} />;
return (
<div className="content">
<h4>{description.title}</h4>
<article className="media">
<AvatarWrapper>
<p className={classNames("image", "is-64x64", classes.spacing)}>
<AvatarImage changeset={changeset} />
</p>
</AvatarWrapper>
<div className="media-content">
<p>
<ChangesetAuthor changeset={changeset} />
</p>
<p>
<Interpolate
i18nKey="changesets.changeset.summary"
id={id}
time={date}
/>
</p>
</div>
<div className="media-right">{this.renderTags()}</div>
</article>
<p>
{description.message.split("\n").map((item, key) => {
return (
<span key={key}>
{item}
<br />
</span>
);
})}
</p>
</div>
);
}
getTags = () => {
const { changeset } = this.props;
return changeset._embedded.tags || [];
};
renderTags = () => {
const tags = this.getTags();
if (tags.length > 0) {
return (
<div className="level-item">
{tags.map((tag: Tag) => {
return <ChangesetTag key={tag.name} tag={tag} />;
})}
</div>
);
}
return null;
};
}
export default injectSheet(styles)(translate("repos")(ChangesetDetails));

View File

@@ -6,20 +6,42 @@ import type { Repository, Changeset } from "@scm-manager/ui-types";
type Props = {
repository: Repository,
changeset: Changeset
changeset: Changeset,
link: boolean
};
export default class ChangesetId extends React.Component<Props> {
render() {
const { repository, changeset } = this.props;
static defaultProps = {
link: true
};
shortId = (changeset: Changeset) => {
return changeset.id.substr(0, 7);
};
renderLink = () => {
const { changeset, repository } = this.props;
return (
<Link
to={`/repo/${repository.namespace}/${repository.name}/changeset/${
changeset.id
}`}
>
{changeset.id.substr(0, 7)}
{this.shortId(changeset)}
</Link>
);
};
renderText = () => {
const { changeset } = this.props;
return this.shortId(changeset);
};
render() {
const { link } = this.props;
if (link) {
return this.renderLink();
}
return this.renderText();
}
}

View File

@@ -3,13 +3,15 @@ import React from "react";
import type { Changeset, Repository, Tag } from "@scm-manager/ui-types";
import classNames from "classnames";
import { translate, Interpolate } from "react-i18next";
import ChangesetAvatar from "./ChangesetAvatar";
import ChangesetId from "./ChangesetId";
import injectSheet from "react-jss";
import { DateFromNow } from "@scm-manager/ui-components";
import ChangesetAuthor from "./ChangesetAuthor";
import ChangesetTag from "./ChangesetTag";
import { compose } from "redux";
import { parseDescription } from "./changesets";
import AvatarWrapper from "./AvatarWrapper";
import AvatarImage from "./AvatarImage";
const styles = {
pointer: {
@@ -46,14 +48,23 @@ class ChangesetRow extends React.Component<Props> {
const changesetLink = this.createLink(changeset);
const dateFromNow = <DateFromNow date={changeset.date} />;
const authorLine = <ChangesetAuthor changeset={changeset} />;
const description = parseDescription(changeset.description);
return (
<article className={classNames("media", classes.inner)}>
<ChangesetAvatar changeset={changeset} />
<AvatarWrapper>
<div>
<figure className="media-left">
<p className="image is-64x64">
<AvatarImage changeset={changeset} />
</p>
</figure>
</div>
</AvatarWrapper>
<div className={classNames("media-content", classes.withOverflow)}>
<div className="content">
<p className="is-ellipsis-overflow">
{changeset.description}
<strong>{description.title}</strong>
<br />
<Interpolate
i18nKey="changesets.changeset.summary"

View File

@@ -0,0 +1,25 @@
// @flow
export type Description = {
title: string,
message: string
};
export function parseDescription(description?: string): Description {
const desc = description ? description : "";
const lineBreak = desc.indexOf("\n");
let title;
let message = "";
if (lineBreak > 0) {
title = desc.substring(0, lineBreak);
message = desc.substring(lineBreak + 1);
} else {
title = desc;
}
return {
title,
message
};
}

View File

@@ -0,0 +1,22 @@
// @flow
import { parseDescription } from "./changesets";
describe("parseDescription tests", () => {
it("should return a description with title and message", () => {
const desc = parseDescription("Hello\nTrillian");
expect(desc.title).toBe("Hello");
expect(desc.message).toBe("Trillian");
});
it("should return a description with title and without message", () => {
const desc = parseDescription("Hello Trillian");
expect(desc.title).toBe("Hello Trillian");
});
it("should return an empty description for undefined", () => {
const desc = parseDescription();
expect(desc.title).toBe("");
expect(desc.message).toBe("");
});
});

View File

@@ -17,6 +17,7 @@ const styles = {
type Props = {
branches: Branch[], // TODO: Use generics?
selected: (branch?: Branch) => void,
selectedBranch: string,
// context props
classes: Object,
@@ -31,6 +32,12 @@ class BranchSelector extends React.Component<Props, State> {
this.state = {};
}
componentDidMount() {
this.props.branches
.filter(branch => branch.name === this.props.selectedBranch)
.forEach(branch => this.setState({ selectedBranch: branch }));
}
render() {
const { branches, classes, t } = this.props;
@@ -60,6 +67,8 @@ class BranchSelector extends React.Component<Props, State> {
</div>
</div>
);
} else {
return null;
}
}

View File

@@ -0,0 +1,75 @@
//@flow
import React from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import type { Changeset, Repository } from "@scm-manager/ui-types";
import {
fetchChangesetIfNeeded,
getChangeset,
getFetchChangesetFailure,
isFetchChangesetPending
} from "../modules/changesets";
import ChangesetDetails from "../components/changesets/ChangesetDetails";
import { translate } from "react-i18next";
import { Loading, ErrorPage } from "@scm-manager/ui-components";
type Props = {
id: string,
changeset: Changeset,
repository: Repository,
loading: boolean,
error: Error,
fetchChangesetIfNeeded: (repository: Repository, id: string) => void,
match: any,
t: string => string
};
class ChangesetView extends React.Component<Props> {
componentDidMount() {
const { fetchChangesetIfNeeded, repository } = this.props;
const id = this.props.match.params.id;
fetchChangesetIfNeeded(repository, id);
}
render() {
const { changeset, loading, error, t, repository } = this.props;
if (error) {
return (
<ErrorPage
title={t("changeset-error.title")}
subtitle={t("changeset-error.subtitle")}
error={error}
/>
);
}
if (!changeset || loading) return <Loading />;
return <ChangesetDetails changeset={changeset} repository={repository} />;
}
}
const mapStateToProps = (state, ownProps: Props) => {
const repository = ownProps.repository;
const id = ownProps.match.params.id;
const changeset = getChangeset(state, repository, id);
const loading = isFetchChangesetPending(state, repository, id);
const error = getFetchChangesetFailure(state, repository, id);
return { changeset, error, loading };
};
const mapDispatchToProps = dispatch => {
return {
fetchChangesetIfNeeded: (repository: Repository, id: string) => {
dispatch(fetchChangesetIfNeeded(repository, id));
}
};
};
export default withRouter(
connect(
mapStateToProps,
mapDispatchToProps
)(translate("changesets")(ChangesetView))
);

View File

@@ -92,11 +92,12 @@ class BranchRoot extends React.Component<Props> {
}
renderBranchSelector = () => {
const { repository, branches } = this.props;
const { repository, branches, selected } = this.props;
if (repository._links.branches) {
return (
<BranchSelector
branches={branches}
selectedBranch={selected}
selected={(b: Branch) => {
this.branchSelected(b);
}}

View File

@@ -7,9 +7,11 @@ import {
getRepository,
isFetchRepoPending
} from "../modules/repos";
import { connect } from "react-redux";
import { Route, Switch } from "react-router-dom";
import type { Repository } from "@scm-manager/ui-types";
import {
ErrorPage,
Loading,
@@ -26,8 +28,12 @@ import Permissions from "../permissions/containers/Permissions";
import type { History } from "history";
import EditNavLink from "../components/EditNavLink";
import BranchRoot from "./BranchRoot";
import BranchRoot from "./ChangesetsRoot";
import ChangesetView from "./ChangesetView";
import PermissionsNavLink from "../components/PermissionsNavLink";
import Sources from "../sources/containers/Sources";
import RepositoryNavLink from "../components/RepositoryNavLink";
import { getRepositoriesLink } from "../../modules/indexResource";
type Props = {
@@ -74,6 +80,11 @@ class RepositoryRoot extends React.Component<Props> {
this.props.deleteRepo(repository, this.deleted);
};
matchChangeset = (route: any) => {
const url = this.matchedUrl();
return route.location.pathname.match(`${url}/changeset/`);
};
matches = (route: any) => {
const url = this.matchedUrl();
const regex = new RegExp(`${url}(/branches)?/?[^/]*/changesets?.*`);
@@ -121,6 +132,24 @@ class RepositoryRoot extends React.Component<Props> {
/>
)}
/>
<Route
exact
path={`${url}/changeset/:id`}
render={() => <ChangesetView repository={repository} />}
/>
<Route
path={`${url}/sources`}
exact={true}
render={() => (
<Sources repository={repository} baseUrl={`${url}/sources`} />
)}
/>
<Route
path={`${url}/sources/:revision/:path*`}
render={() => (
<Sources repository={repository} baseUrl={`${url}/sources`} />
)}
/>
<Route
path={`${url}/changesets`}
render={() => (
@@ -147,11 +176,20 @@ class RepositoryRoot extends React.Component<Props> {
<Navigation>
<Section label={t("repository-root.navigation-label")}>
<NavLink to={url} label={t("repository-root.information")} />
<NavLink
activeOnlyWhenExact={false}
<RepositoryNavLink
repository={repository}
linkName="changesets"
to={`${url}/changesets/`}
label={t("repository-root.history")}
activeWhenMatch={this.matches}
activeOnlyWhenExact={false}
/>
<RepositoryNavLink
repository={repository}
linkName="sources"
to={`${url}/sources`}
label={t("repository-root.sources")}
activeOnlyWhenExact={false}
/>
<EditNavLink repository={repository} editUrl={`${url}/edit`} />
<PermissionsNavLink

View File

@@ -5,7 +5,7 @@ import {
PENDING_SUFFIX,
SUCCESS_SUFFIX
} from "../../modules/types";
import { apiClient } from "@scm-manager/ui-components";
import { apiClient, urls } from "@scm-manager/ui-components";
import { isPending } from "../../modules/pending";
import { getFailure } from "../../modules/failure";
import type {
@@ -20,8 +20,76 @@ export const FETCH_CHANGESETS_PENDING = `${FETCH_CHANGESETS}_${PENDING_SUFFIX}`;
export const FETCH_CHANGESETS_SUCCESS = `${FETCH_CHANGESETS}_${SUCCESS_SUFFIX}`;
export const FETCH_CHANGESETS_FAILURE = `${FETCH_CHANGESETS}_${FAILURE_SUFFIX}`;
//TODO: Content type
export const FETCH_CHANGESET = "scm/repos/FETCH_CHANGESET";
export const FETCH_CHANGESET_PENDING = `${FETCH_CHANGESET}_${PENDING_SUFFIX}`;
export const FETCH_CHANGESET_SUCCESS = `${FETCH_CHANGESET}_${SUCCESS_SUFFIX}`;
export const FETCH_CHANGESET_FAILURE = `${FETCH_CHANGESET}_${FAILURE_SUFFIX}`;
// actions
//TODO: Content type
export function fetchChangesetIfNeeded(repository: Repository, id: string) {
return (dispatch: any, getState: any) => {
if (shouldFetchChangeset(getState(), repository, id)) {
return dispatch(fetchChangeset(repository, id));
}
};
}
export function fetchChangeset(repository: Repository, id: string) {
return function(dispatch: any) {
dispatch(fetchChangesetPending(repository, id));
return apiClient
.get(createChangesetUrl(repository, id))
.then(response => response.json())
.then(data => dispatch(fetchChangesetSuccess(data, repository, id)))
.catch(err => {
dispatch(fetchChangesetFailure(repository, id, err));
});
};
}
function createChangesetUrl(repository: Repository, id: string) {
return urls.concat(repository._links.changesets.href, id);
}
export function fetchChangesetPending(
repository: Repository,
id: string
): Action {
return {
type: FETCH_CHANGESET_PENDING,
itemId: createChangesetItemId(repository, id)
};
}
export function fetchChangesetSuccess(
changeset: any,
repository: Repository,
id: string
): Action {
return {
type: FETCH_CHANGESET_SUCCESS,
payload: { changeset, repository, id },
itemId: createChangesetItemId(repository, id)
};
}
function fetchChangesetFailure(
repository: Repository,
id: string,
error: Error
): Action {
return {
type: FETCH_CHANGESET_FAILURE,
payload: {
repository,
id,
error
},
itemId: createChangesetItemId(repository, id)
};
}
export function fetchChangesets(
repository: Repository,
@@ -80,7 +148,11 @@ export function fetchChangesetsSuccess(
): Action {
return {
type: FETCH_CHANGESETS_SUCCESS,
payload: changesets,
payload: {
repository,
branch,
changesets
},
itemId: createItemId(repository, branch)
};
}
@@ -101,6 +173,11 @@ function fetchChangesetsFailure(
};
}
function createChangesetItemId(repository: Repository, id: string) {
const { namespace, name } = repository;
return namespace + "/" + name + "/" + id;
}
function createItemId(repository: Repository, branch?: Branch): string {
const { namespace, name } = repository;
let itemId = namespace + "/" + name;
@@ -118,10 +195,32 @@ export default function reducer(
if (!action.payload) {
return state;
}
const payload = action.payload;
switch (action.type) {
case FETCH_CHANGESET_SUCCESS:
const _key = createItemId(payload.repository);
let _oldByIds = {};
if (state[_key] && state[_key].byId) {
_oldByIds = state[_key].byId;
}
const changeset = payload.changeset;
return {
...state,
[_key]: {
...state[_key],
byId: {
..._oldByIds,
[changeset.id]: changeset
}
}
};
case FETCH_CHANGESETS_SUCCESS:
const changesets = payload._embedded.changesets;
const changesets = payload.changesets._embedded.changesets;
const changesetIds = changesets.map(c => c.id);
const key = action.itemId;
@@ -129,26 +228,32 @@ export default function reducer(
return state;
}
let oldByIds = {};
if (state[key] && state[key].byId) {
oldByIds = state[key].byId;
const repoId = createItemId(payload.repository);
let oldState = {};
if (state[repoId]) {
oldState = state[repoId];
}
const branchName = payload.branch ? payload.branch.name : "";
const byIds = extractChangesetsByIds(changesets);
return {
...state,
[key]: {
[repoId]: {
byId: {
...oldByIds,
...oldState.byId,
...byIds
},
list: {
entries: changesetIds,
entry: {
page: payload.page,
pageTotal: payload.pageTotal,
_links: payload._links
byBranch: {
...oldState.byBranch,
[branchName]: {
entries: changesetIds,
entry: {
page: payload.changesets.page,
pageTotal: payload.changesets.pageTotal,
_links: payload.changesets._links
}
}
}
}
@@ -174,17 +279,76 @@ export function getChangesets(
repository: Repository,
branch?: Branch
) {
const key = createItemId(repository, branch);
const repoKey = createItemId(repository);
const changesets = state.changesets[key];
const stateRoot = state.changesets[repoKey];
if (!stateRoot || !stateRoot.byBranch) {
return null;
}
const branchName = branch ? branch.name : "";
const changesets = stateRoot.byBranch[branchName];
if (!changesets) {
return null;
}
return changesets.list.entries.map((id: string) => {
return changesets.byId[id];
return changesets.entries.map((id: string) => {
return stateRoot.byId[id];
});
}
export function getChangeset(
state: Object,
repository: Repository,
id: string
) {
const key = createItemId(repository);
const changesets =
state.changesets && state.changesets[key]
? state.changesets[key].byId
: null;
if (changesets != null && changesets[id]) {
return changesets[id];
}
return null;
}
export function shouldFetchChangeset(
state: Object,
repository: Repository,
id: string
) {
if (getChangeset(state, repository, id)) {
return false;
}
return true;
}
export function isFetchChangesetPending(
state: Object,
repository: Repository,
id: string
) {
return isPending(
state,
FETCH_CHANGESET,
createChangesetItemId(repository, id)
);
}
export function getFetchChangesetFailure(
state: Object,
repository: Repository,
id: string
) {
return getFailure(
state,
FETCH_CHANGESET,
createChangesetItemId(repository, id)
);
}
export function isFetchChangesetsPending(
state: Object,
repository: Repository,
@@ -202,9 +366,15 @@ export function getFetchChangesetsFailure(
}
const selectList = (state: Object, repository: Repository, branch?: Branch) => {
const itemId = createItemId(repository, branch);
if (state.changesets[itemId] && state.changesets[itemId].list) {
return state.changesets[itemId].list;
const repoId = createItemId(repository);
const branchName = branch ? branch.name : "";
if (state.changesets[repoId]) {
const repoState = state.changesets[repoId];
if (repoState.byBranch && repoState.byBranch[branchName]) {
return repoState.byBranch[branchName];
}
}
return {};
};

View File

@@ -8,11 +8,23 @@ import reducer, {
FETCH_CHANGESETS_FAILURE,
FETCH_CHANGESETS_PENDING,
FETCH_CHANGESETS_SUCCESS,
FETCH_CHANGESET,
FETCH_CHANGESET_FAILURE,
FETCH_CHANGESET_PENDING,
FETCH_CHANGESET_SUCCESS,
fetchChangesets,
fetchChangesetsSuccess,
getChangesets,
getFetchChangesetsFailure,
isFetchChangesetsPending
isFetchChangesetsPending,
fetchChangeset,
getChangeset,
fetchChangesetIfNeeded,
shouldFetchChangeset,
isFetchChangesetPending,
getFetchChangesetFailure,
fetchChangesetSuccess,
selectListAsCollection
} from "./changesets";
const branch = {
@@ -21,7 +33,7 @@ const branch = {
_links: {
history: {
href:
"http://scm/api/rest/v2/repositories/foo/bar/branches/specific/changesets"
"http://scm.hitchhicker.com/api/v2/repositories/foo/bar/branches/specific/changesets"
}
}
};
@@ -32,14 +44,14 @@ const repository = {
type: "GIT",
_links: {
self: {
href: "http://scm/api/rest/v2/repositories/foo/bar"
href: "http://scm.hitchhicker.com/api/v2/repositories/foo/bar"
},
changesets: {
href: "http://scm/api/rest/v2/repositories/foo/bar/changesets"
href: "http://scm.hitchhicker.com/api/v2/repositories/foo/bar/changesets"
},
branches: {
href:
"http://scm/api/rest/v2/repositories/foo/bar/branches/specific/branches"
"http://scm.hitchhicker.com/api/v2/repositories/foo/bar/branches/specific/branches"
}
}
};
@@ -49,9 +61,10 @@ const changesets = {};
describe("changesets", () => {
describe("fetching of changesets", () => {
const DEFAULT_BRANCH_URL =
"http://scm/api/rest/v2/repositories/foo/bar/changesets";
"http://scm.hitchhicker.com/api/v2/repositories/foo/bar/changesets";
const SPECIFIC_BRANCH_URL =
"http://scm/api/rest/v2/repositories/foo/bar/branches/specific/changesets";
"http://scm.hitchhicker.com/api/v2/repositories/foo/bar/branches/specific/changesets";
const mockStore = configureMockStore([thunk]);
afterEach(() => {
@@ -59,6 +72,102 @@ describe("changesets", () => {
fetchMock.restore();
});
const changesetId = "aba876c0625d90a6aff1494f3d161aaa7008b958";
it("should fetch changeset", () => {
fetchMock.getOnce(DEFAULT_BRANCH_URL + "/" + changesetId, "{}");
const expectedActions = [
{
type: FETCH_CHANGESET_PENDING,
itemId: "foo/bar/" + changesetId
},
{
type: FETCH_CHANGESET_SUCCESS,
payload: {
changeset: {},
id: changesetId,
repository: repository
},
itemId: "foo/bar/" + changesetId
}
];
const store = mockStore({});
return store
.dispatch(fetchChangeset(repository, changesetId))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it("should fail fetching changeset on error", () => {
fetchMock.getOnce(DEFAULT_BRANCH_URL + "/" + changesetId, 500);
const expectedActions = [
{
type: FETCH_CHANGESET_PENDING,
itemId: "foo/bar/" + changesetId
}
];
const store = mockStore({});
return store
.dispatch(fetchChangeset(repository, changesetId))
.then(() => {
expect(store.getActions()[0]).toEqual(expectedActions[0]);
expect(store.getActions()[1].type).toEqual(FETCH_CHANGESET_FAILURE);
expect(store.getActions()[1].payload).toBeDefined();
});
});
it("should fetch changeset if needed", () => {
fetchMock.getOnce(DEFAULT_BRANCH_URL + "/id3", "{}");
const expectedActions = [
{
type: FETCH_CHANGESET_PENDING,
itemId: "foo/bar/id3"
},
{
type: FETCH_CHANGESET_SUCCESS,
payload: {
changeset: {},
id: "id3",
repository: repository
},
itemId: "foo/bar/id3"
}
];
const store = mockStore({});
return store
.dispatch(fetchChangesetIfNeeded(repository, "id3"))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it("should not fetch changeset if not needed", () => {
fetchMock.getOnce(DEFAULT_BRANCH_URL + "/id1", 500);
const state = {
changesets: {
"foo/bar": {
byId: {
id1: { id: "id1" },
id2: { id: "id2" }
}
}
}
};
const store = mockStore(state);
return expect(
store.dispatch(fetchChangesetIfNeeded(repository, "id1"))
).toEqual(undefined);
});
it("should fetch changesets for default branch", () => {
fetchMock.getOnce(DEFAULT_BRANCH_URL, "{}");
@@ -69,7 +178,11 @@ describe("changesets", () => {
},
{
type: FETCH_CHANGESETS_SUCCESS,
payload: changesets,
payload: {
repository,
undefined,
changesets
},
itemId: "foo/bar"
}
];
@@ -91,7 +204,11 @@ describe("changesets", () => {
},
{
type: FETCH_CHANGESETS_SUCCESS,
payload: changesets,
payload: {
repository,
branch,
changesets
},
itemId
}
];
@@ -150,7 +267,11 @@ describe("changesets", () => {
},
{
type: FETCH_CHANGESETS_SUCCESS,
payload: changesets,
payload: {
repository,
undefined,
changesets
},
itemId: "foo/bar"
}
];
@@ -173,7 +294,11 @@ describe("changesets", () => {
},
{
type: FETCH_CHANGESETS_SUCCESS,
payload: changesets,
payload: {
repository,
branch,
changesets
},
itemId: "foo/bar/specific"
}
];
@@ -215,7 +340,7 @@ describe("changesets", () => {
);
expect(newState["foo/bar"].byId["changeset2"].description).toEqual("foo");
expect(newState["foo/bar"].byId["changeset3"].description).toEqual("bar");
expect(newState["foo/bar"].list).toEqual({
expect(newState["foo/bar"].byBranch[""]).toEqual({
entry: {
page: 1,
pageTotal: 10,
@@ -225,6 +350,20 @@ describe("changesets", () => {
});
});
it("should store the changeset list to branch", () => {
const newState = reducer(
{},
fetchChangesetsSuccess(repository, branch, responseBody)
);
expect(newState["foo/bar"].byId["changeset1"]).toBeDefined();
expect(newState["foo/bar"].byBranch["specific"].entries).toEqual([
"changeset1",
"changeset2",
"changeset3"
]);
});
it("should not remove existing changesets", () => {
const state = {
"foo/bar": {
@@ -232,8 +371,10 @@ describe("changesets", () => {
id2: { id: "id2" },
id1: { id: "id1" }
},
list: {
entries: ["id1", "id2"]
byBranch: {
"": {
entries: ["id1", "id2"]
}
}
}
};
@@ -245,7 +386,7 @@ describe("changesets", () => {
const fooBar = newState["foo/bar"];
expect(fooBar.list.entries).toEqual([
expect(fooBar.byBranch[""].entries).toEqual([
"changeset1",
"changeset2",
"changeset3"
@@ -253,11 +394,154 @@ describe("changesets", () => {
expect(fooBar.byId["id2"]).toEqual({ id: "id2" });
expect(fooBar.byId["id1"]).toEqual({ id: "id1" });
});
const responseBodySingleChangeset = {
id: "id3",
author: {
mail: "z@phod.com",
name: "zaphod"
},
date: "2018-09-13T08:46:22Z",
description: "added testChangeset",
_links: {},
_embedded: {
tags: [],
branches: []
}
};
it("should add changeset to state", () => {
const newState = reducer(
{
"foo/bar": {
byId: {
"id2": {
id: "id2",
author: { mail: "mail@author.com", name: "author" }
}
},
list: {
entry: {
page: 1,
pageTotal: 10,
_links: {}
},
entries: ["id2"]
}
}
},
fetchChangesetSuccess(responseBodySingleChangeset, repository, "id3")
);
expect(newState).toBeDefined();
expect(newState["foo/bar"].byId["id3"].description).toEqual(
"added testChangeset"
);
expect(newState["foo/bar"].byId["id3"].author.mail).toEqual("z@phod.com");
expect(newState["foo/bar"].byId["id2"]).toBeDefined();
expect(newState["foo/bar"].byId["id3"]).toBeDefined();
expect(newState["foo/bar"].list).toEqual({
entry: {
page: 1,
pageTotal: 10,
_links: {}
},
entries: ["id2"]
});
});
});
describe("changeset selectors", () => {
const error = new Error("Something went wrong");
it("should return changeset", () => {
const state = {
changesets: {
"foo/bar": {
byId: {
id1: { id: "id1" },
id2: { id: "id2" }
}
}
}
};
const result = getChangeset(state, repository, "id1");
expect(result).toEqual({ id: "id1" });
});
it("should return null if changeset does not exist", () => {
const state = {
changesets: {
"foo/bar": {
byId: {
id1: { id: "id1" },
id2: { id: "id2" }
}
}
}
};
const result = getChangeset(state, repository, "id3");
expect(result).toEqual(null);
});
it("should return true if changeset does not exist", () => {
const state = {
changesets: {
"foo/bar": {
byId: {
id1: { id: "id1" },
id2: { id: "id2" }
}
}
}
};
const result = shouldFetchChangeset(state, repository, "id3");
expect(result).toEqual(true);
});
it("should return false if changeset exists", () => {
const state = {
changesets: {
"foo/bar": {
byId: {
id1: { id: "id1" },
id2: { id: "id2" }
}
}
}
};
const result = shouldFetchChangeset(state, repository, "id2");
expect(result).toEqual(false);
});
it("should return true, when fetching changeset is pending", () => {
const state = {
pending: {
[FETCH_CHANGESET + "/foo/bar/id1"]: true
}
};
expect(isFetchChangesetPending(state, repository, "id1")).toBeTruthy();
});
it("should return false, when fetching changeset is not pending", () => {
expect(isFetchChangesetPending({}, repository, "id1")).toEqual(false);
});
it("should return error if fetching changeset failed", () => {
const state = {
failure: {
[FETCH_CHANGESET + "/foo/bar/id1"]: error
}
};
expect(getFetchChangesetFailure(state, repository, "id1")).toEqual(error);
});
it("should return false if fetching changeset did not fail", () => {
expect(getFetchChangesetFailure({}, repository, "id1")).toBeUndefined();
});
it("should get all changesets for a given repository", () => {
const state = {
changesets: {
@@ -266,8 +550,10 @@ describe("changesets", () => {
id2: { id: "id2" },
id1: { id: "id1" }
},
list: {
entries: ["id1", "id2"]
byBranch: {
"": {
entries: ["id1", "id2"]
}
}
}
}
@@ -303,5 +589,32 @@ describe("changesets", () => {
it("should return false if fetching changesets did not fail", () => {
expect(getFetchChangesetsFailure({}, repository)).toBeUndefined();
});
it("should return list as collection for the default branch", () => {
const state = {
changesets: {
"foo/bar": {
byId: {
id2: { id: "id2" },
id1: { id: "id1" }
},
byBranch: {
"": {
entry: {
page: 1,
pageTotal: 10,
_links: {}
},
entries: ["id1", "id2"]
}
}
}
}
};
const collection = selectListAsCollection(state, repository);
expect(collection.page).toBe(1);
expect(collection.pageTotal).toBe(10);
});
});
});

View File

@@ -5,13 +5,13 @@ import { Checkbox, InputField, SubmitButton } from "@scm-manager/ui-components";
import TypeSelector from "./TypeSelector";
import type {
PermissionCollection,
PermissionEntry
PermissionCreateEntry
} from "@scm-manager/ui-types";
import * as validator from "./permissionValidation";
type Props = {
t: string => string,
createPermission: (permission: PermissionEntry) => void,
createPermission: (permission: PermissionCreateEntry) => void,
loading: boolean,
currentPermissions: PermissionCollection
};
@@ -68,7 +68,7 @@ class CreatePermissionForm extends React.Component<Props, State> {
<SubmitButton
label={t("permission.add-permission.submit-button")}
loading={loading}
disabled={!this.state.valid || this.state.name == ""}
disabled={!this.state.valid || this.state.name === ""}
/>
</form>
</div>

View File

@@ -1,21 +1,30 @@
// @flow
import { validation } from "@scm-manager/ui-components";
import type {
PermissionCollection,
} from "@scm-manager/ui-types";
import type { PermissionCollection } from "@scm-manager/ui-types";
const isNameValid = validation.isNameValid;
export { isNameValid };
export const isPermissionValid = (name: string, groupPermission: boolean, permissions: PermissionCollection) => {
return isNameValid(name) && !currentPermissionIncludeName(name, groupPermission, permissions);
export const isPermissionValid = (
name: string,
groupPermission: boolean,
permissions: PermissionCollection
) => {
return (
isNameValid(name) &&
!currentPermissionIncludeName(name, groupPermission, permissions)
);
};
const currentPermissionIncludeName = (name: string, groupPermission: boolean, permissions: PermissionCollection) => {
const currentPermissionIncludeName = (
name: string,
groupPermission: boolean,
permissions: PermissionCollection
) => {
for (let i = 0; i < permissions.length; i++) {
if (
permissions[i].name === name &&
permissions[i].groupPermission == groupPermission
permissions[i].groupPermission === groupPermission
)
return true;
}

View File

@@ -17,7 +17,8 @@ describe("permission validation", () => {
{
name: "PermissionName",
groupPermission: true,
type: "READ"
type: "READ",
_links: {}
}
];
const name = "PermissionName";
@@ -33,7 +34,8 @@ describe("permission validation", () => {
{
name: "PermissionName",
groupPermission: false,
type: "READ"
type: "READ",
_links: {}
}
];
const name = "PermissionName";

View File

@@ -21,7 +21,7 @@ import { Loading, ErrorPage } from "@scm-manager/ui-components";
import type {
Permission,
PermissionCollection,
PermissionEntry
PermissionCreateEntry
} from "@scm-manager/ui-types";
import SinglePermission from "./SinglePermission";
import CreatePermissionForm from "../components/CreatePermissionForm";
@@ -42,7 +42,7 @@ type Props = {
fetchPermissions: (link: string, namespace: string, repoName: string) => void,
createPermission: (
link: string,
permission: PermissionEntry,
permission: PermissionCreateEntry,
namespace: string,
repoName: string,
callback?: () => void
@@ -184,7 +184,7 @@ const mapDispatchToProps = dispatch => {
},
createPermission: (
link: string,
permission: PermissionEntry,
permission: PermissionCreateEntry,
namespace: string,
repoName: string,
callback?: () => void

View File

@@ -6,7 +6,7 @@ import type { Action } from "@scm-manager/ui-components";
import type {
PermissionCollection,
Permission,
PermissionEntry
PermissionCreateEntry
} from "@scm-manager/ui-types";
import { isPending } from "../../../modules/pending";
import { getFailure } from "../../../modules/failure";
@@ -222,7 +222,7 @@ export function modifyPermissionReset(namespace: string, repoName: string) {
// create permission
export function createPermission(
link: string,
permission: PermissionEntry,
permission: PermissionCreateEntry,
namespace: string,
repoName: string,
callback?: () => void
@@ -259,7 +259,7 @@ export function createPermission(
}
export function createPermissionPending(
permission: PermissionEntry,
permission: PermissionCreateEntry,
namespace: string,
repoName: string
): Action {
@@ -271,7 +271,7 @@ export function createPermissionPending(
}
export function createPermissionSuccess(
permission: PermissionEntry,
permission: PermissionCreateEntry,
namespace: string,
repoName: string
): Action {

View File

@@ -656,7 +656,7 @@ describe("permissions selectors", () => {
it("should return true, when createPermission is true", () => {
const state = {
permissions: {
["hitchhiker/puzzle42"]: {
"hitchhiker/puzzle42": {
createPermission: true
}
}
@@ -667,7 +667,7 @@ describe("permissions selectors", () => {
it("should return false, when createPermission is false", () => {
const state = {
permissions: {
["hitchhiker/puzzle42"]: {
"hitchhiker/puzzle42": {
createPermission: false
}
}

View File

@@ -0,0 +1,22 @@
// @flow
import React from "react";
import type { File } from "@scm-manager/ui-types";
type Props = {
file: File
};
class FileIcon extends React.Component<Props> {
render() {
const { file } = this.props;
let icon = "file";
if (file.subRepository) {
icon = "folder-plus";
} else if (file.directory) {
icon = "folder";
}
return <i className={`fa fa-${icon}`} />;
}
}
export default FileIcon;

View File

@@ -0,0 +1,27 @@
// @flow
import React from "react";
type Props = {
bytes: number
};
class FileSize extends React.Component<Props> {
static format(bytes: number) {
if (!bytes) {
return "0 B";
}
const units = ["B", "K", "M", "G", "T", "P", "E", "Z", "Y"];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
const size = i === 0 ? bytes : (bytes / 1024 ** i).toFixed(2);
return `${size} ${units[i]}`;
}
render() {
const formattedBytes = FileSize.format(this.props.bytes);
return <span>{formattedBytes}</span>;
}
}
export default FileSize;

View File

@@ -0,0 +1,10 @@
import FileSize from "./FileSize";
it("should format bytes", () => {
expect(FileSize.format(0)).toBe("0 B");
expect(FileSize.format(160)).toBe("160 B");
expect(FileSize.format(6304)).toBe("6.16 K");
expect(FileSize.format(28792588)).toBe("27.46 M");
expect(FileSize.format(1369510189)).toBe("1.28 G");
expect(FileSize.format(42949672960)).toBe("40.00 G");
});

View File

@@ -0,0 +1,184 @@
//@flow
import React from "react";
import { translate } from "react-i18next";
import { connect } from "react-redux";
import injectSheet from "react-jss";
import FileTreeLeaf from "./FileTreeLeaf";
import type { Repository, File } from "@scm-manager/ui-types";
import { ErrorNotification, Loading } from "@scm-manager/ui-components";
import {
fetchSources,
getFetchSourcesFailure,
isFetchSourcesPending,
getSources
} from "../modules/sources";
import { withRouter } from "react-router-dom";
import { compose } from "redux";
const styles = {
iconColumn: {
width: "16px"
}
};
type Props = {
loading: boolean,
error: Error,
tree: File,
repository: Repository,
revision: string,
path: string,
baseUrl: string,
fetchSources: (Repository, string, string) => void,
// context props
classes: any,
t: string => string,
match: any
};
export function findParent(path: string) {
if (path.endsWith("/")) {
path = path.substring(0, path.length - 1);
}
const index = path.lastIndexOf("/");
if (index > 0) {
return path.substring(0, index);
}
return "";
}
class FileTree extends React.Component<Props> {
componentDidMount() {
const { fetchSources, repository, revision, path } = this.props;
fetchSources(repository, revision, path);
}
componentDidUpdate(prevProps) {
const { fetchSources, repository, revision, path } = this.props;
if (prevProps.revision !== revision || prevProps.path !== path) {
fetchSources(repository, revision, path);
}
}
render() {
const {
error,
loading,
tree,
revision,
path,
baseUrl,
classes,
t
} = this.props;
const compareFiles = function(f1: File, f2: File): number {
if (f1.directory) {
if (f2.directory) {
return f1.name.localeCompare(f2.name);
} else {
return -1;
}
} else {
if (f2.directory) {
return 1;
} else {
return f1.name.localeCompare(f2.name);
}
}
};
if (error) {
return <ErrorNotification error={error} />;
}
if (loading) {
return <Loading />;
}
if (!tree) {
return null;
}
const files = [];
if (path) {
files.push({
name: "..",
path: findParent(path),
directory: true
});
}
if (tree._embedded) {
files.push(...tree._embedded.children.sort(compareFiles));
}
let baseUrlWithRevision = baseUrl;
if (revision) {
baseUrlWithRevision += "/" + encodeURIComponent(revision);
} else {
baseUrlWithRevision += "/" + encodeURIComponent(tree.revision);
}
return (
<table className="table table-hover table-sm is-fullwidth">
<thead>
<tr>
<th className={classes.iconColumn} />
<th>{t("sources.file-tree.name")}</th>
<th className="is-hidden-mobile">
{t("sources.file-tree.length")}
</th>
<th className="is-hidden-mobile">
{t("sources.file-tree.lastModified")}
</th>
<th>{t("sources.file-tree.description")}</th>
</tr>
</thead>
<tbody>
{files.map(file => (
<FileTreeLeaf
key={file.name}
file={file}
baseUrl={baseUrlWithRevision}
/>
))}
</tbody>
</table>
);
}
}
const mapStateToProps = (state: any, ownProps: Props) => {
const { repository, revision, path } = ownProps;
const loading = isFetchSourcesPending(state, repository, revision, path);
const error = getFetchSourcesFailure(state, repository, revision, path);
const tree = getSources(state, repository, revision, path);
return {
revision,
path,
loading,
error,
tree
};
};
const mapDispatchToProps = dispatch => {
return {
fetchSources: (repository: Repository, revision: string, path: string) => {
dispatch(fetchSources(repository, revision, path));
}
};
};
export default compose(
withRouter,
connect(
mapStateToProps,
mapDispatchToProps
)
)(injectSheet(styles)(translate("repos")(FileTree)));

View File

@@ -0,0 +1,12 @@
// @flow
import { findParent } from "./FileTree";
describe("find parent tests", () => {
it("should return the parent path", () => {
expect(findParent("src/main/js/")).toBe("src/main");
expect(findParent("src/main/js")).toBe("src/main");
expect(findParent("src/main")).toBe("src");
expect(findParent("src")).toBe("");
});
});

View File

@@ -0,0 +1,81 @@
//@flow
import * as React from "react";
import injectSheet from "react-jss";
import { DateFromNow } from "@scm-manager/ui-components";
import FileSize from "./FileSize";
import FileIcon from "./FileIcon";
import { Link } from "react-router-dom";
import type { File } from "@scm-manager/ui-types";
const styles = {
iconColumn: {
width: "16px"
}
};
type Props = {
file: File,
baseUrl: string,
// context props
classes: any
};
export function createLink(base: string, file: File) {
let link = base;
if (file.path) {
let path = file.path;
if (path.startsWith("/")) {
path = path.substring(1);
}
link += "/" + path;
}
if (!link.endsWith("/")) {
link += "/";
}
return link;
}
class FileTreeLeaf extends React.Component<Props> {
createLink = (file: File) => {
return createLink(this.props.baseUrl, file);
};
createFileIcon = (file: File) => {
if (file.directory) {
return (
<Link to={this.createLink(file)}>
<FileIcon file={file} />
</Link>
);
}
return <FileIcon file={file} />;
};
createFileName = (file: File) => {
if (file.directory) {
return <Link to={this.createLink(file)}>{file.name}</Link>;
}
return file.name;
};
render() {
const { file, classes } = this.props;
const fileSize = file.directory ? "" : <FileSize bytes={file.length} />;
return (
<tr>
<td className={classes.iconColumn}>{this.createFileIcon(file)}</td>
<td>{this.createFileName(file)}</td>
<td className="is-hidden-mobile">{fileSize}</td>
<td className="is-hidden-mobile">
<DateFromNow date={file.lastModified} />
</td>
<td>{file.description}</td>
</tr>
);
}
}
export default injectSheet(styles)(FileTreeLeaf);

View File

@@ -0,0 +1,24 @@
// @flow
import { createLink } from "./FileTreeLeaf";
import type { File } from "@scm-manager/ui-types";
describe("create link tests", () => {
function dir(path: string): File {
return {
name: "dir",
path: path,
directory: true
};
}
it("should create link", () => {
expect(createLink("src", dir("main"))).toBe("src/main/");
expect(createLink("src", dir("/main"))).toBe("src/main/");
expect(createLink("src", dir("/main/"))).toBe("src/main/");
});
it("should return base url if the directory path is empty", () => {
expect(createLink("src", dir(""))).toBe("src/");
});
});

View File

@@ -0,0 +1,131 @@
// @flow
import React from "react";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import type { Repository, Branch } from "@scm-manager/ui-types";
import FileTree from "../components/FileTree";
import { ErrorNotification, Loading } from "@scm-manager/ui-components";
import BranchSelector from "../../containers/BranchSelector";
import {
fetchBranches,
getBranches,
getFetchBranchesFailure,
isFetchBranchesPending
} from "../../modules/branches";
import { compose } from "redux";
type Props = {
repository: Repository,
loading: boolean,
error: Error,
baseUrl: string,
branches: Branch[],
revision: string,
path: string,
// dispatch props
fetchBranches: Repository => void,
// Context props
history: any,
match: any
};
class Sources extends React.Component<Props> {
componentDidMount() {
const { fetchBranches, repository } = this.props;
fetchBranches(repository);
}
branchSelected = (branch?: Branch) => {
const { baseUrl, history, path } = this.props;
let url;
if (branch) {
if (path) {
url = `${baseUrl}/${encodeURIComponent(branch.name)}/${path}`;
} else {
url = `${baseUrl}/${encodeURIComponent(branch.name)}/`;
}
} else {
url = `${baseUrl}/`;
}
history.push(url);
};
render() {
const { repository, baseUrl, loading, error, revision, path } = this.props;
if (error) {
return <ErrorNotification error={error} />;
}
if (loading) {
return <Loading />;
}
return (
<>
{this.renderBranchSelector()}
<FileTree
repository={repository}
revision={revision}
path={path}
baseUrl={baseUrl}
/>
</>
);
}
renderBranchSelector = () => {
const { repository, branches, revision } = this.props;
if (repository._links.branches) {
return (
<BranchSelector
branches={branches}
selectedBranch={revision}
selected={(b: Branch) => {
this.branchSelected(b);
}}
/>
);
}
return null;
};
}
const mapStateToProps = (state, ownProps) => {
const { repository, match } = ownProps;
const { revision, path } = match.params;
const decodedRevision = revision ? decodeURIComponent(revision) : undefined;
const loading = isFetchBranchesPending(state, repository);
const error = getFetchBranchesFailure(state, repository);
const branches = getBranches(state, repository);
return {
repository,
revision: decodedRevision,
path,
loading,
error,
branches
};
};
const mapDispatchToProps = dispatch => {
return {
fetchBranches: (repository: Repository) => {
dispatch(fetchBranches(repository));
}
};
};
export default compose(
withRouter,
connect(
mapStateToProps,
mapDispatchToProps
)
)(Sources);

View File

@@ -0,0 +1,141 @@
// @flow
import * as types from "../../../modules/types";
import type { Repository, File, Action } from "@scm-manager/ui-types";
import { apiClient } from "@scm-manager/ui-components";
import { isPending } from "../../../modules/pending";
import { getFailure } from "../../../modules/failure";
export const FETCH_SOURCES = "scm/repos/FETCH_SOURCES";
export const FETCH_SOURCES_PENDING = `${FETCH_SOURCES}_${types.PENDING_SUFFIX}`;
export const FETCH_SOURCES_SUCCESS = `${FETCH_SOURCES}_${types.SUCCESS_SUFFIX}`;
export const FETCH_SOURCES_FAILURE = `${FETCH_SOURCES}_${types.FAILURE_SUFFIX}`;
export function fetchSources(
repository: Repository,
revision: string,
path: string
) {
return function(dispatch: any) {
dispatch(fetchSourcesPending(repository, revision, path));
return apiClient
.get(createUrl(repository, revision, path))
.then(response => response.json())
.then(sources => {
dispatch(fetchSourcesSuccess(repository, revision, path, sources));
})
.catch(err => {
const error = new Error(`failed to fetch sources: ${err.message}`);
dispatch(fetchSourcesFailure(repository, revision, path, error));
});
};
}
function createUrl(repository: Repository, revision: string, path: string) {
const base = repository._links.sources.href;
if (!revision && !path) {
return base;
}
// TODO handle trailing slash
const pathDefined = path ? path : "";
return `${base}${encodeURIComponent(revision)}/${pathDefined}`;
}
export function fetchSourcesPending(
repository: Repository,
revision: string,
path: string
): Action {
return {
type: FETCH_SOURCES_PENDING,
itemId: createItemId(repository, revision, path)
};
}
export function fetchSourcesSuccess(
repository: Repository,
revision: string,
path: string,
sources: File
) {
return {
type: FETCH_SOURCES_SUCCESS,
payload: sources,
itemId: createItemId(repository, revision, path)
};
}
export function fetchSourcesFailure(
repository: Repository,
revision: string,
path: string,
error: Error
): Action {
return {
type: FETCH_SOURCES_FAILURE,
payload: error,
itemId: createItemId(repository, revision, path)
};
}
function createItemId(repository: Repository, revision: string, path: string) {
const revPart = revision ? revision : "_";
const pathPart = path ? path : "";
return `${repository.namespace}/${repository.name}/${revPart}/${pathPart}`;
}
// reducer
export default function reducer(
state: any = {},
action: Action = { type: "UNKNOWN" }
): any {
if (action.type === FETCH_SOURCES_SUCCESS) {
return {
[action.itemId]: action.payload,
...state
};
}
return state;
}
// selectors
export function getSources(
state: any,
repository: Repository,
revision: string,
path: string
): ?File {
if (state.sources) {
return state.sources[createItemId(repository, revision, path)];
}
return null;
}
export function isFetchSourcesPending(
state: any,
repository: Repository,
revision: string,
path: string
): boolean {
return isPending(
state,
FETCH_SOURCES,
createItemId(repository, revision, path)
);
}
export function getFetchSourcesFailure(
state: any,
repository: Repository,
revision: string,
path: string
): ?Error {
return getFailure(
state,
FETCH_SOURCES,
createItemId(repository, revision, path)
);
}

View File

@@ -0,0 +1,220 @@
// @flow
import type { Repository } from "@scm-manager/ui-types";
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import fetchMock from "fetch-mock";
import {
FETCH_SOURCES,
FETCH_SOURCES_FAILURE,
FETCH_SOURCES_PENDING,
FETCH_SOURCES_SUCCESS,
fetchSources,
getFetchSourcesFailure,
isFetchSourcesPending,
default as reducer,
getSources,
fetchSourcesSuccess
} from "./sources";
const sourcesUrl =
"http://localhost:8081/scm/rest/api/v2/repositories/scm/core/sources/";
const repository: Repository = {
name: "core",
namespace: "scm",
type: "git",
_links: {
sources: {
href: sourcesUrl
}
}
};
const collection = {
revision: "76aae4bb4ceacf0e88938eb5b6832738b7d537b4",
_links: {
self: {
href:
"http://localhost:8081/scm/rest/api/v2/repositories/scm/core/sources/76aae4bb4ceacf0e88938eb5b6832738b7d537b4/"
}
},
_embedded: {
files: [
{
name: "src",
path: "src",
directory: true,
description: null,
length: 176,
lastModified: null,
subRepository: null,
_links: {
self: {
href:
"http://localhost:8081/scm/rest/api/v2/repositories/scm/core/sources/76aae4bb4ceacf0e88938eb5b6832738b7d537b4/src"
}
}
},
{
name: "package.json",
path: "package.json",
directory: false,
description: "bump version",
length: 780,
lastModified: "2017-07-31T11:17:19Z",
subRepository: null,
_links: {
self: {
href:
"http://localhost:8081/scm/rest/api/v2/repositories/scm/core/content/76aae4bb4ceacf0e88938eb5b6832738b7d537b4/package.json"
},
history: {
href:
"http://localhost:8081/scm/rest/api/v2/repositories/scm/core/sources/history/76aae4bb4ceacf0e88938eb5b6832738b7d537b4/package.json"
}
}
}
]
}
};
describe("sources fetch", () => {
const mockStore = configureMockStore([thunk]);
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
});
it("should fetch the sources of the repository", () => {
fetchMock.getOnce(sourcesUrl, collection);
const expectedActions = [
{ type: FETCH_SOURCES_PENDING, itemId: "scm/core/_/" },
{
type: FETCH_SOURCES_SUCCESS,
itemId: "scm/core/_/",
payload: collection
}
];
const store = mockStore({});
return store.dispatch(fetchSources(repository)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it("should fetch the sources of the repository with the given revision and path", () => {
fetchMock.getOnce(sourcesUrl + "abc/src", collection);
const expectedActions = [
{ type: FETCH_SOURCES_PENDING, itemId: "scm/core/abc/src" },
{
type: FETCH_SOURCES_SUCCESS,
itemId: "scm/core/abc/src",
payload: collection
}
];
const store = mockStore({});
return store.dispatch(fetchSources(repository, "abc", "src")).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
it("should dispatch FETCH_SOURCES_FAILURE on server error", () => {
fetchMock.getOnce(sourcesUrl, {
status: 500
});
const store = mockStore({});
return store.dispatch(fetchSources(repository)).then(() => {
const actions = store.getActions();
expect(actions[0].type).toBe(FETCH_SOURCES_PENDING);
expect(actions[1].type).toBe(FETCH_SOURCES_FAILURE);
expect(actions[1].itemId).toBe("scm/core/_/");
expect(actions[1].payload).toBeDefined();
});
});
});
describe("reducer tests", () => {
it("should return unmodified state on unknown action", () => {
const state = {};
expect(reducer(state)).toBe(state);
});
it("should store the collection, without revision and path", () => {
const expectedState = {
"scm/core/_/": collection
};
expect(
reducer({}, fetchSourcesSuccess(repository, null, null, collection))
).toEqual(expectedState);
});
it("should store the collection, with revision and path", () => {
const expectedState = {
"scm/core/abc/src/main": collection
};
expect(
reducer(
{},
fetchSourcesSuccess(repository, "abc", "src/main", collection)
)
).toEqual(expectedState);
});
});
describe("selector tests", () => {
it("should return null", () => {
expect(getSources({}, repository)).toBeFalsy();
});
it("should return the source collection without revision and path", () => {
const state = {
sources: {
"scm/core/_/": collection
}
};
expect(getSources(state, repository)).toBe(collection);
});
it("should return the source collection without revision and path", () => {
const state = {
sources: {
"scm/core/abc/src/main": collection
}
};
expect(getSources(state, repository, "abc", "src/main")).toBe(collection);
});
it("should return true, when fetch sources is pending", () => {
const state = {
pending: {
[FETCH_SOURCES + "/scm/core/_/"]: true
}
};
expect(isFetchSourcesPending(state, repository)).toEqual(true);
});
it("should return false, when fetch sources is not pending", () => {
expect(isFetchSourcesPending({}, repository)).toEqual(false);
});
const error = new Error("incredible error from hell");
it("should return error when fetch sources did fail", () => {
const state = {
failure: {
[FETCH_SOURCES + "/scm/core/_/"]: error
}
};
expect(getFetchSourcesFailure(state, repository)).toEqual(error);
});
it("should return undefined when fetch sources did not fail", () => {
expect(getFetchSourcesFailure({}, repository)).toBe(undefined);
});
});