Action

Format Markdown

Posted by jpp, Last update about 4 years ago

Use prettier js to format markdown via script.
Mac only.
Requires prettier to be installed globally yarn global add prettier or npm install -g prettier and the prettier install folder added to the script (check with which prettier).

Steps

  • script (macOS only)

    /*
    Uses prettier to format contents of draft
    Prettier should be installed glabally `yarn global add prettier`
    `prettierFolder` contstant should be udpated to point to the install folder
    (`which prettier`)
    */
    
    const prettierFolder = "/usr/local/bin";
    const fm = FileManager.createLocal();
    const tmpFile = "tmp.md";
    const tmpFilePath = `${fm.basePath}/${tmpFile}`;
    
    formatDraft();
    
    function formatDraft() {
      console.log(tmpFilePath);
      writeFile();
      formatFile();
      const formatted = readFile();
    
      if (formatted) {
        draft.content = formatted;
        draft.update();
      }
      cleanup();
    }
    
    function writeFile() {
      const result = fm.writeString(tmpFile, draft.content);
      if (!result) {
        console.log(`Write failed: ${fm.lastError}`);
        context.fail();
      }
      return result;
    }
    
    function readFile() {
      const result = fm.readString(tmpFile);
      if (!result) {
        console.log(`Read failed: ${fm.lastError}`);
        context.fail();
      }
      return result;
    }
    
    function formatFile() {
      const script = `#!/usr/bin/env bash
    export PATH=$2:$PATH
    prettier --write "$1"
    `;
    
      const runner = ShellScript.create(script);
      if (runner.execute([tmpFilePath, prettierFolder])) {
        console.log(`Shell script succeeded: ${runner.standardOutput}`);
      } else {
        console.log(`Shell script failed: ${runner.standardError}`);
        context.fail();
      }
    }
    
    function cleanup() {
      const script = `#!/usr/bin/env bash
    mv "$1" ~/.Trash/
    `;
    
      const runner = ShellScript.create(script);
      if (runner.execute([tmpFilePath])) {
        console.log(`Shell script succeeded: ${runner.standardOutput}`);
      } else {
        console.log(`Shell script failed: ${runner.standardError}`);
        context.fail();
      }
    }
    

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.