Skip to content

Commit

Permalink
feat(parsers): add duration parser
Browse files Browse the repository at this point in the history
  • Loading branch information
miton18 committed Mar 5, 2024
1 parent 1b991a2 commit 62d6089
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
22 changes: 22 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
"colors": "1.4.0",
"common-env": "^6.4.0",
"curlconverter": "^3.21.0",
"duration-js": "^4.0.0",
"eventsource": "^1.1.0",
"iso8601-duration": "^2.1.2",
"isomorphic-git": "^1.25.3",
"linux-release-info": "^3.0.0",
"lodash": "^4.17.21",
Expand Down
37 changes: 37 additions & 0 deletions src/parsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
const cliparse = require('cliparse');

const Application = require('./models/application.js');
const ISO8601 = require('iso8601-duration');
const Duration = require('duration-js');

function flavor (flavor) {
const flavors = Application.listAvailableFlavors();
Expand Down Expand Up @@ -143,6 +145,40 @@ function portNumber (number) {
return cliparse.parsers.error(`Invalid port number '${number}'. Should match ${portNumberRegex}`);
}

/**
* Parse a duration into seconds
* A Zero seconds duration is allowed
* @param {string} durationStr an ISO8601, 1h or a positive number
* @returns {number} number of seconds
*/
function durationInSeconds (durationStr = '') {
const failed = cliparse.parsers.error(`Invalid duration: "${durationStr}", expect (IS0 8601 duration / a "1h, 1m, 30s" like duration / a positive number in seconds)`);

if (durationStr.startsWith('P')) {
try {
const d = ISO8601.parse(durationStr);
return cliparse.parsers.success(ISO8601.toSeconds(d));
}
catch (err) {
return failed;
}
}

try {
const duration = Duration.parse(durationStr);
return cliparse.parsers.success(duration.seconds());
}
catch (err) {
const n = Number.parseInt(durationStr);
console.log(`N: ${n}`);
if (isNaN(n) || n < 0) {
return failed;
}

return cliparse.parsers.success(n);
}
}

module.exports = {
buildFlavor,
flavor,
Expand All @@ -162,4 +198,5 @@ module.exports = {
ipAddress,
portNumberRegex,
portNumber,
durationInSeconds,
};

0 comments on commit 62d6089

Please sign in to comment.