-
Notifications
You must be signed in to change notification settings - Fork 5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
WIP: External code snippets and example code #81
Draft
flaki
wants to merge
2
commits into
main
Choose a base branch
from
flaki/29-code-examples
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
node_modules |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
const visit = require('unist-util-visit'); | ||
const { join, dirname } = require('path'); | ||
const CACHEDIR = join(__dirname, '../.cache'); | ||
const { mkdir } = require('fs'); | ||
const fetch = require('node-fetch') | ||
|
||
const plugin = (options) => { | ||
const transformer = async (ast, vfile) => { | ||
//DEBUG: | ||
//if (vfile.path.includes('test.md')) console.log(ast) | ||
|
||
const cblocks = [] | ||
const assets = [] | ||
|
||
// Collect all (relevant) codeblocks | ||
visit(ast, 'code', async (node) => { | ||
// In this extension we repurpose the language hint for a source URL | ||
// Code blocks that need their URL cached & replaced with the correct imports: | ||
if (node.lang?.startsWith('http://') || node.lang?.startsWith('https://')) { | ||
cblocks.push(node) | ||
} | ||
}); | ||
|
||
//DEBUG: | ||
//if (cblocks.length) console.log(cblocks) | ||
|
||
// We run the changes outside of the visitor because the visitor does not support callbacks | ||
for (const node of cblocks) { | ||
const url = node.lang; | ||
const lang = await detectLang(url); | ||
const file = await cachedFile(url); | ||
node.lang = lang | ||
assets.push(file.path) | ||
const assetId = assets.length-1 | ||
|
||
// TODO: decide whether to use asset imports & external files or embedded content | ||
node.value = `/* ${url} {__externalCodeSnippet${assetId}} */\n` + file.contents; | ||
} | ||
|
||
//DEBUG: | ||
//if (cblocks.length) console.log(cblocks, assets) | ||
}; | ||
return transformer; | ||
}; | ||
|
||
module.exports = plugin; | ||
|
||
|
||
async function detectLang(url) { | ||
//TODO: | ||
return 'rust' | ||
} | ||
|
||
async function cachedFile(url) { | ||
// Convert the URL into a cache path | ||
const path = cachePath(url); | ||
if (!path) { | ||
return `/* ERROR: could not cache file: ${url} */` | ||
} | ||
// TODO: maybe we want to have a whitelist for allowed paths? | ||
// E.g. limit to https://raw.githubusercontent.com/suborbital/** | ||
|
||
// <check if file is already cached at p> | ||
|
||
// TODO: handle request errors | ||
const contents = await fetch(url).then(r => r.text()); | ||
|
||
// <ensure recursively mkdir(dirname(p)) | ||
// <cache file contents at p> | ||
|
||
// Return both path and contents | ||
return { path, contents } | ||
} | ||
|
||
function cachePath(url) { | ||
const p = (/https?:\/\/(.*)/.exec(url) ?? [])[1]; | ||
if (!p) { | ||
console.error('Cache path invalid!'); | ||
return void 0; | ||
} | ||
|
||
return join(CACHEDIR, p); | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
{ | ||
"name": "codeblocks", | ||
"version": "1.0.0", | ||
"description": "", | ||
"main": "index.js", | ||
"scripts": { | ||
"test": "echo \"Error: no test specified\" && exit 1" | ||
}, | ||
"author": "", | ||
"license": "ISC", | ||
"dependencies": { | ||
"node-fetch": "^2.6.7", | ||
"unist-util-visit": "^2.0.1" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
name: fetch | ||
namespace: default | ||
lang: rust | ||
apiVersion: 0.2.5 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
[package] | ||
name = "fetch" | ||
version = "0.1.0" | ||
authors = ["Suborbital Runnable <info@suborbital.dev>"] | ||
edition = "2018" | ||
|
||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | ||
|
||
[lib] | ||
crate-type = ["cdylib", "rlib"] | ||
|
||
[dependencies] | ||
suborbital = { path = "../../../api/rust/core" } |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
use suborbital::runnable::*; | ||
use suborbital::http; | ||
use suborbital::util; | ||
use suborbital::log; | ||
use std::collections::BTreeMap; | ||
|
||
struct Fetch{} | ||
|
||
impl Runnable for Fetch { | ||
fn run(&self, input: Vec<u8>) -> Result<Vec<u8>, RunErr> { | ||
let url = util::to_string(input); | ||
|
||
let _ = match http::get(url.as_str(), None) { | ||
Ok(res) => res, | ||
Err(e) => return Err(RunErr::new(1, e.message.as_str())) | ||
}; | ||
|
||
// test sending a POST request with headers and a body | ||
let mut headers = BTreeMap::new(); | ||
headers.insert("Content-Type", "application/json"); | ||
headers.insert("X-ATMO-TEST", "testvalgoeshere"); | ||
|
||
let body = String::from("{\"message\": \"testing the echo!\"}").as_bytes().to_vec(); | ||
|
||
match http::post("https://postman-echo.com/post", Some(body), Some(headers)) { | ||
Ok(res) => { | ||
log::info(util::to_string(res.clone()).as_str()); | ||
Ok(res) | ||
}, | ||
Err(e) => Err(RunErr::new(1, e.message.as_str())) | ||
} | ||
} | ||
} | ||
|
||
|
||
// initialize the runner, do not edit below // | ||
static RUNNABLE: &Fetch = &Fetch{}; | ||
|
||
#[no_mangle] | ||
pub extern fn _start() { | ||
use_runnable(RUNNABLE); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This looks very exciting!
I would love to try and use it, but am running into bumps. Would it be helpful to have a handler and curl request example, too?
Or maybe make this a part of a greater sample project?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah sorry, I just used this as an example, haven't tried if it actually worked -- just pulled it out of the
rwasm-testdata
🙈