All files / kanbn/src/controller edit.js

89.41% Statements 845/945
83.15% Branches 153/184
92.85% Functions 26/28
89.41% Lines 845/945

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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 94624x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 22x 22x 22x 22x 20x 22x 22x 22x 22x   22x 22x 22x 22x   22x 22x 22x 22x 21x 22x 22x 22x 22x 22x 22x 22x 22x 22x 1x 1x 21x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 3x 1x 1x 2x 3x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 1x     1x 1x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 20x 20x 19x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x             22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 36x 36x 36x 36x 36x 36x 36x   36x 36x 24x 24x 51x 51x 51x 1x 1x 1x 50x 50x 50x 51x 1x 1x 1x 49x 49x 49x 49x 51x 1x 1x 1x 48x 48x 48x 48x 48x 51x       48x 51x 1x 1x 1x 47x 47x 47x 47x 47x 51x       47x 47x 47x 47x 51x 3x 3x 1x 1x 1x 3x 46x 46x 46x 46x 46x 46x 51x 1x 1x 46x 46x 51x 1x 1x 46x 46x 51x 3x     3x 3x 1x 1x 1x 3x 45x 45x 51x                   45x 45x 51x                   45x 45x 51x 2x     2x 2x 1x 1x 1x 1x 1x 44x 44x 51x                         44x 44x 51x 2x 2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 43x 43x 51x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 43x 43x 51x 2x 2x 2x 2x       2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 42x 42x 51x 1x 1x 1x 42x 42x 51x 2x 2x 2x 2x 2x 1x 1x 1x 2x 1x 1x 41x 41x 51x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 41x 41x 51x 3x     3x 12x 12x 12x 12x         12x 12x 12x 12x 2x 2x 2x 2x               2x 2x 2x 1x 1x 1x 1x 1x 1x 2x               2x                 2x 2x 1x 12x 2x 40x 40x 40x 51x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 1x 1x 1x 1x 1x 7x 1x 1x 1x 5x 5x 5x 7x 4x 38x 38x 51x 22x 22x 20x 20x 20x 20x 20x 20x 1x 1x 20x 20x 20x 1x 1x 20x 20x 20x 2x 2x 20x 20x 20x     20x 20x 20x     20x 20x 20x     20x 20x 20x     20x 20x 20x 1x 1x 20x 20x 20x 1x 1x 20x 20x 20x 19x 3x 3x 3x 3x 1x 1x 3x 1x 1x 3x 1x 3x 3x 3x 19x 20x 20x 20x 20x 2x 2x 20x 20x 20x 20x 20x 19x 1x 1x 1x 1x 1x 19x 20x 20x 20x 19x 19x 20x 20x 20x 19x 3x 3x 3x 3x 1x 1x 3x 2x 2x 3x   3x 3x 3x 19x 20x 20x 20x 20x 1x 1x 20x 20x 20x 20x 20x 20x 22x 22x 2x 22x 22x 22x 51x 16x 16x 16x 24x  
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'));
 
/**
 * Update a task interactively
 * @param {object} taskData
 * @param {string[]} taskIds
 * @param {string} columnName
 * @param {string[]} columnNames
 * @return {Promise<any>}
 */
