utils.tsx 8.9 KB

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