utils.tsx 8.7 KB

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