utils.tsx 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import {Query} from 'history';
  2. import isArray from 'lodash/isArray';
  3. import isObject from 'lodash/isObject';
  4. import isString from 'lodash/isString';
  5. import ConfigStore from 'sentry/stores/configStore';
  6. import {Project} from 'sentry/types';
  7. import {EventTag} from 'sentry/types/event';
  8. import {formatNumberWithDynamicDecimalPoints} from 'sentry/utils/formatters';
  9. import {appendTagCondition} from 'sentry/utils/queryString';
  10. function arrayIsEqual(arr?: any[], other?: any[], deep?: boolean): boolean {
  11. // if the other array is a falsy value, return
  12. if (!arr && !other) {
  13. return true;
  14. }
  15. if (!arr || !other) {
  16. return false;
  17. }
  18. // compare lengths - can save a lot of time
  19. if (arr.length !== other.length) {
  20. return false;
  21. }
  22. return arr.every((val, idx) => valueIsEqual(val, other[idx], deep));
  23. }
  24. export function valueIsEqual(value?: any, other?: any, deep?: boolean): boolean {
  25. if (value === other) {
  26. return true;
  27. }
  28. if (isArray(value) || isArray(other)) {
  29. if (arrayIsEqual(value, other, deep)) {
  30. return true;
  31. }
  32. } else if (isObject(value) || isObject(other)) {
  33. if (objectMatchesSubset(value, other, deep)) {
  34. return true;
  35. }
  36. }
  37. return false;
  38. }
  39. function objectMatchesSubset(obj?: object, other?: object, deep?: boolean): boolean {
  40. let k: string;
  41. if (obj === other) {
  42. return true;
  43. }
  44. if (!obj || !other) {
  45. return false;
  46. }
  47. if (deep !== true) {
  48. for (k in other) {
  49. if (obj[k] !== other[k]) {
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. for (k in other) {
  56. if (!valueIsEqual(obj[k], other[k], deep)) {
  57. return false;
  58. }
  59. }
  60. return true;
  61. }
  62. export function intcomma(x: number): string {
  63. return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  64. }
  65. export function lastOfArray<T extends Array<unknown> | ReadonlyArray<unknown>>(
  66. t: T
  67. ): T[number] {
  68. return t[t.length - 1];
  69. }
  70. export function sortArray<T>(arr: Array<T>, score_fn: (entry: T) => string): Array<T> {
  71. arr.sort((a, b) => {
  72. const a_score = score_fn(a),
  73. b_score = score_fn(b);
  74. for (let i = 0; i < a_score.length; i++) {
  75. if (a_score[i] > b_score[i]) {
  76. return 1;
  77. }
  78. if (a_score[i] < b_score[i]) {
  79. return -1;
  80. }
  81. }
  82. return 0;
  83. });
  84. return arr;
  85. }
  86. export function objectIsEmpty(obj = {}): boolean {
  87. for (const prop in obj) {
  88. if (obj.hasOwnProperty(prop)) {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. export function trim(str: string): string {
  95. return str.replace(/^\s+|\s+$/g, '');
  96. }
  97. /**
  98. * Replaces slug special chars with a space
  99. */
  100. export function explodeSlug(slug: string): string {
  101. return trim(slug.replace(/[-_]+/g, ' '));
  102. }
  103. export function defined<T>(item: T): item is Exclude<T, null | undefined> {
  104. return item !== undefined && item !== null;
  105. }
  106. export function nl2br(str: string): string {
  107. return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
  108. }
  109. /**
  110. * This function has a critical security impact, make sure to check all usages before changing this function.
  111. * In some parts of our code we rely on that this only really is a string starting with http(s).
  112. */
  113. export function isUrl(str: any): boolean {
  114. return (
  115. !!str &&
  116. isString(str) &&
  117. (str.indexOf('http://') === 0 || str.indexOf('https://') === 0)
  118. );
  119. }
  120. export function escape(str: string): string {
  121. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  122. }
  123. export function percent(value: number, totalValue: number): number {
  124. // prevent division by zero
  125. if (totalValue === 0) {
  126. return 0;
  127. }
  128. return (value / totalValue) * 100;
  129. }
  130. export function toTitleCase(str: string): string {
  131. return str.replace(
  132. /\w\S*/g,
  133. txt => txt.charAt(0).toUpperCase() + txt.substring(1).toLowerCase()
  134. );
  135. }
  136. /**
  137. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  138. * means that:
  139. * - 1000 megabytes is equal to 1 gigabyte
  140. * - 1024 mebibytes is equal to 1 gibibytes
  141. *
  142. * We will use base 10 throughout billing for attachments. This function formats
  143. * quota/usage values for display.
  144. *
  145. * For storage/memory/file sizes, please take a look at formatBytesBase2
  146. */
  147. export function formatBytesBase10(bytes: number, u: number = 0) {
  148. const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  149. const threshold = 1000;
  150. while (bytes >= threshold) {
  151. bytes /= threshold;
  152. u += 1;
  153. }
  154. return formatNumberWithDynamicDecimalPoints(bytes) + ' ' + units[u];
  155. }
  156. /**
  157. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  158. * means that:
  159. * - 1000 megabytes is equal to 1 gigabyte
  160. * - 1024 mebibytes is equal to 1 gibibytes
  161. *
  162. * We will use base 2 to display storage/memory/file sizes as that is commonly
  163. * used by Windows or RAM or CPU cache sizes, and it is more familiar to the user
  164. *
  165. * For billing-related code around attachments. please take a look at
  166. * formatBytesBase10
  167. */
  168. export function formatBytesBase2(bytes: number, fixPoints: number | false = 1): string {
  169. const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  170. const thresh = 1024;
  171. if (bytes < thresh) {
  172. return (
  173. (fixPoints === false
  174. ? formatNumberWithDynamicDecimalPoints(bytes)
  175. : bytes.toFixed(fixPoints)) + ' B'
  176. );
  177. }
  178. let u = -1;
  179. do {
  180. bytes /= thresh;
  181. ++u;
  182. } while (bytes >= thresh);
  183. return (
  184. (fixPoints === false
  185. ? formatNumberWithDynamicDecimalPoints(bytes)
  186. : bytes.toFixed(fixPoints)) +
  187. ' ' +
  188. units[u]
  189. );
  190. }
  191. export function getShortCommitHash(hash: string): string {
  192. if (hash.match(/^[a-f0-9]{40}$/)) {
  193. hash = hash.substring(0, 7);
  194. }
  195. return hash;
  196. }
  197. export function parseRepo<T>(repo: T): T {
  198. if (typeof repo === 'string') {
  199. const re = /(?:github\.com|bitbucket\.org)\/([^\/]+\/[^\/]+)/i;
  200. const match = repo.match(re);
  201. const parsedRepo = match ? match[1] : repo;
  202. return parsedRepo as any;
  203. }
  204. return repo;
  205. }
  206. /**
  207. * Converts a multi-line textarea input value into an array,
  208. * eliminating empty lines
  209. */
  210. export function extractMultilineFields(value: string): string[] {
  211. return value
  212. .split('\n')
  213. .map(f => trim(f))
  214. .filter(f => f !== '');
  215. }
  216. /**
  217. * If the value is of type Array, converts it to type string, keeping the line breaks, if there is any
  218. */
  219. export function convertMultilineFieldValue<T extends string | string[]>(
  220. value: T
  221. ): string {
  222. if (Array.isArray(value)) {
  223. return value.join('\n');
  224. }
  225. if (typeof value === 'string') {
  226. return value.split('\n').join('\n');
  227. }
  228. return '';
  229. }
  230. function projectDisplayCompare(a: Project, b: Project): number {
  231. if (a.isBookmarked !== b.isBookmarked) {
  232. return a.isBookmarked ? -1 : 1;
  233. }
  234. return a.slug.localeCompare(b.slug);
  235. }
  236. // Sort a list of projects by bookmarkedness, then by id
  237. export function sortProjects(projects: Array<Project>): Array<Project> {
  238. return projects.sort(projectDisplayCompare);
  239. }
  240. // build actorIds
  241. export const buildUserId = (id: string) => `user:${id}`;
  242. export const buildTeamId = (id: string) => `team:${id}`;
  243. /**
  244. * Removes the organization / project scope prefix on feature names.
  245. */
  246. export function descopeFeatureName<T>(feature: T): T | string {
  247. if (typeof feature !== 'string') {
  248. return feature;
  249. }
  250. const results = feature.match(/(?:^(?:projects|organizations):)?(.*)/);
  251. if (results && results.length > 0) {
  252. return results.pop()!;
  253. }
  254. return feature;
  255. }
  256. export function isWebpackChunkLoadingError(error: Error): boolean {
  257. return (
  258. error &&
  259. typeof error.message === 'string' &&
  260. error.message.toLowerCase().includes('loading chunk')
  261. );
  262. }
  263. export function deepFreeze<T>(object: T) {
  264. // Retrieve the property names defined on object
  265. const propNames = Object.getOwnPropertyNames(object);
  266. // Freeze properties before freezing self
  267. for (const name of propNames) {
  268. const value = object[name];
  269. object[name] = value && typeof value === 'object' ? deepFreeze(value) : value;
  270. }
  271. return Object.freeze(object);
  272. }
  273. export function generateQueryWithTag(prevQuery: Query, tag: EventTag): Query {
  274. const query = {...prevQuery};
  275. // some tags are dedicated query strings since other parts of the app consumes this,
  276. // for example, the global selection header.
  277. switch (tag.key) {
  278. case 'environment':
  279. query.environment = tag.value;
  280. break;
  281. case 'project':
  282. query.project = tag.value;
  283. break;
  284. default:
  285. query.query = appendTagCondition(query.query, tag.key, tag.value);
  286. }
  287. return query;
  288. }
  289. export const isFunction = (value: any): value is Function => typeof value === 'function';
  290. // NOTE: only escapes a " if it's not already escaped
  291. export function escapeDoubleQuotes(str: string) {
  292. return str.replace(/\\([\s\S])|(")/g, '\\$1$2');
  293. }
  294. export function generateBaseControlSiloUrl() {
  295. return ConfigStore.get('links').sentryUrl || '';
  296. }
  297. export function generateOrgSlugUrl(orgSlug) {
  298. const sentryDomain = window.__initialData.links.sentryUrl.split('/')[2];
  299. return `${window.location.protocol}//${orgSlug}.${sentryDomain}${window.location.pathname}`;
  300. }