From 451dcc70b368a4b4fc26f8c7b9d6577d74d81d19 Mon Sep 17 00:00:00 2001 From: Flavio Wuensche Date: Sat, 2 Dec 2023 16:15:02 +0100 Subject: [PATCH] feat: allow cherry diff to take a json file as input --- bin/cherry.js | 38 ++++++++++++++++++++++++++------------ 1 file changed, 26 insertions(+), 12 deletions(-) diff --git a/bin/cherry.js b/bin/cherry.js index 15db3754..4dcf8a77 100755 --- a/bin/cherry.js +++ b/bin/cherry.js @@ -170,12 +170,14 @@ program program .command('diff') .requiredOption('--metric ', 'Add a metric', (value, previous) => (previous ? [...previous, value] : [value])) + .option('--input-file ', 'A JSON file containing the metrics to compare with') .option('--api-key ', 'Your cherrypush.com API key (available on https://www.cherrypush.com/user/settings)') .option('--error-if-increase', 'Return an error status code (1) if the metric increased since its last report') .action(async (options) => { const configuration = await getConfiguration() const apiKey = options.apiKey || process.env.CHERRY_API_KEY const metrics = options.metric + const inputFile = options.inputFile let lastMetricValue let previousOccurrences @@ -189,21 +191,33 @@ program for (const metric of metrics) { try { console.log('-----------------------------------') - console.log(`Fetching last value for metric ${metric}...`) - const params = { - project_name: configuration.project_name, - metric_name: metric, - api_key: apiKey, + if (inputFile) { + const content = fs.readFileSync(inputFile, 'utf8') + const metrics = JSON.parse(content) + const metricOccurrences = metrics.find((m) => m.name === metric)?.occurrences || [] + lastMetricValue = _.sumBy(metricOccurrences, (occurrence) => + _.isNumber(occurrence.value) ? occurrence.value : 1 + ) + previousOccurrences = metricOccurrences.map((occurrence) => occurrence.text) + } else { + console.log(`Fetching last value for metric ${metric}...`) + const params = { + project_name: configuration.project_name, + metric_name: metric, + api_key: apiKey, + } + + const response = await axios.get(API_BASE_URL + '/metrics', { params }).catch((error) => { + console.error(`Error: ${error.response.status} ${error.response.statusText}`) + console.error(error.response.data.error) + process.exit(1) + }) + + lastMetricValue = response.data.value + previousOccurrences = response.data.occurrences } - const response = await axios.get(API_BASE_URL + '/metrics', { params }).catch((error) => { - console.error(`Error: ${error.response.status} ${error.response.statusText}`) - console.error(error.response.data.error) - process.exit(1) - }) - lastMetricValue = response.data.value - previousOccurrences = response.data.occurrences if (!Number.isInteger(lastMetricValue)) { console.log('No last value found for this metric, aborting.') process.exit(1)