Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(parsers): add duration parser #698

Merged
merged 1 commit into from
Mar 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
};
Loading