Drafts Action Directory

Import Script

Posted by @edgauthier, Last update 5 months ago

Defines an import_script(id) function that can be used by other scripts to enable reuse of code stored in separate drafts.

The import_script function accepts an identifier that can be either a draft UUID, or the name of a draft. If a name is passed in, the function will look for a draft with the “script” tag that has a title which matches the input argument. This function assumes other “script” drafts have a first line which starts with “// “, which is excluded when comparing the title with the supplied input.

Once this action is imported in Drafts, you can include it in other actions by adding an “Include Action” step and specifying the name of this action. Subsequent script steps can then use the import_script() function to bring in other drafts to be evaluated before they’re processed.

Include this action as the first step in the “Eval Draft” action and you’ll have access to the same imports while evaluating your current draft. I find this to be a good option to develop more complex scripts and run them from the main editor where you don’t have access to the “Include Action” step.

Install

Steps

  • script

    // Scripting - Import Script
    
    (() => {
    
      // RegEx to match a UUID
      const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
      
      /*
       * Imports a script by name or UUID
       * 
       * id - The identifier of a script to search for - 
       *      either a draft UUID or a name (minus leading "// ")
       * 
      **/
      this.import_script = id => {
        // Try UUID lookup if possible
        // Otherwise, find script by name
        const code = id.match(UUID_RE)
          ? findContentByUuid(id)
          : findContentByName(id);
      
        // using this.eval to ensure the code is evaluated 
        // in the global scope (rather than a local scope) 
        // and any defined functions in the import are 
        // available to the calling script 
        this.eval(code);   
      };
      
      const findContentByUuid = id => {
        const d = Draft.find(id);
        return d ? d.content : notFound(id);
      };
      
      const findContentByName = name => {
        const 
          scripts = Draft.query(name, "all", ["script"]),
          i = scripts.findIndex(d => d.title === ('// ' + name));
        
        return i !== -1 ? scripts[i].content : notFound(name);
      };
      
      const notFound = id => {
        const msg = "Import Failed: Not Found";
        context.fail("Not found: " + id);
        app.displayErrorMessage(msg);
        throw msg;
      };
    
    })();

Options

  • After Success Default
    Notification Error
    Log Level Error

Comments

Actions available in the Action Directory are uploaded by community members. Use appropriate caution reviewing downloaded actions before use.