utils.tsx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. /**
  134. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  135. * means that:
  136. * - 1000 megabytes is equal to 1 gigabyte
  137. * - 1024 mebibytes is equal to 1 gibibytes
  138. *
  139. * We will use base 10 throughout billing for attachments. This function formats
  140. * quota/usage values for display.
  141. *
  142. * For storage/memory/file sizes, please take a look at formatBytesBase2
  143. */
  144. export function formatBytesBase10(bytes: number, u: number = 0) {
  145. const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  146. const threshold = 1000;
  147. while (bytes >= threshold) {
  148. bytes /= threshold;
  149. u += 1;
  150. }
  151. return formatNumberWithDynamicDecimalPoints(bytes) + ' ' + units[u];
  152. }
  153. /**
  154. * Note the difference between *a-bytes (base 10) vs *i-bytes (base 2), which
  155. * means that:
  156. * - 1000 megabytes is equal to 1 gigabyte
  157. * - 1024 mebibytes is equal to 1 gibibytes
  158. *
  159. * We will use base 2 to display storage/memory/file sizes as that is commonly
  160. * used by Windows or RAM or CPU cache sizes, and it is more familiar to the user
  161. *
  162. * For billing-related code around attachments. please take a look at
  163. * formatBytesBase10
  164. */
  165. export function formatBytesBase2(bytes: number, fixPoints: number | false = 1): string {
  166. const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  167. const thresh = 1024;
  168. if (bytes < thresh) {
  169. return (
  170. (fixPoints === false
  171. ? formatNumberWithDynamicDecimalPoints(bytes)
  172. : bytes.toFixed(fixPoints)) + ' B'
  173. );
  174. }
  175. let u = -1;
  176. do {
  177. bytes /= thresh;
  178. ++u;
  179. } while (bytes >= thresh);
  180. return (
  181. (fixPoints === false
  182. ? formatNumberWithDynamicDecimalPoints(bytes)
  183. : bytes.toFixed(fixPoints)) +
  184. ' ' +
  185. units[u]
  186. );
  187. }
  188. export function getShortCommitHash(hash: string): string {
  189. if (hash.match(/^[a-f0-9]{40}$/)) {
  190. hash = hash.substring(0, 7);
  191. }
  192. return hash;
  193. }
  194. export function parseRepo<T>(repo: T): T {
  195. if (typeof repo === 'string') {
  196. const re = /(?:github\.com|bitbucket\.org)\/([^\/]+\/[^\/]+)/i;
  197. const match = repo.match(re);
  198. const parsedRepo = match ? match[1] : repo;
  199. return parsedRepo as any;
  200. }
  201. return repo;
  202. }
  203. /**
  204. * Converts a multi-line textarea input value into an array,
  205. * eliminating empty lines
  206. */
  207. export function extractMultilineFields(value: string): string[] {
  208. return value
  209. .split('\n')
  210. .map(f => trim(f))
  211. .filter(f => f !== '');
  212. }
  213. /**
  214. * If the value is of type Array, converts it to type string, keeping the line breaks, if there is any
  215. */
  216. export function convertMultilineFieldValue<T extends string | string[]>(
  217. value: T
  218. ): string {
  219. if (Array.isArray(value)) {
  220. return value.join('\n');
  221. }
  222. if (typeof value === 'string') {
  223. return value.split('\n').join('\n');
  224. }
  225. return '';
  226. }
  227. function projectDisplayCompare(a: Project, b: Project): number {
  228. if (a.isBookmarked !== b.isBookmarked) {
  229. return a.isBookmarked ? -1 : 1;
  230. }
  231. return a.slug.localeCompare(b.slug);
  232. }
  233. // Sort a list of projects by bookmarkedness, then by id
  234. export function sortProjects(projects: Array<Project>): Array<Project> {
  235. return projects.sort(projectDisplayCompare);
  236. }
  237. // build actorIds
  238. export const buildUserId = (id: string) => `user:${id}`;
  239. export const buildTeamId = (id: string) => `team:${id}`;
  240. /**
  241. * Removes the organization / project scope prefix on feature names.
  242. */
  243. export function descopeFeatureName<T>(feature: T): T | string {
  244. if (typeof feature !== 'string') {
  245. return feature;
  246. }
  247. const results = feature.match(/(?:^(?:projects|organizations):)?(.*)/);
  248. if (results && results.length > 0) {
  249. return results.pop()!;
  250. }
  251. return feature;
  252. }
  253. export function isWebpackChunkLoadingError(error: Error): boolean {
  254. return (
  255. error &&
  256. typeof error.message === 'string' &&
  257. error.message.toLowerCase().includes('loading chunk')
  258. );
  259. }
  260. export function deepFreeze<T>(object: T) {
  261. // Retrieve the property names defined on object
  262. const propNames = Object.getOwnPropertyNames(object);
  263. // Freeze properties before freezing self
  264. for (const name of propNames) {
  265. const value = object[name];
  266. object[name] = value && typeof value === 'object' ? deepFreeze(value) : value;
  267. }
  268. return Object.freeze(object);
  269. }
  270. export function generateQueryWithTag(prevQuery: Query, tag: EventTag): Query {
  271. const query = {...prevQuery};
  272. // some tags are dedicated query strings since other parts of the app consumes this,
  273. // for example, the global selection header.
  274. switch (tag.key) {
  275. case 'environment':
  276. query.environment = tag.value;
  277. break;
  278. case 'project':
  279. query.project = tag.value;
  280. break;
  281. default:
  282. query.query = appendTagCondition(query.query, tag.key, tag.value);
  283. }
  284. return query;
  285. }
  286. export const isFunction = (value: any): value is Function => typeof value === 'function';
  287. // NOTE: only escapes a " if it's not already escaped
  288. export function escapeDoubleQuotes(str: string) {
  289. return str.replace(/\\([\s\S])|(")/g, '\\$1$2');
  290. }
  291. export function generateBaseControlSiloUrl() {
  292. return ConfigStore.get('links').sentryUrl || '';
  293. }
  294. export function generateOrgSlugUrl(orgSlug) {
  295. const sentryDomain = window.__initialData.links.sentryUrl.split('/')[2];
  296. return `${window.location.protocol}//${orgSlug}.${sentryDomain}${window.location.pathname}`;
  297. }