async function interactive(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: 'editDescription',
      message: 'Edit description?',
      default: false
    },
    {
      type: 'editor',
      name: 'description',
      message: 'Task description:',
      default: taskData.description,
      when: answers => answers.editDescription
    },
    {
      type: 'list',
      name: 'column',
      message: 'Column:',
      default: columnName,
      choices: columnNames
    },
    {
      type: 'expand',
      name: 'editDue',
      message: 'Edit or remove due date?',
      default: 'none',
      when: answers => dueDateExists,
      choices: [
        {
          key: 'e',
          name: 'Edit',
          value: 'edit'
        },
        {
          key: 'r',
          name: 'Remove',
          value: 'remove'
        },
        new inquirer.Separator(),
        {
          key: 'n',
          name: 'Do nothing',
          value: 'none'
        }
      ]
    },
    {
      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 || answers.editDue === 'edit'
    },
    {
      type: 'expand',
      name: 'editPlannedStart',
      message: 'Edit or remove planned start date?',
      default: 'none',
      when: answers => plannedStartDateExists,
      choices: [
        {
          key: 'e',
          name: 'Edit',
          value: 'edit'
        },
        {
          key: 'r',
          name: 'Remove',
          value: 'remove'
        },
        new inquirer.Separator(),
        {
          key: 'n',
          name: 'Do nothing',
          value: 'none'
        }
      ]
    },
    {
      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 || answers.editPlannedStart === 'edit'
    },
    {
      type: 'expand',
      name: 'editPlannedFinish',
      message: 'Edit or remove planned finish date?',
      default: 'none',
      when: answers => plannedFinishDateExists,
      choices: [
        {
          key: 'e',
          name: 'Edit',
          value: 'edit'
        },
        {
          key: 'r',
          name: 'Remove',
          value: 'remove'
        },
        new inquirer.Separator(),
        {
          key: 'n',
          name: 'Do nothing',
          value: 'none'
        }
      ]
    },
    {
      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 || answers.editPlannedFinish === 'edit'
    },
    {
      type: 'expand',
      name: 'editAssigned',
      message: 'Edit or remove assigned user?',
      default: 'none',
      when: answers => assignedExists,
      choices: [
        {
          key: 'e',
          name: 'Edit',
          value: 'edit'
        },
        {
          key: 'r',
          name: 'Remove',
          value: 'remove'
        },
        new inquirer.Separator(),
        {
          key: 'n',
          name: 'Do nothing',
          value: 'none'
        }
      ]
    },
    {
      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 || answers.editAssigned === 'edit'
    },
    {
      type: 'recursive',
      name: 'addSubTasks',
      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: 'editSubTasks',
      initialMessage: 'Update or remove a sub-task?',
      message: 'Update or remove another sub-task?',
      default: false,
      when: answers => taskData.subTasks.length > 0,
      prompts: [
        {
          type: 'list',
          name: 'selectSubTask',
          message: 'Which sub-task do you want to update or remove?',
          choices: taskData.subTasks.map(subTask => subTask.text)
        },
        {
          type: 'expand',
          name: 'editSubTask',
          message: 'Edit completion status or remove sub-task?',
          default: 'none',
          choices: [
            {
              key: 'e',
              name: 'Edit completion status',
              value: 'edit'
            },
            {
              key: 'r',
              name: 'Remove',
              value: 'remove'
            },
            new inquirer.Separator(),
            {
              key: 'n',
              name: 'Do nothing',
              value: 'none'
            }
          ]
        },
        {
          type: 'confirm',
          name: 'completed',
          message: 'Sub-task completed?',
          default: answers => taskData.subTasks.find(subTask => subTask.text === answers.selectSubTask).completed,
          when: answers => answers.editSubTask === 'edit'
        }
      ]
    },
    {
      type: 'recursive',
      name: 'addTags',
      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: 'removeTags',
      initialMessage: 'Remove a tag?',
      message: 'Remove another tag?',
      default: false,
      when: answers => (
        'metadata' in taskData &&
        'tags' in taskData.metadata &&
        taskData.metadata.tags.length > 0
      ),
      prompts: [
        {
          type: 'list',
          name: 'selectTag',
          message: 'Which tag do you want to remove?',
          choices: taskData.metadata.tags
        }
      ]
    },
    {
      type: 'recursive',
      name: 'addRelations',
      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:'
        }
      ]
    },
    {
      type: 'recursive',
      name: 'editRelations',
      initialMessage: 'Update or remove a relation?',
      message: 'Update or remove another relation?',
      default: false,
      when: answers => taskData.relations.length > 0,
      prompts: [
        {
          type: 'list',
          name: 'selectRelation',
          message: 'Which relation do you want to update or remove?',
          choices: taskData.relations.map(relation => relation.task)
        },
        {
          type: 'expand',
          name: 'editRelation',
          message: 'Edit relation type or remove relation?',
          default: 'none',
          choices: [
            {
              key: 'e',
              name: 'Edit relation type',
              value: 'edit'
            },
            {
              key: 'r',
              name: 'Remove',
              value: 'remove'
            },
            new inquirer.Separator(),
            {
              key: 'n',
              name: 'Do nothing',
              value: 'none'
            }
          ]
        },
        {
          type: 'input',
          name: 'type',
          message: 'Relation type:',
          default: answers => taskData.relations.find(relation => relation.task === answers.selectRelation).type,
          when: answers => answers.editRelation === 'edit'
        }
      ]
    }
  ]);
}
 
