Action

Prepend Mac External

Posted by sylumer, Last update over 3 years ago - Unlisted

Prepend the content of the current draft to a file path outside the Drafts sandbox, as specified by the tag PATH in this action.

IMPORTANT:
1) This action will not work on i*OS.
2) The file to be appended to must already exist.

Steps

  • defineTemplateTag

    name
    PATH
    template
    $HOME/Library/Mobile Documents/com~apple~CloudDocs/Test/example.txt
  • script

    // Generate a v4 UUID.
    function genUUID(a,b)
    {
    	for(b=a='';a++<36;b+=a*51&52?(a^15?8^Math.random()*(a^20?16:4):4).toString(16):'-');
    	return b;
    }
    
    // Append to a file outside the drafts sandbox
    function macPrepend(p_strDestinationPath, p_strContent)
    {
    	//Set the name of a temporary file
    	let strTempFilePath = genUUID() + ".txt";
    
    	// Set up a shell script to copy the file into the Drafts area
    	let strScript = `#!/bin/zsh
    	cp "${p_strDestinationPath}" "$HOME/Library/Mobile Documents/iCloud~com~agiletortoise~Drafts5/Documents/${strTempFilePath}"`
    	let shScript = ShellScript.create(strScript);
    
    	// Run the script
    	if (shScript.execute([]))
    	{
    		// Initialise the file manager
    		let fmLocal = FileManager.createCloud();
    
    		// Read the content of the file
    		let strOriginal = fmLocal.readString("/" + strTempFilePath);
    
    		// Overwrite the content of the file, prepending the new content
    		fmLocal.writeString("/" + strTempFilePath, p_strContent + "\n" + strOriginal);
    
    		// Set up a shell script to move the file out of the Drafts area
    		let strScript = `#!/bin/zsh
    		mv "$HOME/Library/Mobile Documents/iCloud~com~agiletortoise~Drafts5/Documents/${strTempFilePath}" "${p_strDestinationPath}"
    		`;
    		let shScript = ShellScript.create(strScript);
    
    		// Run the script
    		if (shScript.execute([]))
    		{
    			app.displayInfoMessage("File Updated");
    			return true;
    		}
    		else
    		{
    			app.displayErrorMessage("Error: " + shScript.standardError);
    			console.log(shScript.standardError);
    			return false;
    		}
    	}
    	else
    	{
    		app.displayErrorMessage("Error: " + shScript.standardError);
    		console.log(shScript.standardError);
    		return false;
    	}
    }
    
    // Save draft content to the specified file
    macPrepend(draft.getTemplateTag("PATH"), draft.content);
    

Options

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