All files / lib/cli functions.js

83.27% Statements 224/269
67.74% Branches 105/155
96.83% Functions 61/63
82.76% Lines 216/261
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  1x 1x 1x 1x 1x 1x 1x                   3x     3x 2x   1x       1x   3x 2x   3x 1x       3x     3x                             3x 1x 1x 1x     2x     3x 2x   2x       1x 1x             5x 5x       5x 1x   4x 3x   1x     1x   1x   1x   1x 1x     1x 2x 2x 2x               1x   1x 1x   1x 1x     1x 3x           3x   3x 3x 6x   6x 6x   6x 3x     6x 6x 4x 4x     6x             2x 2x 2x       2x     2x 2x           2x                         2x   2x 2x           4x 4x 4x         4x 4x   4x 6x   6x 2x     4x     6x 6x 6x 6x         4x     4x     4x 2x     4x   4x     4x           3x 3x       3x       3x         3x 3x     3x     3x 3x           3x 3x 3x           3x 3x 3x       3x         3x 1x   3x         3x 3x     3x   3x       3x 4x 3x           2x 2x 2x         2x 1x   1x     2x           2x 2x     2x 1x     1x     2x         2x 2x     2x   2x       4x 2x                   22x 22x     2x   22x           19x       19x       19x 19x 19x         19x 19x 19x                                                                             8x       8x               8x 4x 4x       4x 3x     1x 2x 2x       4x 1x     3x     9x     4x   4x 2x   2x         5x           5x 3x 3x       3x 3x     2x       5x               5x 3x 5x 5x 4x   5x 6x 6x       3x         2x 4x 3x   4x 6x       2x         5x 1x     4x 2x 2x 8x 5x     2x     2x 1x 3x 2x         2x   2x     2x         55x 55x   55x 55x   55x 55x           55x             1x                    
'use strict';
const path = require('path');
const fs = require('fs');
const inquirer = require('inquirer');
const chalk = require('chalk');
const todo = require('../todo');
const md = require('../md/md');
const config = require('../config');
 
/*
 * PUBLIC
 */
function tui(options) {
  return Promise.reject(new TypeError('TUI is not yet implemented...', options.argv));
}
 
function newProject(options) {
  inquirer.registerPrompt('multiline', require('../inquirer-multiline'));
  // Parse filename
  let filename;
  if (options.file) {
    filename = options.file;
  }
  else Iif (options.argv.length === 0) {
    filename = config.data.defaultFileName;
  }
  else {
    filename = options.argv.join('_');
  }
  if (path.extname(filename) !== '.md') {
    filename += '.md';
  }
  if (options.global) {
    filename = path.join(config.folder, filename);
  }
 
  // Check file
  const exists = fileCheck(filename);
 
  // Inquirer
  const questions = [
    {
      type: 'input',
      name: 'title',
      message: 'Title: ',
      default: path.basename(filename, '.md')
    },
    {
      type: 'multiline',
      name: 'desc',
      message: 'Description: '
    }
  ];
 
  let inquiry;
  if (exists) {
    inquiry = Promise.resolve()
      .then(() => inquirer.prompt([{type: 'confirm', name: 'overwrite', message: 'File already exists! Overwrite? ', default: false}]))
      .then(answer => answer.overwrite ? Promise.resolve() : Promise.reject(new Error('overwrite')));
  }
  else {
    inquiry = Promise.resolve();
  }
 
  return inquiry
    .then(() => inquirer.prompt(questions))
    .then(answers => {
      return md.writeFile(filename, new todo.Project(answers.title, answers.desc))
        .catch(err => Promise.reject(new Error(`Something went wrong writing the file: ${err.message}`)));
    })
    .catch(x => {
      Eif (x.message === 'overwrite') {
        return Promise.resolve();
      }
      return Promise.reject(x);
    });
}
 
