Commit 397fd09a authored by Phil Hughes's avatar Phil Hughes

Merge branch 'winh-parse-boolean' into 'master'

Add parseBoolean helper function

See merge request gitlab-org/gitlab-ce!23283
parents 07c1466b 0bf740fa
import $ from 'jquery';
import { convertPermissionToBoolean } from '~/lib/utils/common_utils';
import { parseBoolean } from '~/lib/utils/common_utils';
import GfmAutoComplete from '~/gfm_auto_complete';
export default function initGFMInput() {
$('.js-gfm-input:not(.js-vue-textarea)').each((i, el) => {
const gfm = new GfmAutoComplete(gl.GfmAutoComplete && gl.GfmAutoComplete.dataSources);
const enableGFM = convertPermissionToBoolean(el.dataset.supportsAutocomplete);
const enableGFM = parseBoolean(el.dataset.supportsAutocomplete);
gfm.setup($(el), {
emojis: true,
......
import { n__ } from '../locale';
import { convertPermissionToBoolean } from '../lib/utils/common_utils';
import { parseBoolean } from '../lib/utils/common_utils';
export default class SecretValues {
constructor({
......@@ -16,7 +16,7 @@ export default class SecretValues {
this.revealButton = this.container.querySelector('.js-secret-value-reveal-button');
if (this.revealButton) {
const isRevealed = convertPermissionToBoolean(this.revealButton.dataset.secretRevealStatus);
const isRevealed = parseBoolean(this.revealButton.dataset.secretRevealStatus);
this.updateDom(isRevealed);
this.revealButton.addEventListener('click', this.onRevealButtonClicked.bind(this));
......@@ -24,9 +24,7 @@ export default class SecretValues {
}
onRevealButtonClicked() {
const previousIsRevealed = convertPermissionToBoolean(
this.revealButton.dataset.secretRevealStatus,
);
const previousIsRevealed = parseBoolean(this.revealButton.dataset.secretRevealStatus);
this.updateDom(!previousIsRevealed);
}
......
......@@ -4,6 +4,7 @@ import Mousetrap from 'mousetrap';
import axios from '../../lib/utils/axios_utils';
import { refreshCurrentPage, visitUrl } from '../../lib/utils/url_utility';
import findAndFollowLink from '../../lib/utils/navigation_utility';
import { parseBoolean } from '~/lib/utils/common_utils';
const defaultStopCallback = Mousetrap.stopCallback;
Mousetrap.stopCallback = (e, element, combo) => {
......@@ -61,7 +62,7 @@ export default class Shortcuts {
static onTogglePerfBar(e) {
e.preventDefault();
const performanceBarCookieName = 'perf_bar_enabled';
if (Cookies.get(performanceBarCookieName) === 'true') {
if (parseBoolean(Cookies.get(performanceBarCookieName))) {
Cookies.set(performanceBarCookieName, 'false', { path: '/' });
} else {
Cookies.set(performanceBarCookieName, 'true', { path: '/' });
......
......@@ -24,7 +24,7 @@ import BoardSidebar from './components/board_sidebar';
import initNewListDropdown from './components/new_list_dropdown';
import BoardAddIssuesModal from './components/modal/index.vue';
import '~/vue_shared/vue_resource_interceptor';
import { NavigationType } from '~/lib/utils/common_utils';
import { NavigationType, parseBoolean } from '~/lib/utils/common_utils';
let issueBoardsApp;
......@@ -60,7 +60,7 @@ export default () => {
boardsEndpoint: $boardApp.dataset.boardsEndpoint,
listsEndpoint: $boardApp.dataset.listsEndpoint,
boardId: $boardApp.dataset.boardId,
disabled: $boardApp.dataset.disabled === 'true',
disabled: parseBoolean($boardApp.dataset.disabled),
issueLinkBase: $boardApp.dataset.issueLinkBase,
rootPath: $boardApp.dataset.rootPath,
bulkUpdatePath: $boardApp.dataset.bulkUpdatePath,
......
......@@ -5,7 +5,7 @@ import $ from 'jquery';
import _ from 'underscore';
import Vue from 'vue';
import Cookies from 'js-cookie';
import { getUrlParamsArray } from '~/lib/utils/common_utils';
import { getUrlParamsArray, parseBoolean } from '~/lib/utils/common_utils';
const boardsStore = {
disabled: false,
......@@ -78,7 +78,7 @@ const boardsStore = {
});
},
welcomeIsHidden() {
return Cookies.get('issue_board_welcome_hidden') === 'true';
return parseBoolean(Cookies.get('issue_board_welcome_hidden'));
},
removeList(id, type = 'blank') {
const list = this.findList('id', id, type);
......
......@@ -2,7 +2,7 @@
import $ from 'jquery';
import { visitUrl } from './lib/utils/url_utility';
import { convertPermissionToBoolean } from './lib/utils/common_utils';
import { parseBoolean } from './lib/utils/common_utils';
export default class BuildArtifacts {
constructor() {
......@@ -22,7 +22,7 @@ export default class BuildArtifacts {
// eslint-disable-next-line class-methods-use-this
setupEntryClick() {
return $('.tree-holder').on('click', 'tr[data-link]', function() {
visitUrl(this.dataset.link, convertPermissionToBoolean(this.dataset.externalLink));
visitUrl(this.dataset.link, parseBoolean(this.dataset.externalLink));
});
}
// eslint-disable-next-line class-methods-use-this
......
......@@ -2,7 +2,7 @@ import _ from 'underscore';
import axios from '../lib/utils/axios_utils';
import { s__ } from '../locale';
import Flash from '../flash';
import { convertPermissionToBoolean } from '../lib/utils/common_utils';
import { parseBoolean } from '../lib/utils/common_utils';
import statusCodes from '../lib/utils/http_status';
import VariableList from './ci_variable_list';
......@@ -101,7 +101,7 @@ export default class AjaxVariableList {
// If we submitted a row that was destroyed, remove it so we don't try
// to destroy it again which would cause a BE error
const destroyInput = row.querySelector('.js-ci-variable-input-destroy');
if (convertPermissionToBoolean(destroyInput.value)) {
if (parseBoolean(destroyInput.value)) {
row.remove();
// Update the ID input so any future edits and `_destroy` will apply on the BE
} else {
......
import $ from 'jquery';
import { convertPermissionToBoolean } from '../lib/utils/common_utils';
import { parseBoolean } from '../lib/utils/common_utils';
import { s__ } from '../locale';
import setupToggleButtons from '../toggle_buttons';
import CreateItemDropdown from '../create_item_dropdown';
......@@ -150,7 +150,7 @@ export default class VariableList {
removeRow(row) {
const $row = $(row);
const isPersisted = convertPermissionToBoolean($row.attr('data-is-persisted'));
const isPersisted = parseBoolean($row.attr('data-is-persisted'));
if (isPersisted) {
$row.hide();
......
......@@ -2,6 +2,7 @@ import $ from 'jquery';
import Cookies from 'js-cookie';
import _ from 'underscore';
import bp from './breakpoints';
import { parseBoolean } from '~/lib/utils/common_utils';
export default class ContextualSidebar {
constructor() {
......@@ -78,7 +79,7 @@ export default class ContextualSidebar {
if (breakpoint === 'sm' || breakpoint === 'md') {
this.toggleCollapsedSidebar(true);
} else if (breakpoint === 'lg') {
const collapse = Cookies.get('sidebar_collapsed') === 'true';
const collapse = parseBoolean(Cookies.get('sidebar_collapsed'));
this.toggleCollapsedSidebar(collapse);
}
}
......
<script>
import { mapActions, mapGetters, mapState } from 'vuex';
import { GlTooltipDirective } from '@gitlab/ui';
import { convertPermissionToBoolean } from '~/lib/utils/common_utils';
import { parseBoolean } from '~/lib/utils/common_utils';
import Icon from '~/vue_shared/components/icon.vue';
import FileRow from '~/vue_shared/components/file_row.vue';
import FileRowStats from './file_row_stats.vue';
......@@ -18,8 +18,7 @@ export default {
},
data() {
const treeListStored = localStorage.getItem(treeListStorageKey);
const renderTreeList =
treeListStored !== null ? convertPermissionToBoolean(treeListStored) : true;
const renderTreeList = treeListStored !== null ? parseBoolean(treeListStored) : true;
return {
search: '',
......
import Cookies from 'js-cookie';
import { getParameterValues } from '~/lib/utils/url_utility';
import bp from '~/breakpoints';
import { parseBoolean } from '~/lib/utils/common_utils';
import { INLINE_DIFF_VIEW_TYPE, DIFF_VIEW_COOKIE_NAME, MR_TREE_SHOW_KEY } from '../../constants';
const viewTypeFromQueryString = getParameterValues('view')[0];
......@@ -22,7 +23,7 @@ export default () => ({
tree: [],
treeEntries: {},
showTreeList:
storedTreeShow === null ? bp.getBreakpointSize() !== 'xs' : storedTreeShow === 'true',
storedTreeShow === null ? bp.getBreakpointSize() !== 'xs' : parseBoolean(storedTreeShow),
currentDiffFileId: '',
projectPath: '',
commentForms: [],
......
import Vue from 'vue';
import environmentsFolderApp from './environments_folder_view.vue';
import { convertPermissionToBoolean } from '../../lib/utils/common_utils';
import { parseBoolean } from '../../lib/utils/common_utils';
import Translate from '../../vue_shared/translate';
Vue.use(Translate);
......@@ -18,8 +18,8 @@ export default () =>
endpoint: environmentsData.endpoint,
folderName: environmentsData.folderName,
cssContainerClass: environmentsData.cssClass,
canCreateDeployment: convertPermissionToBoolean(environmentsData.canCreateDeployment),
canReadEnvironment: convertPermissionToBoolean(environmentsData.canReadEnvironment),
canCreateDeployment: parseBoolean(environmentsData.canCreateDeployment),
canReadEnvironment: parseBoolean(environmentsData.canReadEnvironment),
};
},
render(createElement) {
......
import Vue from 'vue';
import environmentsComponent from './components/environments_app.vue';
import { convertPermissionToBoolean } from '../lib/utils/common_utils';
import { parseBoolean } from '../lib/utils/common_utils';
import Translate from '../vue_shared/translate';
Vue.use(Translate);
......@@ -19,9 +19,9 @@ export default () =>
newEnvironmentPath: environmentsData.newEnvironmentPath,
helpPagePath: environmentsData.helpPagePath,
cssContainerClass: environmentsData.cssClass,
canCreateEnvironment: convertPermissionToBoolean(environmentsData.canCreateEnvironment),
canCreateDeployment: convertPermissionToBoolean(environmentsData.canCreateDeployment),
canReadEnvironment: convertPermissionToBoolean(environmentsData.canReadEnvironment),
canCreateEnvironment: parseBoolean(environmentsData.canCreateEnvironment),
canCreateDeployment: parseBoolean(environmentsData.canCreateDeployment),
canReadEnvironment: parseBoolean(environmentsData.canReadEnvironment),
};
},
render(createElement) {
......
import Vue from 'vue';
import { parseBoolean } from '~/lib/utils/common_utils';
import Translate from '../vue_shared/translate';
import GroupFilterableList from './groups_filterable_list';
import GroupsStore from './store/groups_store';
......@@ -38,7 +39,7 @@ export default (containerId = 'js-groups-tree', endpoint, action = '') => {
},
data() {
const { dataset } = dataEl || this.$options.el;
const hideProjects = dataset.hideProjects === 'true';
const hideProjects = parseBoolean(dataset.hideProjects);
const service = new GroupsService(endpoint || dataset.endpoint);
const store = new GroupsStore(hideProjects);
......
......@@ -4,6 +4,7 @@ import Translate from '~/vue_shared/translate';
import { highCountTrim } from '~/lib/utils/text_utility';
import SetStatusModalTrigger from './set_status_modal/set_status_modal_trigger.vue';
import SetStatusModalWrapper from './set_status_modal/set_status_modal_wrapper.vue';
import { parseBoolean } from '~/lib/utils/common_utils';
/**
* Updates todo counter when todos are toggled.
......@@ -36,7 +37,7 @@ document.addEventListener('DOMContentLoaded', () => {
const { hasStatus } = this.$options.el.dataset;
return {
hasStatus: hasStatus === 'true',
hasStatus: parseBoolean(hasStatus),
};
},
render(createElement) {
......
......@@ -4,7 +4,7 @@ import Translate from '~/vue_shared/translate';
import ide from './components/ide.vue';
import store from './stores';
import router from './ide_router';
import { convertPermissionToBoolean } from '../lib/utils/common_utils';
import { parseBoolean } from '../lib/utils/common_utils';
Vue.use(Translate);
......@@ -40,7 +40,7 @@ export function initIde(el, options = {}) {
webIDEHelpPagePath: el.dataset.webIdeHelpPagePath,
});
this.setInitialData({
clientsidePreviewEnabled: convertPermissionToBoolean(el.dataset.clientsidePreviewEnabled),
clientsidePreviewEnabled: parseBoolean(el.dataset.clientsidePreviewEnabled),
...extraInitialData(el),
});
},
......
......@@ -3,7 +3,7 @@ import _ from 'underscore';
import { __, sprintf } from './locale';
import axios from './lib/utils/axios_utils';
import flash from './flash';
import { convertPermissionToBoolean } from './lib/utils/common_utils';
import { parseBoolean } from './lib/utils/common_utils';
class ImporterStatus {
constructor({ jobsUrl, importUrl, ciCdOnly }) {
......@@ -141,7 +141,7 @@ function initImporterStatus() {
return new ImporterStatus({
jobsUrl: data.jobsImportPath,
importUrl: data.importPath,
ciCdOnly: convertPermissionToBoolean(data.ciCdOnly),
ciCdOnly: parseBoolean(data.ciCdOnly),
});
}
}
......
import Cookies from 'js-cookie';
import { parseBoolean } from '~/lib/utils/common_utils';
class Landing {
constructor(landingElement, dismissButton, cookieName) {
......@@ -30,7 +31,7 @@ class Landing {
}
isDismissed() {
return Cookies.get(this.cookieName) === 'true';
return parseBoolean(Cookies.get(this.cookieName));
}
}
......
......@@ -420,13 +420,29 @@ export const historyPushState = newUrl => {
window.history.pushState({}, document.title, newUrl);
};
/**
* Returns true for a String "true" and false otherwise.
* This is the opposite of Boolean(...).toString()
*
* @param {String} value
* @returns {Boolean}
*/
export const parseBoolean = value => value === 'true';
/**
* Converts permission provided as strings to booleans.
*
* @param {String} string
* @returns {Boolean}
*/
export const convertPermissionToBoolean = permission => permission === 'true';
export const convertPermissionToBoolean = permission => {
if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('convertPermissionToBoolean is deprecated! Please use parseBoolean instead.');
}
return parseBoolean(permission);
};
/**
* Back Off exponential algorithm
......
......@@ -8,7 +8,12 @@ import flash from './flash';
import BlobForkSuggestion from './blob/blob_fork_suggestion';
import initChangesDropdown from './init_changes_dropdown';
import bp from './breakpoints';
import { parseUrlPathname, handleLocationHash, isMetaClick } from './lib/utils/common_utils';
import {
parseUrlPathname,
handleLocationHash,
isMetaClick,
parseBoolean,
} from './lib/utils/common_utils';
import { isInVueNoteablePage } from './lib/utils/dom_utils';
import { getLocationHash } from './lib/utils/url_utility';
import Diff from './diff';
......@@ -440,7 +445,7 @@ export default class MergeRequestTabs {
// Expand the issuable sidebar unless the user explicitly collapsed it
expandView() {
if (Cookies.get('collapsed_gutter') === 'true') {
if (parseBoolean(Cookies.get('collapsed_gutter'))) {
return;
}
const $gutterIcon = $('.js-sidebar-toggle i:visible');
......
import Vue from 'vue';
import { convertPermissionToBoolean } from '~/lib/utils/common_utils';
import { parseBoolean } from '~/lib/utils/common_utils';
import Dashboard from './components/dashboard.vue';
export default () => {
......@@ -13,7 +13,7 @@ export default () => {
return createElement(Dashboard, {
props: {
...el.dataset,
hasMetrics: convertPermissionToBoolean(el.dataset.hasMetrics),
hasMetrics: parseBoolean(el.dataset.hasMetrics),
},
});
},
......
......@@ -3,10 +3,11 @@
import $ from 'jquery';
import Api from './api';
import { mergeUrlParams } from './lib/utils/url_utility';
import { parseBoolean } from '~/lib/utils/common_utils';
export default class NamespaceSelect {
constructor(opts) {
const isFilter = opts.dropdown.dataset.isFilter === 'true';
const isFilter = parseBoolean(opts.dropdown.dataset.isFilter);
const fieldName = opts.dropdown.dataset.fieldName || 'namespace_id';
$(opts.dropdown).glDropdown({
......
import $ from 'jquery';
import { truncate } from '../../../lib/utils/text_utility';
import { parseBoolean } from '~/lib/utils/common_utils';
const MAX_MESSAGE_LENGTH = 500;
const MESSAGE_CELL_SELECTOR = '.abuse-reports .message';
......@@ -26,7 +27,7 @@ export default class AbuseReports {
const $messageCellElement = $(this);
const originalMessage = $messageCellElement.data('originalMessage');
if (!originalMessage) return;
if ($messageCellElement.data('messageTruncated') === 'true') {
if (parseBoolean($messageCellElement.data('messageTruncated'))) {
$messageCellElement.data('messageTruncated', 'false');
$messageCellElement.text(originalMessage);
} else {
......
import $ from 'jquery';
import U2FRegister from '~/u2f/register';
import { parseBoolean } from '~/lib/utils/common_utils';
document.addEventListener('DOMContentLoaded', () => {
const twoFactorNode = document.querySelector('.js-two-factor-auth');
const skippable = twoFactorNode.dataset.twoFactorSkippable === 'true';
const skippable = parseBoolean(twoFactorNode.dataset.twoFactorSkippable);
if (skippable) {
const button = `<a class="btn btn-sm btn-warning float-right" data-method="patch" href="${
twoFactorNode.dataset.two_factor_skip_url
......
......@@ -3,6 +3,7 @@ import Vue from 'vue';
import Cookies from 'js-cookie';
import Translate from '../../../../../vue_shared/translate';
import illustrationSvg from '../icons/intro_illustration.svg';
import { parseBoolean } from '~/lib/utils/common_utils';
Vue.use(Translate);
......@@ -13,7 +14,7 @@ export default {
data() {
return {
docsUrl: document.getElementById('pipeline-schedules-callout').dataset.docsUrl,
calloutDismissed: Cookies.get(cookieKey) === 'true',
calloutDismissed: parseBoolean(Cookies.get(cookieKey)),
};
},
created() {
......
......@@ -2,7 +2,7 @@ import Vue from 'vue';
import PipelinesStore from '../../../../pipelines/stores/pipelines_store';
import pipelinesComponent from '../../../../pipelines/components/pipelines.vue';
import Translate from '../../../../vue_shared/translate';
import { convertPermissionToBoolean } from '../../../../lib/utils/common_utils';
import { parseBoolean } from '../../../../lib/utils/common_utils';
Vue.use(Translate);
......@@ -33,8 +33,8 @@ document.addEventListener(
noPipelinesSvgPath: this.dataset.noPipelinesSvgPath,
autoDevopsPath: this.dataset.helpAutoDevopsPath,
newPipelinePath: this.dataset.newPipelinePath,
canCreatePipeline: convertPermissionToBoolean(this.dataset.canCreatePipeline),
hasGitlabCi: convertPermissionToBoolean(this.dataset.hasGitlabCi),
canCreatePipeline: parseBoolean(this.dataset.canCreatePipeline),
hasGitlabCi: parseBoolean(this.dataset.hasGitlabCi),
ciLintPath: this.dataset.ciLintPath,
resetCachePath: this.dataset.resetCachePath,
},
......
import Vue from 'vue';
import _ from 'underscore';
import axios from '../../lib/utils/axios_utils';
import { parseBoolean } from '~/lib/utils/common_utils';
let vueResourceInterceptor;
......@@ -41,7 +42,8 @@ export default class PerformanceBarService {
// Vue Resource.
const requestUrl = (response.config || response).url;
const apiRequest = requestUrl && requestUrl.match(/^\/api\//);
const cachedResponse = response.headers && response.headers['x-gitlab-from-cache'] === 'true';
const cachedResponse =
response.headers && parseBoolean(response.headers['x-gitlab-from-cache']);
const fireCallback = requestUrl !== peekUrl && requestId && !apiRequest && !cachedResponse;
return [fireCallback, requestId, requestUrl];
......
import $ from 'jquery';
import axios from '~/lib/utils/axios_utils';
import flash from '../flash';
import { parseBoolean } from '~/lib/utils/common_utils';
export default class Profile {
constructor({ form } = {}) {
......@@ -80,7 +81,7 @@ export default class Profile {
setRepoRadio() {
const multiEditRadios = $('input[name="user[multi_file]"]');
if (this.newRepoActivated || this.newRepoActivated === 'true') {
if (parseBoolean(this.newRepoActivated)) {
multiEditRadios.filter('[value=on]').prop('checked', true);
} else {
multiEditRadios.filter('[value=off]').prop('checked', true);
......
import $ from 'jquery';
import Flash from './flash';
import { __ } from './locale';
import { convertPermissionToBoolean } from './lib/utils/common_utils';
import { parseBoolean } from './lib/utils/common_utils';
/*
example HAML:
......@@ -18,7 +18,7 @@ function updateToggle(toggle, isOn) {
}
function onToggleClicked(toggle, input, clickCallback) {
const previousIsOn = convertPermissionToBoolean(input.value);
const previousIsOn = parseBoolean(input.value);
// Visually change the toggle and start loading
updateToggle(toggle, !previousIsOn);
......@@ -51,7 +51,7 @@ export default function setupToggleButtons(container, clickCallback = () => {})
toggles.forEach(toggle => {
const input = toggle.querySelector('.js-project-feature-toggle-input');
const isOn = convertPermissionToBoolean(input.value);
const isOn = parseBoolean(input.value);
// Get the visible toggle in sync with the hidden input
updateToggle(toggle, isOn);
......
import $ from 'jquery';
import axios from './lib/utils/axios_utils';
import Flash, { hideFlash } from './flash';
import { convertPermissionToBoolean } from './lib/utils/common_utils';
import { parseBoolean } from './lib/utils/common_utils';
export default () => {
$('body').on('click', '.js-usage-consent-action', e => {
......@@ -11,8 +11,8 @@ export default () => {
const { url, checkEnabled, pingEnabled } = e.target.dataset;
const data = {
application_setting: {
version_check_enabled: convertPermissionToBoolean(checkEnabled),
usage_ping_enabled: convertPermissionToBoolean(pingEnabled),
version_check_enabled: parseBoolean(checkEnabled),
usage_ping_enabled: parseBoolean(pingEnabled),
},
};
......
......@@ -346,6 +346,24 @@ describe('common_utils', () => {
});
});
describe('parseBoolean', () => {
it('returns true for "true"', () => {
expect(commonUtils.parseBoolean('true')).toEqual(true);
});
it('returns false for "false"', () => {
expect(commonUtils.parseBoolean('false')).toEqual(false);
});
it('returns false for "something"', () => {
expect(commonUtils.parseBoolean('something')).toEqual(false);
});
it('returns false for null', () => {
expect(commonUtils.parseBoolean(null)).toEqual(false);
});
});
describe('convertPermissionToBoolean', () => {
it('should convert a boolean in a string to a boolean', () => {
expect(commonUtils.convertPermissionToBoolean('true')).toEqual(true);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment