All files / kanbn/src/controller add.js

93.06% Statements 510/548
87.39% Branches 104/119
94.73% Functions 18/19
93.06% Lines 510/548

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 54917x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 14x 14x 14x 14x   14x 14x 14x 14x   14x 14x 14x 14x   14x 14x 14x 14x   14x 14x 14x 14x 14x 14x 14x 14x 13x 1x 1x 12x 13x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 3x 1x 1x 2x 3x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 3x 1x 1x 2x 3x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x             14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 17x 17x 17x 17x 17x 17x 17x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 17x 17x 17x 17x 17x 17x 23x 23x 23x 23x 23x 23x 23x   23x 23x 17x 17x 17x 17x 17x 17x 3x 3x 4x 4x 4x       4x 3x 3x 3x 3x 17x 17x 41x 41x 41x 1x 1x 1x 40x 40x 40x 40x 40x 41x       40x 41x 1x 1x 1x 39x 39x 39x 41x 3x 3x 1x 1x 1x 3x 38x 38x 41x 4x 4x   4x 1x 4x 3x 3x 3x       3x 4x 4x 4x 1x 1x 1x 3x 3x 4x 1x 1x 1x 1x 1x   1x 1x 4x 2x 2x 2x 4x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 34x 41x 20x 20x 34x 34x 41x 1x 1x 34x 34x 41x 2x 2x 1x 1x 1x 2x 33x 33x 41x 2x 2x 1x 1x 1x 2x 32x 32x 41x 2x 2x 1x 1x 1x 2x 31x 31x 41x 2x 2x 1x 1x 1x 1x 1x 30x 30x 41x                   30x 30x 41x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 41x 1x 1x 30x 30x 41x 3x 3x 3x 3x 2x 2x 2x 3x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 2x 2x 29x 29x 41x 6x 36x 36x 6x 6x 6x 6x 2x 1x 1x 1x 1x 1x 1x 6x 2x 2x 1x 1x 1x 1x 1x 1x 6x               6x 2x 2x 1x 1x 1x 1x 1x 1x 6x 6x 3x 36x 3x 26x 26x 41x 14x 14x 11x 11x 1x 1x 11x 2x 2x 11x 1x 1x 11x 1x 1x 11x 1x 1x 11x 11x 2x 2x 11x 11x 11x 1x 1x 11x 10x 1x 1x 10x 10x 11x 11x 14x 14x 3x 14x 14x 14x 41x 12x 12x 17x  
const kanbn = require('../main');
const utility = require('../utility');
const inquirer = require('inquirer');
const fuzzy = require('fuzzy');
const chrono = require('chrono-node');
const getGitUsername = require('git-user-name');
 
inquirer.registerPrompt('datepicker', require('inquirer-datepicker'));
inquirer.registerPrompt('recursive', require('inquirer-recursive'));
inquirer.registerPrompt('autocomplete', require('inquirer-autocomplete-prompt'));
 
/**
 * Create a task interactively
 * @param {object} taskData
 * @param {string[]} taskIds
 * @param {string} columnName
 * @param {string[]} columnNames
 * @return {Promise<any>}
 */
async function interactiveCreateTask(taskData, taskIds, columnName, columnNames) {
  const dueDateExists = (
    'metadata' in taskData &&
    'due' in taskData.metadata &&
    taskData.metadata.due != null
  );
  const plannedStartDateExists = (
    'metadata' in taskData &&
    'plannedStart' in taskData.metadata &&
    taskData.metadata.plannedStart != null
  );
  const plannedFinishDateExists = (
    'metadata' in taskData &&
    'plannedFinish' in taskData.metadata &&
    taskData.metadata.plannedFinish != null
  );
  const assignedExists = (
    'metadata' in taskData &&
    'assigned' in taskData.metadata &&
    taskData.metadata.assigned != null
  );
  return await inquirer.prompt([
    {
      type: 'input',
      name: 'name',
      message: 'Task name:',
      default: taskData.name || '',
      validate: async value => {
        if (!value) {
          return 'Task name cannot be empty';
        }
        return true;
      }
    },
    {
      type: 'confirm',
      name: 'setDescription',
      message: 'Add a description?',
      default: false
    },
    {
      type: 'editor',
      name: 'description',
      message: 'Task description:',
      default: taskData.description,
      when: answers => answers.setDescription
    },
    {
      type: 'list',
      name: 'column',
      message: 'Column:',
      default: columnName,
      choices: columnNames
    },
    {
      type: 'confirm',
      name: 'setDue',
      message: 'Set a due date?',
      default: false,
      when: answers => !dueDateExists
    },
    {
      type: 'datepicker',
      name: 'due',
      message: 'Due date:',
      default: dueDateExists ? taskData.metadata.due : new Date(),
      format: ['Y', '/', 'MM', '/', 'DD'],
      when: answers => answers.setDue,
    },
    {
      type: 'confirm',
      name: 'setPlannedStart',
      message: 'Set a planned start date?',
      default: false,
      when: answers => !plannedStartDateExists
    },
    {
      type: 'datepicker',
      name: 'plannedStart',
      message: 'Planned start date:',
      default: plannedStartDateExists ? taskData.metadata.plannedStart : new Date(),
      format: ['Y', '/', 'MM', '/', 'DD'],
      when: answers => answers.setPlannedStart,
    },
    {
      type: 'confirm',
      name: 'setPlannedFinish',
      message: 'Set a planned finish date?',
      default: false,
      when: answers => !plannedFinishDateExists
    },
    {
      type: 'datepicker',
      name: 'plannedFinish',
      message: 'Planned finish date:',
      default: plannedFinishDateExists ? taskData.metadata.plannedFinish : new Date(),
      format: ['Y', '/', 'MM', '/', 'DD'],
      when: answers => answers.setPlannedFinish,
    },
    {
      type: 'confirm',
      name: 'setAssigned',
      message: 'Assign this task?',
      default: false,
      when: answers => !assignedExists
    },
    {
      type: 'input',
      name: 'assigned',
      message: 'Assigned to:',
      default: assignedExists ? taskData.metadata.assigned : getGitUsername(),
      when: answers => answers.setAssigned || assignedExists
    },
    {
      type: 'recursive',
      name: 'subTasks',
      initialMessage: 'Add a sub-task?',
      message: 'Add another sub-task?',
      default: false,
      prompts: [
        {
          type: 'input',
          name: 'text',
          message: 'Sub-task text:',
          validate: value => {
            if (!value) {
              return 'Sub-task text cannot be empty';
            }
            return true;
          }
        },
        {
          type: 'confirm',
          name: 'completed',
          message: 'Sub-task completed?',
          default: false
        }
      ]
    },
    {
      type: 'recursive',
      name: 'tags',
      initialMessage: 'Add a tag?',
      message: 'Add another tag?',
      default: false,
      prompts: [
        {
          type: 'input',
          name: 'name',
          message: 'Tag name:',
          validate: value => {
            if (!value) {
              return 'Tag name cannot be empty';
            }
            return true;
          }
        }
      ]
    },
    {
      type: 'recursive',
      name: 'relations',
      initialMessage: 'Add a relation?',
      message: 'Add another relation?',
      default: false,
      when: answers => taskIds.length > 0,
      prompts: [
        {
          type: 'autocomplete',
          name: 'task',
          message: 'Related task id:',
          source: (answers, input) => {
            input = input || '';
            const result = fuzzy.filter(input, taskIds);
            return new Promise(resolve => {
              resolve(result.map(result => result.string));
            });
          }
        },
        {
          type: 'input',
          name: 'type',
          message: 'Relation type:'
        }
      ]
    }
  ]);
}
 
/**
 * Add untracked tasks interactively
 * @param {string[]} untrackedTasks
 * @param {string} columnName
 * @param {string[]} columnNames
 */
async function interactiveAddUntrackedTasks(untrackedTasks, columnName, columnNames) {
  return await inquirer.prompt([
    {
      type: 'checkbox',
      name: 'untrackedTasks',
      message: 'Choose which tasks to add:',
      choices: untrackedTasks
    },
    {
      type: 'list',
      name: 'column',
      message: 'Column:',
      default: columnName,
      choices: columnNames
    }
  ]);
}
 
/**
 * Create a task
 * @param {object} taskData
 * @param {string} columnName
 */