function list(options) {
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  if (options.interactive) {
    return listInteractive();
  }
  if (options.argv.length !== 0) {
    return listRegexp();
  }
  return listList();
 
  function listInteractive() {
    return md.readFile(filename)
      .then(project => {
        return getLists(project, 'list', 'Pick a list:', {autoresolve: false})
          .then(listindex => {
            const list = project.getList(listindex[0]);
 
            Eif (list.desc.length !== 0) {
              console.log(chalk.gray(printMD(list.desc)));
            }
 
            list._content.forEach(item => {
              Eif ((!options.checked && !options.unchecked) || (options.checked && item.done) || (options.unchecked && !item.done)) {
                const done = item.done ? chalk.green(config.symbols.ok) : chalk.red(config.symbols.nok);
                console.log('  ' + done + ' ' + printMD(item.value));
              }
            });
          });
      });
  }
 
  function listList() {
    return md.readFile(filename)
      .then(project => {
        Eif (project.title.length !== 0) {
          console.log(chalk.cyan(printMD(project.title)));
        }
        Eif (project.desc.length !== 0) {
          console.log(chalk.gray(printMD(project.desc)));
        }
 
        project._content.forEach(list => {
          console.log(chalk.cyan('  >> ') + printMD(list.title));
        });
      });
  }
 
  function listRegexp() {
    return md.readFile(filename)
      .then(project => {
        const search = options.argv.join('[^]*');
        project.findLists(search, !options.limit).forEach(listindex => {
          const list = project.getList(listindex);
 
          Eif (list.title.length !== 0) {
            console.log(chalk.cyan(printMD(list.title)));
          }
          if (list.desc.length !== 0) {
            console.log(chalk.gray(printMD(list.desc)));
          }
 
          list._content.forEach(item => {
            if ((!options.checked && !options.unchecked) || (options.checked && item.done) || (options.unchecked && !item.done)) {
              const done = item.done ? chalk.green(config.symbols.ok) : chalk.red(config.symbols.nok);
              console.log('  ' + done + ' ' + printMD(item.value));
            }
          });
          console.log();
        });
      });
  }
}
 
function listAdd(options) {
  inquirer.registerPrompt('multiline', require('../inquirer-multiline'));
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  return md.readFile(filename)
    .then(project => {
      let listName;
      Eif (options.argv.length === 0) {
        listName = 'List ' + (project.length + 1);
      }
      else {
        listName = options.argv.join(' ');
      }
 
      const questions = [
        {
          type: 'input',
          name: 'title',
          message: 'Title: ',
          default: listName
        },
        {
          type: 'multiline',
          name: 'desc',
          message: 'Description: '
        }
      ];
      return inquirer.prompt(questions)
        .then(answers => {
          project.insertList(new todo.List(answers.title, answers.desc), Number(options.number) - 1);
          return md.writeFile(filename, project);
        });
    });
}
 
function listRm(options) {
  inquirer.registerPrompt('specialCheckbox', require('../inquirer-custom-checkbox'));
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  function remove(project, lists) {
    lists.sort((a, b) => b - a);
    const listProm = [];
 
    lists.forEach(index => {
      const list = project.getList(index);
      let p;
      if (list.length === 0) {
        p = Promise.resolve({delete: true});
      }
      else {
        p = inquirer.prompt({type: 'confirm', name: 'delete', message: `${printMD(list.title)} is not empty! Remove anyway?`, default: false});
      }
 
      listProm.push(p);
      p.then(answer => {
        Eif (answer.delete) {
          project.removeList(index);
        }
      });
    });
 
    return Promise.all(listProm).then(() => md.writeFile(filename, project));
  }
 
  return md.readFile(filename)
    .then(project => {
      let search;
      if (options.argv.length !== 0) {
        search = options.argv.join('[^]*');
      }
 
      return getLists(project, 'specialCheckbox', 'Pick the list you want to remove:', {search, desc: !options.limit, autoresolve: true, all: options.all})
        .then(listindices => {
          Iif (listindices.length === 0) {
            return Promise.reject(new Error('No list selected'));
          }
          return remove(project, listindices);
        });
    });
}
 
function itemAdd(options) {
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  return md.readFile(filename)
    .then(project => {
      let list;
      let desc;
      Iif (options.List) {
        list = options.List;
        desc = true;
      }
      else {
        list = options.list;
        desc = false;
      }
 
      return getLists(project, 'list', 'Pick a list:', {search: list, desc, autoresolve: true})
        .then(listindex => {
          let p;
          Eif (options.argv.length === 0) {
            p = inquirer.prompt({type: 'input', name: 'value', message: 'Item\'s text: ', default: 'Todo'}).then(answers => answers.value);
          }
          else {
            p = Promise.resolve(options.argv.join(' '));
          }
 
          return p
            .then(value => project.getList(listindex[0]).insertItem(value, false, Number(options.number) - 1))
            .then(() => md.writeFile(filename, project));
        });
    });
}
 
