simple-task-master
Version:
A simple command-line task management tool
180 lines • 6.86 kB
JavaScript
;
/**
* Export tasks command
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.exportCommand = void 0;
const commander_1 = require("commander");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const task_manager_1 = require("../lib/task-manager");
const output_1 = require("../lib/output");
const errors_1 = require("../lib/errors");
/**
* Parse tags filter from string
*/
function parseTagsFilter(tagsStr) {
return tagsStr
.split(',')
.map((tag) => tag.trim())
.filter((tag) => tag.length > 0);
}
/**
* Get file extension from format
*/
function getFileExtension(format) {
switch (format) {
case 'json':
return '.json';
case 'csv':
return '.csv';
case 'yaml':
return '.yaml';
case 'ndjson':
return '.ndjson';
default:
return '.txt';
}
}
/**
* Export tasks to a file or stdout
*/
async function exportTasks(options) {
try {
const taskManager = await task_manager_1.TaskManager.create();
// Build filters
const filters = {};
if (options.status) {
if (!['pending', 'in-progress', 'done'].includes(options.status)) {
throw new errors_1.ValidationError('Status must be one of: pending, in-progress, done');
}
filters.status = options.status;
}
if (options.tags) {
filters.tags = parseTagsFilter(options.tags);
}
if (options.search) {
filters.search = options.search;
}
// Get tasks with full content
const allTasks = await taskManager.list(filters);
const tasks = [];
// Load full content for each task
for (const task of allTasks) {
try {
const fullTask = await taskManager.get(task.id);
tasks.push(fullTask);
}
catch (error) {
(0, output_1.printWarning)(`Could not load content for task ${task.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
tasks.push(task); // Include without content
}
}
// Determine output format
let format = 'json'; // default for export
if (options.format) {
const validFormats = ['json', 'csv', 'ndjson', 'yaml', 'table'];
if (!validFormats.includes(options.format)) {
throw new errors_1.ValidationError(`Invalid format: ${options.format}. Valid formats: ${validFormats.join(', ')}`);
}
format = options.format;
}
// Warn if no tasks found
if (tasks.length === 0) {
(0, output_1.printWarning)('No tasks found matching the specified filters');
}
// Format data
const output = (0, output_1.formatTasks)(tasks, format);
// Output to file or stdout
if (options.output) {
// Ensure output directory exists
const outputDir = path.dirname(options.output);
try {
await fs.mkdir(outputDir, { recursive: true });
}
catch {
// Ignore if directory already exists
}
// Auto-append file extension if not present
let outputPath = options.output;
const expectedExt = getFileExtension(format);
if (!outputPath.endsWith(expectedExt)) {
outputPath += expectedExt;
(0, output_1.printWarning)(`Auto-appending ${expectedExt} extension to output file`);
}
await fs.writeFile(outputPath, output, 'utf8');
(0, output_1.printSuccess)(`Exported ${tasks.length} task${tasks.length === 1 ? '' : 's'} to ${outputPath}`);
}
else {
// Output to stdout
process.stdout.write(output);
if (format !== 'csv') {
process.stdout.write('\n');
}
}
}
catch (error) {
if (error instanceof errors_1.ValidationError ||
error instanceof errors_1.FileSystemError ||
error instanceof errors_1.ConfigurationError ||
error instanceof Error) {
(0, output_1.printError)(error.message);
process.exit(1);
}
throw error;
}
}
/**
* Create the export command
*/
exports.exportCommand = new commander_1.Command('export')
.description('Export tasks to a file or stdout')
.option('-f, --format <format>', 'Export format (json, csv, ndjson, yaml, table)', 'json')
.option('-o, --output <file>', 'Output file (default: stdout, auto-appends extension)')
.option('-s, --status <status>', 'Filter by status (pending, in-progress, done)')
.option('-t, --tags <tags>', 'Filter by tags (comma-separated)')
.option('--search <pattern>', 'Filter by search pattern (title and content)')
.addHelpText('after', `
Examples:
stm export # Export all tasks as JSON to stdout
stm export -f csv -o tasks # Export as CSV to tasks.csv
stm export -s done -f yaml # Export completed tasks as YAML
stm export -t urgent,bug -f json # Export urgent and bug tasks as JSON
stm export --search "API" -f csv # Export tasks containing "API" as CSV`)
.action(async (options) => {
await exportTasks(options);
});
//# sourceMappingURL=export.js.map