1. #!/usr/bin/env node
  2. const { program } = require('commander');
  3. const fs = require('fs');
  4. const path = require('path');
  5. program
  6. .version('1.0.0')
  7. .description('Convert experiment log formats');
  8. program
  9. .command('convert <inputFormat> <outputFormat> <inputFilePath> <outputFilePath>')
  10. .description('Convert log file from one format to another')
  11. .option('-d, --delimiter <delimiter>', 'Delimiter for log entries (default: \\n)')
  12. .action((inputFormat, outputFormat, inputFilePath, outputFilePath, options) => {
  13. const delimiter = options.delimiter || '\n';
  14. try {
  15. const logEntries = fs.readFileSync(inputFilePath, 'utf8').split(delimiter);
  16. let convertedEntries = [];
  17. for (const entry of logEntries) {
  18. // Basic conversion logic - customize as needed
  19. let convertedEntry = entry;
  20. if (inputFormat === 'raw' && outputFormat === 'json') {
  21. try {
  22. const parsed = JSON.parse(entry);
  23. convertedEntry = JSON.stringify(parsed, null, 2); //pretty print
  24. } catch (e) {
  25. console.error(`Error parsing JSON: ${e}`);
  26. convertedEntry = `Error: Invalid JSON - ${entry}`;
  27. }
  28. } else if (inputFormat === 'json' && outputFormat === 'raw') {
  29. try {
  30. const parsed = JSON.parse(entry);
  31. convertedEntry = JSON.stringify(parsed);
  32. } catch (e) {
  33. console.error(`Error parsing JSON: ${e}`);
  34. convertedEntry = `Error: Invalid JSON - ${entry}`;
  35. }
  36. } else if (inputFormat === 'raw' && outputFormat === 'csv') {
  37. // Simple split by comma
  38. convertedEntry = entry.split(',').join(',');
  39. }
  40. //Add more conversion rules as needed
  41. convertedEntries.push(convertedEntry);
  42. }
  43. fs.writeFileSync(outputFilePath, convertedEntries.join(delimiter), 'utf8');
  44. console.log(`Successfully converted ${inputFilePath} to ${outputFilePath}`);
  45. } catch (err) {
  46. console.error(`Error processing files: ${err.message}`);
  47. }
  48. });
  49. program.parse(process.argv);

Add your comment