function itemRm(options) {
  inquirer.registerPrompt('specialCheckbox', require('../inquirer-custom-checkbox'));
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  return md.readFile(filename)
    .then(project => {
      let search;
      let list;
      let desc;
      if (options.argv.length !== 0) {
        search = options.argv.join('.*');
      }
      Iif (options.List) {
        list = options.List;
        desc = true;
      }
      else {
        list = options.list;
        desc = false;
      }
 
      return getItems(project, 'specialCheckbox', 'Pick the items you want to remove:', {listSearch: list, listDesc: desc, search, all: options.all})
        .then(itemindices => {
          Iif (itemindices.length === 0) {
            return Promise.reject(new Error('No items selected'));
          }
 
          itemindices.sort((a, b) => b.index - a.index);
          itemindices.forEach(item => item.list.removeItem(item.index));
          return md.writeFile(filename, project);
        });
    });
}
 
function itemMark(value, options) {
  inquirer.registerPrompt('specialCheckbox', require('../inquirer-custom-checkbox'));
  const {filename, exists} = getFile(options);
  Iif (!exists) {
    return Promise.reject(new Error(`Could not find the file: ${filename}`));
  }
 
  function disable(item) {
    if (item.value.list.getItem(item.value.index).done === value) {
      return 'Already ' + (value ? 'checked' : 'unchecked');
    }
    return false;
  }
 
  return md.readFile(filename)
    .then(project => {
      let search;
      let msg;
      let list;
      let desc;
      Eif (options.argv.length !== 0) {
        search = options.argv.join('.*');
      }
 
      if (value) {
        msg = 'Pick the items you want to check:';
      }
      else {
        msg = 'Pick the items you want to uncheck:';
      }
 
      Iif (options.List) {
        list = options.List;
        desc = true;
      }
      else {
        list = options.list;
        desc = false;
      }
 
      return getItems(project, 'specialCheckbox', msg, {listSearch: list, listDesc: desc, search, disable, all: options.all})
        .then(itemindices => {
          Iif (itemindices.length === 0) {
            return Promise.reject(new Error('No items selected'));
          }
 
          itemindices.forEach(item => item.list.markItem(item.index, value));
          return md.writeFile(filename, project);
        });
    });
}
 
/*
 * PRIVATE
 */
function fileCheck(file) {
  let exists;
  try {
    exists = fs.statSync(file).isFile();
  }
  catch (err) {
    exists = false;
  }
  return exists;
}
 
function getFile(options) {
  // Parse filename
  let filename;
  Iif (options.file) {
    filename = options.file;
  }
  else {
    filename = config.data.defaultFileName;
  }
 
  // Check if file already exists
  let folder = process.cwd();
  for (let i = 0; i <= 1; ++i) {
    Iif (options.global) {
      folder = config.folder;
      ++i;
    }
 
    let test = path.join(folder, filename);
    Eif (fileCheck(test)) {
      return {
        filename: test,
        exists: true
      };
    }
    test = path.join(folder, '.' + filename);
    if (fileCheck(test)) {
      return {
        filename: test,
        exists: true
      };
    }
    if (path.extname(filename) !== '.md') {
      test = path.join(folder, filename + '.md');
      if (fileCheck(test)) {
        return {
          filename: test,
          exists: true
        };
      }
      test = path.join(folder, '.' + filename + '.md');
      if (fileCheck(test)) {
        return {
          filename: test,
          exists: true
        };
      }
    }
 
    folder = config.folder;
  }
 
  return {
    filename,
    exists: false
  };
}
 
