utils.tsx 7.0 KB

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