Action

Post Jekyll blog entry to Github repository

Posted by Joshua Oliphant, Last update 10 months ago

Drafts to GitHub Action

This repository contains a Drafts app action script that automates the process of posting content directly to a GitHub repository, specifically designed for Jekyll or other static site generators that use Markdown files in a _posts directory.

Features

  • Automatically formats Draft content into a Markdown file.
  • Configures file naming based on the title and date.
  • Posts content to your specified GitHub repository.
  • Uses Drafts’ Credentials for secure handling of GitHub authentication details.

Prerequisites

Before using this action, ensure you have:

  • The Drafts app installed on your device.
  • A GitHub account and a repository where you want to post your drafts.
  • A Personal Access Token (PAT) from GitHub with repo scope permissions.

Setup

  1. Generate a Personal Access Token (PAT) on GitHub:

    • Go to your GitHub account settings.
    • Navigate to Developer settings > Personal access tokens.
    • Generate a new token with repo scope.
    • Copy the generated token for later use.
  2. Add the Action to Drafts:

    • Create a new action in Drafts.
    • Paste the provided script into the action’s script step.
  3. Configure the Credential:

    • The first time you run the action, Drafts will prompt you to enter your GitHub details:
      • Username: Your GitHub username.
      • Personal Access Token: The PAT you generated.
      • Repository Name: The name of the GitHub repository where you want to post.
      • Email Address: The email associated with your GitHub account (used for commit info).

Usage

  1. Write your draft in Markdown format. The first line should be the title, prefixed with # (Markdown syntax for a heading).
  2. Run the action you created.
  3. If successful, the content will be posted to your GitHub repository in the _posts directory, named according to the draft’s title and date.

Troubleshooting

  • Authentication Errors: Ensure your PAT is correct and has the necessary permissions.
  • HTTP Errors: Check the console log in Drafts for detailed error messages. Common issues include incorrect repository names or network issues.

Contributing

Contributions to this script are welcome! Please submit pull requests or issues on GitHub to suggest improvements or report bugs.

License

This script is released under MIT License.

Acknowledgements

  • Thanks to all contributors and users for feedback and suggestions.
  • Drafts app for providing a powerful scripting environment.

Steps

  • script

    // Create a GitHub credential
    
    let githubCredential = Credential.create("GitHub", "Enter your GitHub details for posting to your repository.");
    
    githubCredential.addTextField("username", "Username");
    
    githubCredential.addPasswordField("token", "Personal Access Token");
    
    githubCredential.addTextField("repoName", "Repository Name");
    
    githubCredential.addTextField("email", "Email Address");
    
      
    
    // Prompt the user for credentials if not already saved
    
    if (!githubCredential.authorize()) {
    
    console.log("Authorization failed or was cancelled by the user.");
    
    context.fail();
    
    }
    
      
    
    // Extract details from the credentials
    
    const username = githubCredential.getValue("username");
    
    const token = githubCredential.getValue("token");
    
    const repoName = githubCredential.getValue("repoName");
    
    const email = githubCredential.getValue("email");
    
      
    
    // Prepare your post content
    
    const title = draft.content.split("\n")[0].replace('# ', ''); // Assuming the first line of the draft is the title
    
    const date = new Date().toISOString().split('T')[0];
    
    const slug = title.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '').replace(/\-\-+/g, '-').trim('-');
    
    const fileName = `${date}-${slug}.md`;
    
    const fullContent = draft.content; // Here you might format your draft content as needed
    
    const encodedContent = Base64.encode(fullContent);
    
      
    
    // Setup for the GitHub API request
    
    const path = `_posts/${fileName}`;
    
    const apiUrl = `https://api.github.com/repos/${username}/${repoName}/contents/${path}`;
    
      
    
    data = {
    
    owner: `${username}`,
    
    repo: `${repoName}`,
    
    path: `${path}`,
    
    message: 'Send from Drafts',
    
    committer: {
    
    name: `${username}`,
    
    email: `${email}`
    
    },
    
    content: encodedContent
    
    }
    
      
    
    // Create the HTTP request
    
    let http = HTTP.create();
    
    let response = http.request({
    
    "url": apiUrl,
    
    "method": "PUT",
    
    "headers": {
    
    "Authorization": `Bearer ${token}`,
    
    "User-Agent": "DraftsApp",
    
    "Content-Type": "application/json",
    
    'X-GitHub-Api-Version': '2022-11-28'
    
    },
    
    "data": data
    
    });
    
      
    
    // Process the response
    
    if (response.statusCode === 200 || response.statusCode === 201) {
    
    console.log("Successfully created/updated the file on GitHub.");
    
    } else {
    
    console.log("Failed to post to GitHub. Status code: " + response.statusCode + " Response: " + response.responseText);
    
    }

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.