function getLists(project, type, message, {search, desc, autoresolve, all}) {
  Iif (project.length === 0) {
    return Promise.reject(new Error('This project does not contain any lists'));
  }
 
  const question = {
    type,
    name: 'listindices',
    message,
    pageSize: config.data.maxListSize,
    choices: []
  };
 
  if (search) {
    const listindices = project.findLists(search, desc);
    Iif (listindices.length === 0) {
      return Promise.reject(new Error(`Could not find a list that matched with ${search}`));
    }
 
    if (all || (listindices.length === 1 && autoresolve)) {
      return Promise.resolve(listindices);
    }
 
    listindices.forEach(index => {
      const list = project.getList(index);
      question.choices.push({value: index, name: printMD(list.title)});
    });
  }
  else {
    if (all) {
      return Promise.resolve([...Array(project.length).keys()]);
    }
 
    Iif (project.length === 1 && autoresolve) {
      return Promise.resolve([0]);
    }
    project._content.forEach((list, index) => question.choices.push({value: index, name: printMD(list.title)}));
  }
 
  return inquirer.prompt(question)
    .then(answers => {
      if (Array.isArray(answers.listindices)) {
        return answers.listindices;
      }
      return [answers.listindices];
    });
}
 
function getItems(project, type, message, {listSearch, listDesc, search, all, disable}) {
  Iif (project.length === 0) {
    return Promise.reject(new Error('This project does not contain any lists'));
  }
 
  // Get lists
  let lists;
  if (listSearch) {
    const listindices = project.findLists(listSearch, listDesc);
    Iif (listindices.length === 0) {
      return Promise.reject(new Error(`Could not find a list that matched with ${listSearch}`));
    }
 
    lists = [];
    listindices.forEach(index => lists.push(project.getList(index)));
  }
  else {
    lists = project._content;
  }
 
  // Get items
  const question = {
    type,
    name: 'items',
    message,
    pageSize: config.data.maxListSize,
    choices: []
  };
 
  if (search) {
    lists.forEach(list => {
      const itemindices = list.findItems(search);
      if (itemindices.length !== 0) {
        question.choices.push(new inquirer.Separator(printMD(list.title)));
      }
      itemindices.forEach(index => {
        const item = list.getItem(index);
        question.choices.push({value: {list, index}, name: printMD(item.value)});
      });
    });
 
    Iif (question.choices.length === 0) {
      return Promise.reject(new Error(`Could not find an item that matched with ${search}`));
    }
  }
  else {
    lists.forEach(list => {
      if (list.length !== 0) {
        question.choices.push(new inquirer.Separator(printMD(list.title)));
      }
      list._content.forEach((item, index) => {
        question.choices.push({value: {list, index}, name: printMD(item.value)});
      });
    });
 
    Iif (question.choices.length === 0) {
      return Promise.reject(new Error('This project does not contain any items'));
    }
  }
 
  if (question.choices.length === 2) {
    return Promise.resolve([question.choices[1].value]);
  }
 
  if (all) {
    const answer = [];
    question.choices.forEach(choice => {
      if (choice.value) {
        answer.push(choice.value);
      }
    });
    return Promise.resolve(answer);
  }
 
  if (disable) {
    question.choices.forEach(choice => {
      if (choice.value) {
        choice.disabled = disable(choice);
      }
    });
  }
 
  return inquirer.prompt(question)
    .then(answers => {
      Iif (Array.isArray(answers.items)) {
        return answers.items;
      }
      return [answers.items];
    });
}
 
function printMD(string) {
  string = string.replace(/(\W|^)__(.+?)__(\W|$)/g, '$1' + chalk.bold('$2') + '$3');
  string = string.replace(/(\W|^)\*\*(.+?)\*\*(\W|$)/g, '$1' + chalk.bold('$2') + '$3');
 
  string = string.replace(/(\W|^)_(.+?)_(\W|$)/g, '$1' + chalk.italic('$2') + '$3');
  string = string.replace(/(\W|^)\*(.+?)\*(\W|$)/g, '$1' + chalk.italic('$2') + '$3');
 
  Eif (config.data.strikethrough) {
    string = string.replace(/(\W|^)~~(.+?)~~(\W|$)/g, '$1' + chalk.strikethrough('$2') + '$3');
  }
  else {
    string = string.replace(/(\W|^)~~(.+?)~~(\W|$)/g, '$1' + chalk.underline('$2') + '$3');
  }
 
  return string;
}
 
 
/*
 * MODULE EXPORTS
 */
module.exports = {
  tui,
  newProject,
  list,
  listAdd,
  listRm,
  itemAdd,
  itemRm,
  itemMark
};