/**
 * Metadata fields that can be cleared with --unset, in addition to any custom fields defined in
 * the index options
 */
const UNSETTABLE_FIELDS = [
  'started',
  'completed',
  'due',
  'plannedStart',
  'plannedFinish',
  'assigned',
  'progress',
  'tags'
];
 
/**
 * Update a task
 * @param {string} taskId
 * @param {object} taskData
 * @param {?string} columnName
 * @param {string[]} [unsetFields=[]]
 */
function updateTask(taskId, taskData, columnName, unsetFields = []) {
  kanbn
  .updateTask(taskId, taskData, columnName, unsetFields)
  .then(taskId => {
    console.log(`Updated task "${taskId}"`);
  })
  .catch(error => {
    utility.error(error);
  });
}
 
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 task that we're editing
  const taskId = args._[1];
  if (!taskId) {
    utility.error('No task id specified\nTry running {b}kanbn edit "task id"{b}');
    return;
  }
 
  // Make sure the task exists
  try {
    await kanbn.taskExists(taskId);
  } catch (error) {
    utility.error(error);
    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 the current task data
  let taskData;
  try {
    taskData = await kanbn.getTask(taskId);
  } catch (error) {
    utility.error(error);
    return;
  }
 
  // Get column name if specified
  let currentColumnName = await kanbn.findTaskColumn(taskId);
  let columnName = currentColumnName;
  if (args.column) {
    columnName = utility.strArg(args.column);
    if (columnNames.indexOf(columnName) === -1) {
      utility.error(`Column "${columnName}" doesn't exist`);
      return;
    }
  }
 
  // 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) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    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) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    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) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    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) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    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) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    const gitUsername = getGitUsername();
    if (args.assigned === true) {
      if (gitUsername) {
        taskData.metadata.assigned = gitUsername;
      }
    } else {
      taskData.metadata.assigned = utility.strArg(args.assigned);
    }
  }
 
  // Remove sub-tasks
  if (args['remove-sub-task']) {
    const removedSubTasks = utility.arrayArg(args['remove-sub-task']);
 
    // Check that the sub-tasks being removed currently exist
    for (let removedSubTask of removedSubTasks) {
      if (taskData.subTasks.find(subTask => subTask.text === removedSubTask) === undefined) {
        utility.error(`Sub-task "${removedSubTask}" doesn't exist`);
        return;
      }
    }
    taskData.subTasks = taskData.subTasks.filter(subTask => removedSubTasks.indexOf(subTask.text) === -1);
  }
 
  // Add or update sub-tasks
  if (args['sub-task']) {
    const newSubTaskInputs = utility.arrayArg(args['sub-task']);
    const newSubTasks = newSubTaskInputs.map(subTask => {
      const match = subTask.match(/^\[([x ])\] (.*)/);
      if (match !== null) {
        return {
          completed: match[1] === 'x',
          text: match[2]
        };
      }
      return {
        completed: false,
        text: subTask
      };
    });
 
    // Add or update
    for (let newSubTask of newSubTasks) {
 
      // Check if a sub-task already exists in the task with matching text
      const foundSubTask = taskData.subTasks.find(subTask => subTask.text === newSubTask.text);
      if (foundSubTask === undefined) {
 
        // The sub-task doesn't already exist
        taskData.subTasks.push(newSubTask);
 
      // Otherwise, the sub-task already exists so update its completed status
      } else {
        foundSubTask.completed = newSubTask.completed;
      }
    }
  }
 
  // Remove tags
  if (args['remove-tag']) {
    const removedTags = utility.arrayArg(args['remove-tag']);
 
    // Check that the task has metadata
    if (!('metadata' in taskData) || !('tags' in taskData.metadata) || !Array.isArray(taskData.metadata.tags)) {
      utility.error('Task has no tags to remove');
      return;
    }
 
    // Check that the tags being removed currently exist
    for (let removedTag of removedTags) {
      if (taskData.metadata.tags.indexOf(removedTag) === -1) {
        utility.error(`Tag "${removedTag}" doesn't exist`);
        return;
      }
    }
    taskData.metadata.tags = taskData.metadata.tags.filter(tag => removedTags.indexOf(tag) === -1);
  }
 
  // Add tags and overwrite existing tags
  if (args.tag) {
    const newTags = utility.arrayArg(args.tag);
    taskData.metadata.tags = [...new Set([...taskData.metadata.tags || [], ...newTags])];
  }
 
  // Remove relations
  if (args['remove-relation']) {
    const removedRelations = utility.arrayArg(args['remove-relation']);
 
    // Check that the relations being removed currently exist
    for (let removedRelation of removedRelations) {
      if (taskData.relations.find(relation => relation.task === removedRelation) === undefined) {
        utility.error(`Relation "${removedRelation}" doesn't exist`);
        return;
      }
    }
    taskData.relations = taskData.relations.filter(relation => removedRelations.indexOf(relation.task) === -1);
  }
 
  // Add or update relations
  if (args.relation) {
    const newRelationInputs = utility.arrayArg(args.relation);
    const newRelations = newRelationInputs.map(relation => {
      const parts = relation.split(' ');
      return parts.length === 1
        ? {
          type: '',
          task: parts[0].trim()
        }
        : {
          type: parts[0].trim(),
          task: parts[1].trim()
        };
    });
 
    // Add or update
    for (let newRelation of newRelations) {
 
      // Check if a relation already exists in the task with matching task id
      const foundRelation = taskData.relations.find(relation => relation.task === newRelation.task);
      if (foundRelation === undefined) {
 
        // The relation doesn't already exist
        taskData.relations.push(newRelation);
 
      // Otherwise, the relation already exists so update its relation type
      } else {
        foundRelation.type = newRelation.type;
      }
    }
  }
 
  // Check custom field types
  if ('customFields' in index.options) {
    if (!('metadata' in taskData)) {
      taskData.metadata = {};
    }
    for (let arg of Object.keys(args)) {
 
      // Check if we're removing a custom field
      const removeCustomField = index.options.customFields.find(p => `remove-${p.name}` === arg);
      if (removeCustomField !== undefined) {
        if (removeCustomField.name in taskData.metadata) {
          delete taskData.metadata[removeCustomField.name];
        }
      }
 
      // Check if we're adding or modifying a custom field
      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 "${fieldName}" 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;
        }
      }
    }
  }
 
  // Unset metadata fields
  const unsetFields = [];
  if (args.unset) {
    const customFieldNames = 'customFields' in index.options
      ? index.options.customFields.map(customField => customField.name)
      : [];
    const unsettableFields = [...UNSETTABLE_FIELDS, ...customFieldNames];
 
    // Arguments that set the value of a metadata field, so that setting and unsetting the same
    // field in one command can be rejected instead of silently resolving one way or the other
    const settingArgs = {
      due: args.due,
      plannedStart: args.plannedStart,
      plannedFinish: args.plannedFinish,
      progress: args.progress,
      assigned: args.assigned,
      tags: args.tag,
      ...Object.fromEntries(customFieldNames.map(name => [name, args[name]]))
    };
 
    for (let field of utility.arrayArg(args.unset)) {
      if (unsettableFields.indexOf(field) === -1) {
        utility.error(
          `Cannot unset "${field}"\nAvailable fields: ${unsettableFields.join(', ')}`
        );
        return;
      }
      if (settingArgs[field] !== undefined) {
        utility.error(`Cannot set and unset "${field}" in the same command`);
        return;
      }
      if (unsetFields.indexOf(field) === -1) {
        unsetFields.push(field);
      }
    }
  }
 
  // Update task interactively
  if (args.interactive) {
    interactive(taskData, taskIds, columnName, columnNames)
    .then(answers => {
 
      // Name
      taskData.name = answers.name;
 
      // Description
      if ('description' in answers) {
        taskData.description = answers.description;
      }
 
      // Remove due date
      if ('editDue' in answers && answers.editDue === 'remove') {
        delete taskData.metadata.due;
      }
 
      // Due date
      if ('due' in answers) {
        taskData.metadata.due = answers.due;
      }
 
      // Remove planned start date
      if ('editPlannedStart' in answers && answers.editPlannedStart === 'remove') {
        delete taskData.metadata.plannedStart;
      }
 
      // Planned start date
      if ('plannedStart' in answers) {
        taskData.metadata.plannedStart = answers.plannedStart;
      }
 
      // Remove planned finish date
      if ('editPlannedFinish' in answers && answers.editPlannedFinish === 'remove') {
        delete taskData.metadata.plannedFinish;
      }
 
      // Planned finish date
      if ('plannedFinish' in answers) {
        taskData.metadata.plannedFinish = answers.plannedFinish;
      }
 
      // Remove assigned
      if ('editAssigned' in answers && answers.editAssigned === 'remove') {
        delete taskData.metadata.assigned;
      }
 
      // Assigned
      if ('assigned' in answers) {
        taskData.metadata.assigned = answers.assigned;
      }
 
      // Edit or remove sub-tasks
      if ('editSubTasks' in answers) {
        for (editSubTask of answers.editSubTasks) {
          const i = taskData.subTasks.findIndex(subTask => subTask.text === editSubTask.selectSubTask);
          if (i !== -1) {
            switch (editSubTask.editSubTask) {
              case 'remove':
                taskData.subTasks.splice(i, 1);
                break;
              case 'edit':
                taskData.subTasks[i].completed = editSubTask.completed;
                break;
              default:
                break;
            }
          }
        }
      }
 
      // Add sub-tasks
      if ('addSubTasks' in answers) {
        taskData.subTasks.push(...answers.addSubTasks.map(addSubTask => ({
          text: addSubTask.text,
          completed: addSubTask.completed
        })));
      }
 
      // Remove tags
      if ('removeTags' in answers && 'metadata' in taskData && 'tags' in taskData.metadata) {
        for (removeTag of answers.removeTags) {
          const i = taskData.metadata.tags.indexOf(removeTag.selectTag);
          if (i !== -1) {
            taskData.metadata.tags.splice(i, 1);
          }
        }
      }
 
      // Add tags
      if ('addTags' in answers && 'metadata' in taskData && 'tags' in taskData.metadata) {
        taskData.metadata.tags.push(...answers.addTags.map(tag => tag.name));
      }
 
      // Edit or remove relations
      if ('editRelations' in answers) {
        for (editRelation of answers.editRelations) {
          const i = taskData.relations.findIndex(relation => relation.task === editRelation.selectRelation);
          if (i !== -1) {
            switch (editRelation.editRelation) {
              case 'remove':
                taskData.relations.splice(i, 1);
                break;
              case 'edit':
                taskData.relations[i].type = editRelation.type;
                break;
              default:
                break;
            }
          }
        }
      }
 
      // Add relations
      if ('addRelations' in answers) {
        taskData.relations.push(...answers.addRelations.map(addRelation => ({
          task: addRelation.task,
          type: addRelation.type
        })));
      }
 
      // Update task
      columnName = answers.column !== currentColumnName ? answers.column : null;
      updateTask(taskId, taskData, columnName, unsetFields);
    })
    .catch(error => {
      utility.error(error);
    });
 
  // Otherwise edit task non-interactively
  } else {
    columnName = columnName !== currentColumnName ? columnName : null;
    updateTask(taskId, taskData, columnName, unsetFields);
  }
};