utils.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 {Project} from 'sentry/types';
  6. import {EventTag} from 'sentry/types/event';
  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 (isArray(value) || 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. !!str &&
  114. isString(str) &&
  115. (str.indexOf('http://') === 0 || str.indexOf('https://') === 0)
  116. );
  117. }
  118. export function escape(str: string): string {
  119. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  120. }
  121. export function percent(value: number, totalValue: number): number {
  122. // prevent division by zero
  123. if (totalValue === 0) {
  124. return 0;
  125. }
  126. return (value / totalValue) * 100;
  127. }
  128. export function toTitleCase(str: string): string {
  129. return str.replace(
  130. /\w\S*/g,
  131. txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()
  132. );
  133. }
  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 bytes.toLocaleString(undefined, {maximumFractionDigits: 2}) + ' ' + 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 = 1): string {
  167. const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
  168. const thresh = 1024;
  169. if (bytes < thresh) {
  170. return bytes + ' B';
  171. }
  172. let u = -1;
  173. do {
  174. bytes /= thresh;
  175. ++u;
  176. } while (bytes >= thresh);
  177. return bytes.toFixed(fixPoints) + ' ' + units[u];
  178. }
  179. export function getShortCommitHash(hash: string): string {
  180. if (hash.match(/^[a-f0-9]{40}$/)) {
  181. hash = hash.substr(0, 7);
  182. }
  183. return hash;
  184. }
  185. export function parseRepo<T>(repo: T): T {
  186. if (typeof repo === 'string') {
  187. const re = /(?:github\.com|bitbucket\.org)\/([^\/]+\/[^\/]+)/i;
  188. const match = repo.match(re);
  189. const parsedRepo = match ? match[1] : repo;
  190. return parsedRepo as any;
  191. }
  192. return repo;
  193. }
  194. /**
  195. * Converts a multi-line textarea input value into an array,
  196. * eliminating empty lines
  197. */
  198. export function extractMultilineFields(value: string): Array<string> {
  199. return value
  200. .split('\n')
  201. .map(f => trim(f))
  202. .filter(f => f !== '');
  203. }
  204. /**
  205. * If the value is of type Array, converts it to type string, keeping the line breaks, if there is any
  206. */
  207. export function convertMultilineFieldValue<T extends string | Array<string>>(
  208. value: T
  209. ): string {
  210. if (Array.isArray(value)) {
  211. return value.join('\n');
  212. }
  213. if (typeof value === 'string') {
  214. return value.split('\n').join('\n');
  215. }
  216. return '';
  217. }
  218. function projectDisplayCompare(a: Project, b: Project): number {
  219. if (a.isBookmarked !== b.isBookmarked) {
  220. return a.isBookmarked ? -1 : 1;
  221. }
  222. return a.slug.localeCompare(b.slug);
  223. }
  224. // Sort a list of projects by bookmarkedness, then by id
  225. export function sortProjects(projects: Array<Project>): Array<Project> {
  226. return projects.sort(projectDisplayCompare);
  227. }
  228. // build actorIds
  229. export const buildUserId = (id: string) => `user:${id}`;
  230. export const buildTeamId = (id: string) => `team:${id}`;
  231. /**
  232. * Removes the organization / project scope prefix on feature names.
  233. */
  234. export function descopeFeatureName<T>(feature: T): T | string {
  235. if (typeof feature !== 'string') {
  236. return feature;
  237. }
  238. const results = feature.match(/(?:^(?:projects|organizations):)?(.*)/);
  239. if (results && results.length > 0) {
  240. return results.pop()!;
  241. }
  242. return feature;
  243. }
  244. export function isWebpackChunkLoadingError(error: Error): boolean {
  245. return (
  246. error &&
  247. typeof error.message === 'string' &&
  248. error.message.toLowerCase().includes('loading chunk')
  249. );
  250. }
  251. export function deepFreeze<T>(object: T) {
  252. // Retrieve the property names defined on object
  253. const propNames = Object.getOwnPropertyNames(object);
  254. // Freeze properties before freezing self
  255. for (const name of propNames) {
  256. const value = object[name];
  257. object[name] = value && typeof value === 'object' ? deepFreeze(value) : value;
  258. }
  259. return Object.freeze(object);
  260. }
  261. export function generateQueryWithTag(prevQuery: Query, tag: EventTag): Query {
  262. const query = {...prevQuery};
  263. // some tags are dedicated query strings since other parts of the app consumes this,
  264. // for example, the global selection header.
  265. switch (tag.key) {
  266. case 'environment':
  267. query.environment = tag.value;
  268. break;
  269. case 'project':
  270. query.project = tag.value;
  271. break;
  272. default:
  273. query.query = appendTagCondition(query.query, tag.key, tag.value);
  274. }
  275. return query;
  276. }
  277. export const isFunction = (value: any): value is Function => typeof value === 'function';
  278. // NOTE: only escapes a " if it's not already escaped
  279. export function escapeDoubleQuotes(str: string) {
  280. return str.replace(/\\([\s\S])|(")/g, '\\$1$2');
  281. }