You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

measures.ts 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. import { MetricKey, MetricType } from '../types/metrics';
  21. import {
  22. QualityGateStatusCondition,
  23. QualityGateStatusConditionEnhanced,
  24. } from '../types/quality-gates';
  25. import { Dict, Measure, MeasureEnhanced, Metric } from '../types/types';
  26. import {
  27. CCT_SOFTWARE_QUALITY_METRICS,
  28. LEAK_CCT_SOFTWARE_QUALITY_METRICS,
  29. LEAK_OLD_TAXONOMY_METRICS,
  30. ONE_SECOND,
  31. } from './constants';
  32. import { translate, translateWithParameters } from './l10n';
  33. import { getCurrentLocale } from './l10nBundle';
  34. import { isDefined } from './types';
  35. export const MEASURES_REDIRECTION: Partial<Record<MetricKey, MetricKey>> = {
  36. [MetricKey.wont_fix_issues]: MetricKey.accepted_issues,
  37. [MetricKey.open_issues]: MetricKey.violations,
  38. [MetricKey.reopened_issues]: MetricKey.violations,
  39. };
  40. export function enhanceMeasuresWithMetrics(
  41. measures: Measure[],
  42. metrics: Metric[],
  43. ): MeasureEnhanced[] {
  44. return measures
  45. .map((measure) => {
  46. const metric = metrics.find((metric) => metric.key === measure.metric);
  47. return metric && { ...measure, metric };
  48. })
  49. .filter(isDefined);
  50. }
  51. export function enhanceConditionWithMeasure(
  52. condition: QualityGateStatusCondition,
  53. measures: MeasureEnhanced[],
  54. ): QualityGateStatusConditionEnhanced | undefined {
  55. const measure = measures.find((m) => m.metric.key === condition.metric);
  56. // Make sure we have a period index. This is necessary when dealing with
  57. // applications.
  58. let { period } = condition;
  59. if (measure?.period && !period) {
  60. period = measure.period.index;
  61. }
  62. return measure && { ...condition, period, measure };
  63. }
  64. export function isPeriodBestValue(measure: Measure | MeasureEnhanced): boolean {
  65. return measure.period?.bestValue ?? false;
  66. }
  67. /** Check if metric is differential */
  68. export function isDiffMetric(metricKey: MetricKey | string): boolean {
  69. return metricKey.startsWith('new_');
  70. }
  71. export function getDisplayMetrics(metrics: Metric[]) {
  72. return metrics.filter(
  73. (metric) =>
  74. !metric.hidden &&
  75. ([...CCT_SOFTWARE_QUALITY_METRICS, ...LEAK_CCT_SOFTWARE_QUALITY_METRICS].includes(
  76. metric.key as MetricKey,
  77. ) ||
  78. ![MetricType.Data, MetricType.Distribution].includes(metric.type as MetricType)),
  79. );
  80. }
  81. export function findMeasure(measures: MeasureEnhanced[], metric: MetricKey | string) {
  82. return measures.find((measure) => measure.metric.key === metric);
  83. }
  84. export function areLeakCCTMeasuresComputed(measures?: Measure[] | MeasureEnhanced[]) {
  85. if (
  86. LEAK_OLD_TAXONOMY_METRICS.every(
  87. (metric) =>
  88. !measures?.find((measure) =>
  89. isMeasureEnhanced(measure) ? measure.metric.key === metric : measure.metric === metric,
  90. ),
  91. )
  92. ) {
  93. return true;
  94. }
  95. return LEAK_CCT_SOFTWARE_QUALITY_METRICS.every((metric) =>
  96. measures?.find((measure) =>
  97. isMeasureEnhanced(measure) ? measure.metric.key === metric : measure.metric === metric,
  98. ),
  99. );
  100. }
  101. export function areCCTMeasuresComputed(measures?: Measure[] | MeasureEnhanced[]) {
  102. return CCT_SOFTWARE_QUALITY_METRICS.every((metric) =>
  103. measures?.find((measure) =>
  104. isMeasureEnhanced(measure) ? measure.metric.key === metric : measure.metric === metric,
  105. ),
  106. );
  107. }
  108. export function areLeakAndOverallCCTMeasuresComputed(measures?: Measure[] | MeasureEnhanced[]) {
  109. return areLeakCCTMeasuresComputed(measures) && areCCTMeasuresComputed(measures);
  110. }
  111. function isMeasureEnhanced(measure: Measure | MeasureEnhanced): measure is MeasureEnhanced {
  112. return (measure.metric as Metric)?.key !== undefined;
  113. }
  114. export const getCCTMeasureValue = (key: string, value?: string) => {
  115. if (
  116. CCT_SOFTWARE_QUALITY_METRICS.concat(LEAK_CCT_SOFTWARE_QUALITY_METRICS).includes(
  117. key as MetricKey,
  118. ) &&
  119. value !== undefined
  120. ) {
  121. return JSON.parse(value).total;
  122. }
  123. return value;
  124. };
  125. const HOURS_IN_DAY = 8;
  126. type Formatter = (value: string | number, options?: Dict<unknown>) => string;
  127. /**
  128. * Format a measure value for a given type
  129. * ! For Ratings, use formatRating instead
  130. */
  131. export function formatMeasure(
  132. value: string | number | undefined,
  133. type: string,
  134. options?: Dict<unknown>,
  135. ): string {
  136. const formatter = getFormatter(type);
  137. // eslint-disable-next-line react-hooks/rules-of-hooks
  138. return useFormatter(value, formatter, options);
  139. }
  140. type RatingValue = 'A' | 'B' | 'C' | 'D' | 'E';
  141. const RATING_VALUES: RatingValue[] = ['A', 'B', 'C', 'D', 'E'];
  142. export function formatRating(value: string | number | undefined): RatingValue | undefined {
  143. if (!value) {
  144. return undefined;
  145. }
  146. if (typeof value === 'string') {
  147. value = parseInt(value, 10);
  148. }
  149. // rating is 1-5, adjust for 0-based indexing
  150. return RATING_VALUES[value - 1];
  151. }
  152. /** Return a localized metric name */
  153. export function localizeMetric(metricKey: string): string {
  154. return translate('metric', metricKey, 'name');
  155. }
  156. /** Return corresponding "short" for better display in UI */
  157. export function getShortType(type: string): string {
  158. if (type === MetricType.Integer) {
  159. return MetricType.ShortInteger;
  160. } else if (type === 'WORK_DUR') {
  161. return MetricType.ShortWorkDuration;
  162. }
  163. return type;
  164. }
  165. function useFormatter(
  166. value: string | number | undefined,
  167. formatter: Formatter,
  168. options?: Dict<unknown>,
  169. ): string {
  170. return value !== undefined && value !== '' ? formatter(value, options) : '';
  171. }
  172. function getFormatter(type: string): Formatter {
  173. const FORMATTERS: Dict<Formatter> = {
  174. INT: intFormatter,
  175. SHORT_INT: shortIntFormatter,
  176. FLOAT: floatFormatter,
  177. PERCENT: percentFormatter,
  178. WORK_DUR: durationFormatter,
  179. SHORT_WORK_DUR: shortDurationFormatter,
  180. RATING: ratingFormatter,
  181. LEVEL: levelFormatter,
  182. MILLISEC: millisecondsFormatter,
  183. };
  184. return FORMATTERS[type] || noFormatter;
  185. }
  186. function numberFormatter(
  187. value: string | number,
  188. minimumFractionDigits = 0,
  189. maximumFractionDigits = minimumFractionDigits,
  190. ) {
  191. const { format } = new Intl.NumberFormat(getCurrentLocale(), {
  192. minimumFractionDigits,
  193. maximumFractionDigits,
  194. });
  195. if (typeof value === 'string') {
  196. return format(parseFloat(value));
  197. }
  198. return format(value);
  199. }
  200. function noFormatter(value: string | number): string | number {
  201. return value;
  202. }
  203. function intFormatter(value: string | number): string {
  204. return numberFormatter(value);
  205. }
  206. const shortIntFormats = [
  207. { unit: 1e10, formatUnit: 1e9, fraction: 0, suffix: 'short_number_suffix.g' },
  208. { unit: 1e9, formatUnit: 1e9, fraction: 1, suffix: 'short_number_suffix.g' },
  209. { unit: 1e7, formatUnit: 1e6, fraction: 0, suffix: 'short_number_suffix.m' },
  210. { unit: 1e6, formatUnit: 1e6, fraction: 1, suffix: 'short_number_suffix.m' },
  211. { unit: 1e4, formatUnit: 1e3, fraction: 0, suffix: 'short_number_suffix.k' },
  212. { unit: 1e3, formatUnit: 1e3, fraction: 1, suffix: 'short_number_suffix.k' },
  213. ];
  214. function shortIntFormatter(
  215. value: string | number,
  216. option?: { roundingFunc?: (x: number) => number },
  217. ): string {
  218. const roundingFunc = option?.roundingFunc;
  219. if (typeof value === 'string') {
  220. value = parseFloat(value);
  221. }
  222. for (let i = 0; i < shortIntFormats.length; i++) {
  223. const { unit, formatUnit, fraction, suffix } = shortIntFormats[i];
  224. const nextFraction = unit / (shortIntFormats[i + 1] ? shortIntFormats[i + 1].unit / 10 : 1);
  225. const roundedValue = numberRound(value / unit, nextFraction, roundingFunc);
  226. if (roundedValue >= 1) {
  227. return (
  228. numberFormatter(
  229. numberRound(value / formatUnit, Math.pow(10, fraction), roundingFunc),
  230. 0,
  231. fraction,
  232. ) + translate(suffix)
  233. );
  234. }
  235. }
  236. return numberFormatter(value);
  237. }
  238. function numberRound(
  239. value: number,
  240. fraction: number = 1000,
  241. roundingFunc: (x: number) => number = Math.round,
  242. ) {
  243. return roundingFunc(value * fraction) / fraction;
  244. }
  245. function floatFormatter(value: string | number): string {
  246. return numberFormatter(value, 1, 5);
  247. }
  248. function percentFormatter(
  249. value: string | number,
  250. { decimals, omitExtraDecimalZeros }: { decimals?: number; omitExtraDecimalZeros?: boolean } = {},
  251. ): string {
  252. if (typeof value === 'string') {
  253. value = parseFloat(value);
  254. }
  255. if (value === 100) {
  256. return '100%';
  257. } else if (omitExtraDecimalZeros && decimals) {
  258. // If omitExtraDecimalZeros is true, all trailing decimal 0s will be removed,
  259. // except for the first decimal.
  260. // E.g. for decimals=3:
  261. // - omitExtraDecimalZeros: false, value: 45.450 => 45.450
  262. // - omitExtraDecimalZeros: true, value: 45.450 => 45.45
  263. // - omitExtraDecimalZeros: false, value: 85 => 85.000
  264. // - omitExtraDecimalZeros: true, value: 85 => 85.0
  265. return `${numberFormatter(value, 1, decimals)}%`;
  266. }
  267. return `${numberFormatter(value, decimals || 1)}%`;
  268. }
  269. function ratingFormatter(value: string | number): string {
  270. if (typeof value === 'string') {
  271. value = parseInt(value, 10);
  272. }
  273. return String.fromCharCode(97 + value - 1).toUpperCase();
  274. }
  275. function levelFormatter(value: string | number): string {
  276. if (typeof value === 'number') {
  277. value = value.toString();
  278. }
  279. const l10nKey = `metric.level.${value}`;
  280. const result = translate(l10nKey);
  281. // if couldn't translate, return the initial value
  282. return l10nKey !== result ? result : value;
  283. }
  284. function millisecondsFormatter(value: string | number): string {
  285. if (typeof value === 'string') {
  286. value = parseInt(value, 10);
  287. }
  288. const ONE_MINUTE = 60 * ONE_SECOND;
  289. if (value >= ONE_MINUTE) {
  290. const minutes = Math.round(value / ONE_MINUTE);
  291. return `${minutes}min`;
  292. } else if (value >= ONE_SECOND) {
  293. const seconds = Math.round(value / ONE_SECOND);
  294. return `${seconds}s`;
  295. }
  296. return `${value}ms`;
  297. }
  298. /*
  299. * Debt Formatters
  300. */
  301. function shouldDisplayDays(days: number): boolean {
  302. return days > 0;
  303. }
  304. function shouldDisplayDaysInShortFormat(days: number): boolean {
  305. return days > 0.9;
  306. }
  307. function shouldDisplayHours(days: number, hours: number): boolean {
  308. return hours > 0 && days < 10;
  309. }
  310. function shouldDisplayHoursInShortFormat(hours: number): boolean {
  311. return hours > 0.9;
  312. }
  313. function shouldDisplayMinutes(days: number, hours: number, minutes: number): boolean {
  314. return minutes > 0 && hours < 10 && days === 0;
  315. }
  316. function addSpaceIfNeeded(value: string): string {
  317. return value.length > 0 ? `${value} ` : value;
  318. }
  319. function formatDuration(isNegative: boolean, days: number, hours: number, minutes: number): string {
  320. let formatted = '';
  321. if (shouldDisplayDays(days)) {
  322. formatted += translateWithParameters('work_duration.x_days', isNegative ? -1 * days : days);
  323. }
  324. if (shouldDisplayHours(days, hours)) {
  325. formatted = addSpaceIfNeeded(formatted);
  326. formatted += translateWithParameters(
  327. 'work_duration.x_hours',
  328. isNegative && formatted.length === 0 ? -1 * hours : hours,
  329. );
  330. }
  331. if (shouldDisplayMinutes(days, hours, minutes)) {
  332. formatted = addSpaceIfNeeded(formatted);
  333. formatted += translateWithParameters(
  334. 'work_duration.x_minutes',
  335. isNegative && formatted.length === 0 ? -1 * minutes : minutes,
  336. );
  337. }
  338. return formatted;
  339. }
  340. function formatDurationShort(
  341. isNegative: boolean,
  342. days: number,
  343. hours: number,
  344. minutes: number,
  345. ): string {
  346. if (shouldDisplayDaysInShortFormat(days)) {
  347. const roundedDays = Math.round(days);
  348. const formattedDays = formatMeasure(
  349. isNegative ? -1 * roundedDays : roundedDays,
  350. MetricType.ShortInteger,
  351. );
  352. return translateWithParameters('work_duration.x_days', formattedDays);
  353. }
  354. if (shouldDisplayHoursInShortFormat(hours)) {
  355. const roundedHours = Math.round(hours);
  356. const formattedHours = formatMeasure(
  357. isNegative ? -1 * roundedHours : roundedHours,
  358. MetricType.ShortInteger,
  359. );
  360. return translateWithParameters('work_duration.x_hours', formattedHours);
  361. }
  362. const formattedMinutes = formatMeasure(
  363. isNegative ? -1 * minutes : minutes,
  364. MetricType.ShortInteger,
  365. );
  366. return translateWithParameters('work_duration.x_minutes', formattedMinutes);
  367. }
  368. function durationFormatter(value: string | number): string {
  369. if (typeof value === 'string') {
  370. value = parseInt(value, 10);
  371. }
  372. if (value === 0) {
  373. return '0';
  374. }
  375. const hoursInDay = HOURS_IN_DAY;
  376. const isNegative = value < 0;
  377. const absValue = Math.abs(value);
  378. const days = Math.floor(absValue / hoursInDay / 60);
  379. let remainingValue = absValue - days * hoursInDay * 60;
  380. const hours = Math.floor(remainingValue / 60);
  381. remainingValue -= hours * 60;
  382. return formatDuration(isNegative, days, hours, remainingValue);
  383. }
  384. function shortDurationFormatter(value: string | number): string {
  385. if (typeof value === 'string') {
  386. value = parseInt(value, 10);
  387. }
  388. if (value === 0) {
  389. return '0';
  390. }
  391. const hoursInDay = HOURS_IN_DAY;
  392. const isNegative = value < 0;
  393. const absValue = Math.abs(value);
  394. const days = absValue / hoursInDay / 60;
  395. let remainingValue = absValue - Math.floor(days) * hoursInDay * 60;
  396. const hours = remainingValue / 60;
  397. remainingValue -= Math.floor(hours) * 60;
  398. return formatDurationShort(isNegative, days, hours, remainingValue);
  399. }