function createTask(taskData, columnName) {
  kanbn
  .createTask(taskData, columnName)
  .then(taskId => {
    console.log(`Created task "${taskId}" in column "${columnName}"`);
  })
  .catch(error => {
    utility.error(error);
  });
}
 
/**
 * Add untracked tasks to the index
 * @param {string[]} untrackedTasks
 * @param {string} columnName
 */
async function addUntrackedTasks(untrackedTasks, columnName) {
  for (let untrackedTask of untrackedTasks) {
    try {
      await kanbn.addUntrackedTaskToIndex(untrackedTask, columnName);
    } catch (error) {
      utility.error(error);
      return;
    }
  }
  console.log(
    `Added ${untrackedTasks.length} task${untrackedTasks.length !== 1 ? 's' : ''} to column "${columnName}"`
  );
}
 
module.exports = async args => {
 
  // Make sure kanbn has been initialised
  if (!await kanbn.initialised()) {
    utility.error('Kanbn has not been initialised in this folder\nTry running: {b}kanbn init{b}');
    return;
  }
 
  // Get the index and make sure it has some columns
  let index;
  try {
    index = await kanbn.getIndex();
  } catch (error) {
    utility.error(error);
    return;
  }
  const columnNames = Object.keys(index.columns);
  if (!columnNames.length) {
    utility.error('No columns defined in the index\nTry running {b}kanbn init -c "column name"{b}');
    return;
  }
 
  // Get column name if specified, otherwise default to the first available column
  let columnName = columnNames[0];
  if (args.column) {
    columnName = utility.strArg(args.column);
    if (columnNames.indexOf(columnName) === -1) {
      utility.error(`Column "${columnName}" doesn't exist`);
      return;
    }
  }
 
  // Add untracked file(s)
  if (args.untracked) {
    const untrackedTasks = [];
    if (Array.isArray(args.untracked)) {
      untrackedTasks.push(...args.untracked);
    } else if (typeof args.untracked === 'string') {
      untrackedTasks.push(args.untracked);
    } else if (args.untracked === true) {
      try {
        untrackedTasks.push(...await kanbn.findUntrackedTasks());
      } catch (error) {
        utility.error(error);
        return;
      }
    }
 
    // Make sure there are some untracked tasks to add
    if (untrackedTasks.length === 0) {
      utility.error('No untracked tasks to add');
      return;
    }
 
    // Add untracked files interactively
    if (args.interactive) {
      interactiveAddUntrackedTasks(untrackedTasks, columnName, columnNames)
      .then(async answers => {
        await addUntrackedTasks(answers.untrackedTasks, answers.column);
      })
      .catch(error => {
        utility.error(error);
      });
      return;
    } else {
      await addUntrackedTasks(untrackedTasks, columnName);
      return;
    }
  }
 
  // Otherwise, create a task from arguments or interactively
  const taskData = {
    metadata: {}
  };
 
  // Get a list of existing task ids
  const taskIds = [...await kanbn.findTrackedTasks()];
 
  // Get task settings from arguments
  // Name
  if (args.name) {
    taskData.name = utility.strArg(args.name);
  }
 
  // Description
  if (args.description) {
    taskData.description = utility.strArg(args.description);
  }
 
  // Due date
  if (args.due) {
    taskData.metadata.due = chrono.parseDate(utility.strArg(args.due));
    if (taskData.metadata.due === null) {
      utility.error('Unable to parse due date');
      return;
    }
  }
 
  // Planned start date
  if (args.plannedStart) {
    taskData.metadata.plannedStart = chrono.parseDate(utility.strArg(args.plannedStart));
    if (taskData.metadata.plannedStart === null) {
      utility.error('Unable to parse plannedStart date');
      return;
    }
  }
 
  // Planned finish date
  if (args.plannedFinish) {
    taskData.metadata.plannedFinish = chrono.parseDate(utility.strArg(args.plannedFinish));
    if (taskData.metadata.plannedFinish === null) {
      utility.error('Unable to parse plannedFinish date');
      return;
    }
  }
 
  // Progress
  if (args.progress) {
    const progressValue = parseFloat(utility.strArg(args.progress));
    if (isNaN(progressValue)) {
      utility.error('Progress value is not a number');
      return;
    }
    taskData.metadata.progress = progressValue;
  }
 
  // Assigned
  if (args.assigned) {
    const gitUsername = getGitUsername();
    if (args.assigned === true) {
      if (gitUsername) {
        taskData.metadata.assigned = gitUsername;
      }
    } else {
      taskData.metadata.assigned = utility.strArg(args.assigned);
    }
  }
 
  // Sub-tasks
  if (args['sub-task']) {
    const subTasks = utility.arrayArg(args['sub-task']);
    taskData.subTasks = subTasks.map(subTask => {
      const match = subTask.match(/^\[([x ])\] (.*)/);
      if (match !== null) {
        return {
          completed: match[1] === 'x',
          text: match[2]
        };
      }
      return {
        completed: false,
        text: subTask
      };
    });
  }
 
  // Tags
  if (args.tag) {
    taskData.metadata.tags = utility.arrayArg(args.tag);
  }
 
  // Relations
  if (args.relation) {
    const relations = utility.arrayArg(args.relation).map(relation => {
      const parts = relation.split(':');
      return parts.length === 1
        ? {
          type: '',
          task: parts[0].trim()
        }
        : {
          type: parts[0].trim(),
          task: parts[1].trim()
        };
    });
 
    // Make sure each relation is an existing task
    for (let relation of relations) {
      if (taskIds.indexOf(relation.task) === -1) {
        utility.error(`Related task ${relation.task} doesn't exist`);
        return;
      }
    }
    taskData.relations = relations;
  }
 
  // Check metadata field types
  if ('customFields' in index.options) {
    for (let arg of Object.keys(args)) {
      const customField = index.options.customFields.find(p => p.name === arg);
      if (customField !== undefined) {
 
        // Check value type
        switch (customField.type) {
          case 'boolean':
            if (typeof args[arg] === 'boolean') {
              taskData.metadata[arg] = args[arg];
            } else {
              utility.error(`Custom field "${arg}" value is not a boolean`);
              return;
            }
            break;
          case 'number':
            const numberValue = parseFloat(args[arg]);
            if (!isNaN(numberValue)) {
              taskData.metadata[arg] = numberValue;
            } else {
              utility.error(`Custom field "${arg}" value is not a number`);
              return;
            }
            break;
          case 'string':
            if (typeof args[arg] === 'string') {
              taskData.metadata[arg] = args[arg];
            } else {
              utility.error(`Custom field "${arg}" value is not a string`);
              return;
            }
            break;
          case 'date':
            const dateValue = chrono.parseDate(args[arg]);
            if (dateValue instanceof Date) {
              taskData.metadata[arg] = dateValue;
            } else {
              utility.error(`Unable to parse date for custom field "${arg}"`);
              return;
            }
            break;
          default: break;
        }
      }
    }
  }
 
  // Create task interactively
  if (args.interactive) {
    interactiveCreateTask(taskData, taskIds, columnName, columnNames)
    .then(answers => {
      taskData.name = answers.name;
      if ('description' in answers) {
        taskData.description = answers.description;
      }
      if ('due' in answers) {
        taskData.metadata.due = answers.due;
      }
      if ('plannedStart' in answers) {
        taskData.metadata.plannedStart = answers.plannedStart;
      }
      if ('plannedFinish' in answers) {
        taskData.metadata.plannedFinish = answers.plannedFinish;
      }
      if ('assigned' in answers) {
        taskData.metadata.assigned = answers.assigned;
      }
      if ('subTasks' in answers) {
        taskData.subTasks = answers.subTasks.map(subTask => ({
          text: subTask.text,
          completed: subTask.completed
        }));
      }
      if ('tags' in answers && answers.tags.length > 0) {
        taskData.metadata.tags = answers.tags.map(tag => tag.name);
      }
      if ('relations' in answers) {
        taskData.relations = answers.relations.map(relation => ({
          task: relation.task,
          type: relation.type
        }));
      }
      columnName = answers.column;
      createTask(taskData, columnName);
    })
    .catch(error => {
      utility.error(error);
    });
 
  // Otherwise create task non-interactively
  } else {
    createTask(taskData, columnName);
  }
};