utils.tsx 8.7 KB

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