Making a TIME Management Tool for the CLI (part 2)

This is the third day of my participation in the August More Text Challenge. For details, see “August More Text Challenge”.

preface

The previous article described the background of the project and what is expected to be achieved through the project

Set up the initial engineering of the project

This article will continue to expand the function

The function development

MD turn JSON

The simplest markDown format is as follows

# 2021-08-03
## TaskName
*Fishing in 0.6Copy the code

The corresponding JSON structure is as follows

[{"title": "2021-08-03"."tasks": [{"title": "TaskName"."things": [{"time": "0.6"."content": "Fishing"}]}]}]Copy the code
  • The outermost layer is an array
    • There are multiple 1-level titles in an MD, so the outermost data structure uses an array
  • The second floor
    • Title corresponds to the level 1 title
    • Tasks stores a list of tasks composed of secondary headings and their subcontents, stored as an array
  • The third layer
    • Title corresponds to the content of the secondary title
    • Things consists of each row of its child list
      • Each line of content corresponds to a basic event unit
      • The basic event unit contains two parts: event content and event duration

The conversion process is as follows:

The MD content is read in and parsed by line

const lines = fileContent.split('\n')
Copy the code

Determine whether to start with a # level 1 heading. If yes, it is a new day

Add title, tasks attributes to it

const resData = []
let item = null
for (const line of lines) {
       // Judge whether it is a new day
       if (line.startsWith(The '#')) {
           // Store the old ones
           if (item) {
               resData.push(item)
           }
       const title = line.replace(/#|\s/g.' ')
        item = {
            title,
            tasks: []}}}Copy the code

Then determine whether to start with a ## secondary heading, and if so, add it to the tasks list as a task

// Determine whether it is a task
if (line.startsWith('## ')) {
    const title = line.replace(/#|\s/g.' ')
    let task = {
        title,
        things: []
    }
    item.tasks.push(task)
}
Copy the code

Decide if it starts with *, and if so, add it to the things list as a thing

if (line.startsWith(The '*')) {
    const task = item.tasks.pop()
    const { things } = task
    const rTime = /((0.\d*)|(\d*))? $/
    const time = line.match(rTime)[0] | |'0'
    let step = -1, text = ' '
    const content = (step = (text = line.replace(/\*|\s/g.' ')).lastIndexOf(time)) === -1 ? text : text.slice(0, step)
    const thing = {
        time,
        content
    }
    things.push(thing)
    item.tasks.push(task)
}
Copy the code

And so on until the next # level 1 heading is encountered

Full code link

Add the instruction

Edit the bin/index.js file

Add two optionsOutput, JSON

Json export is performed only when –output and –json are entered simultaneously

#! /usr/bin/env node
const json = require('.. /package.json');
const commander = require('commander');
const { getFilesContent, getFilePath, createFile } = require('.. /src/utils');
const { outputJson } = require('.. /src/output');

// Command execution directory
const cwd = process.cwd()

// Set the version number
commander.version(json.version)

/ / export
commander.arguments('
      
        '
      ) // Multiple files/directories
    .option('-o, --output'.'Export analysis results')
    .option('-j, --json'.'Export result as json description file')
    .action((filenames, cmdObj) = > {
        const { output, json } = cmdObj

        / / export
        if (output) {
            let outFileName = 'res'
            // Follow up logic

            // Get the contents of all files
            const content = getFilesContent(filenames.map(filename= > {
                return getFilePath(cwd, filename)
            }))
            if (json) {
                createFile(getFilePath(cwd, `${outFileName}.json`), outputJson(content), false)
            }
        }
    })

commander.parse(process.argv)
Copy the code

After the addition, run timec –help to check the addition

The corresponding execution instruction is

timec -oj filepath1 filepath2 ....
Copy the code
  • Among themprocess.cwd()Can get the directory where the instruction is executed
  • filenamesParameter Is obtained except for the parameters in the options section
  • CmdObj contains the contents of the options parameter. The value type is Boolean
    • --outputCorresponding output parameter
    • --jsonThe content of the corresponding JSON parameter
    • And so on

other

Because of the limited free time each day, this article will stop there

If you still feel more than enough, please stay tuned for further updates, or check out the warehouse first

Welcome to comment section to raise demand, exchange discussion

This series will continue to be updated and iterated until the first generation of the product is completed

  • The warehouse address