Setup Rustlings
lessonDuration 1m 44sFree
Set up for Rust exercises.
Browse
Find courses, lessons, articles, talks, and podcasts.
182 resources
Showing 1–24 · Page 1 of 8
lessonDuration 1m 44sFree
Set up for Rust exercises.
lessonDuration 1m 30s
We scaffold out a Netlify function in a new directory and access it via curl and the browser.
lessonDuration 4m 5s
To make our opengraph image generation function, we'll have to work out a way to pass the querystring variables from the original URL through to the React script running inside the headless browser. We choose to set them on the window using another injected script, and we also cover handling URL decoding of querystring components.
lessonDuration 58s
Netlify functions are shipped at .netlify/functions/<function-name>. Our users will want a shorter, more memorable URL, so let's give that to them using redirects. This redirect also lets us swap our our function at any time so that users aren't writing the direct path to the function into their production sites.
lessonDuration 7m 32s
Every time we hit our function it runs the headless browser and regenerates the image. We can fix this by using Cloudinary as a write-through cache in front of our Netlify opengraph image generation function. If the image exists, Cloudinary will return it, if not it will ask our function to generate it, then cache it.
lessonDuration 1m 38s
The twitter card validator is useful for testing opengraph meta tags. Sometimes it doesn't show up exactly right and we use actual tweets to test the real resolution.
lessonDuration 22s
When taking screenshots, it's important that the browser is big enough to show all of the content in the DOM that we want to screenshot. We can do this by setting the viewport.
lessonDuration 5m 43s
We take the opengraph image we wrote in codesandbox and copy it into our serverless function. We use Rollup to compile the component into an IIFE (immediately invoked function expression) that can run in our headless browser environment and cover a wide set of rollup plugins that we need for compatibility. We end the lesson having successfully screenshot our opengraph react component from our Netlify Function **Note**: Due to Netlify changing their handling, the path in `fs.readFileSync` is affected. Update to: ```js const script = fs.readFileSync(path.resolve(__dirname, "image.js"), "utf-8"); ```
lessonDuration 4m 59s
We cover installing Playwright, which will run the headless browser for us, in a way that doesn't also install unused browser bundles, reducing the size and allowing us to deploy it to netlify in a function. We also cover a set of Playwright APIs like page.setContent, page.evaluate, page.screenshot, and how to return a base64 encoded image from a lambda function. We also cover passing values from native browser functions like getBoundingClientRect back to our node script and fixing a few errors along the way.
lessonDuration 2m 47s
We scaffold out a new GitHub repo to deploy netlify functions and a small index.html file, while covering Makefile basics and netlify.toml. The lesson ends with a working Netlify site.
lessonDuration 12m 26s
We build a React component that implements our Figma design with the intent of creating screenshots in a headless browser later. We use Emotion, a CSS-in-JS library, Flexbox, and React Textfit to build a scalable OpenGraph image. We cover using complex CSS selectors with multiple pseudo-selectors as well as common Flexbox layout techniques such as space-between. * [Our Gradient](https://www.gradientmagic.com/collection/angular/gradient/1559907993739)
lessonDuration 11m 44sFree
Figma is a web-based collaborative interface design tool that we can use to prototype the look and feel of our OpenGraph cards. We dive into a few of the basic features using [Ryan Warner's](https://twitter.com/ryanwarnercodes) community [social branding templates](https://twitter.com/ryanwarnercodes/status/1239578329340170240), such as text placement, using the eyedropper and color tools, as well as pulling in gradients as images to fit our working area. * [Social Branding Template](https://www.figma.com/community/file/820337605519256142) * [Gradient Magic](https://www.gradientmagic.com/)
lessonDuration 6m 58s
We have been ignoring implementing tests for the write subcommand. Now is the time that we'll test the command we have been building. We'll build out a fake editor script that our test will use to check if the command is functioning properly. We will then use `arg` to build the command as we would normally use it ourselves. After writing the test, we'll see how to clean up after ourselves so that we aren't leaving testing artifacts leftover just from running a test. --- How to integration test a cargo binary that calls out to `EDITOR` for modifications and asks the user for input. First we'll create a fake editor script to use instead of vim, etc. `tests/fake_editor.sh` is a one-liner. ```shell echo "testing" >> $1; ``` Then we'll write our test using `assert_cmd` to build up a `Command` that points to the `garden` binary in out `Cargo.toml`. We grab the fake editor path script using `std::env::current_dir()`, make sure the file exists (which means we've grabbed the right path), and spawn a new `Command` with the `EDITOR` variable set to the fake editor script. The equivalent call to our bin is ```shell EDITOR=path/to/fake-editor.sh garden write -t atitle ``` And the rust code to execute. ```rust fn test_write_with_title() { let mut cmd = Command::cargo_bin("garden").unwrap(); let fake_editor_path = std::env::current_dir() .expect("expect to be in a dir") .join("tests") .join("fake-editor.sh"); if !fake_editor_path.exists() { panic!( "fake editor shell script could not be found" ) } let assert = cmd .env("EDITOR", fake_editor_path.into_os_string()) .arg("write") .arg("-t") .arg("atitle") .write_stdin("N\n".as_bytes()) .assert(); assert.success(); } ``` Note that we're asserting that the command exited sucessfully, and that we're inputing `N\n` to the bin's stdin, which responds to a request for user input after the editor closes. Note that this doesn't actually test for the resulting file existence, and also that we're writing our files out directly into our default digital garden! We can solve this with `assert_fs` and `predicates`. We'll bring in both preludes (a prelude is a bunch of stuff the library author thinks will be useful to have around all the time) and create a new temporary directory. We'll use the `GARDEN_PATH` environment variable to pass the temporary directory in to the `garden` bin and that's it, we've added a temporary directory to our test. No more polluting the default garden! ```rust use assert_fs::prelude::*; use predicates::prelude::*; fn test_write_with_title() { let temp_dir = assert_fs::TempDir::new().unwrap(); let mut cmd = Command::cargo_bin("garden").unwrap(); let fake_editor_path = std::env::current_dir() .expect("expect to be in a dir") .join("tests") .join("fake-editor.sh"); if !fake_editor_path.exists() { panic!( "fake editor shell script could not be found" ) } let assert = cmd .env("EDITOR", fake_editor_path.into_os_string()) .env("GARDEN_PATH", temp_dir.path()) .arg("write") .arg("-t") .arg("atitle") .write_stdin("N\n".as_bytes()) .assert(); assert.success(); temp_dir .child("atitle.md") .assert(predicate::path::exists()); } ``` Now that's enough, but we can also check to make sure the file we expect to exist actually exists. `temp_dir.child` gives us the possible file, and we can assert on that file with a test from `predicates` that tests to make sure the file exists. ```rust temp_dir .child("atitle.md") .assert(predicate::path::exists()); ```
lessonDuration 7m 47s
What user experience do we want for the act of writing? We have a few options, including letting users write directly in the console or giving them a prepared file that they can then open and write in. Writing directly in the console doesn't give a user access to their text editor of choice. Which means lacking autocomplete, syntax highlighting, snippets, and other functionality. Creating a file and handling the path back to the user doesn't quite work for us either, as that reduces the utility of the garden write command to the equivalent of running `touch filename.md`. So for our use case, we'd ideally like to open the user's preferred editing environment, whatever that happens to be, then wait for them to be done with the file before continuing. Since we're working with a CLI tool, we can safely assume that our users either know how to, or are willingly to learn how to, set environment variables. This means we can use the `EDITOR` variable to select an editor to use. This is the same way `git commit` works. --- In Rust, there is a crate that handles not only `EDITOR`, but also various fallbacks per-platform. We'll take advantage of [edit](https://crates.io/crates/edit) to call out to the user's choice of editor. The quick usage of edit allows us to call the `edit::edit` function, and get the user's data. ```rust pub fn write(garden_path: PathBuf, title: Option<String>) -> Result<()> { dbg!(garden_path, title); let template = "# "; let content_from_user = edit::edit(template).wrap_err("unable to read writing")?; dbg!(content_from_user); todo!() } ``` This results in a filename that looks like: `.tmpBy0Yun` "somewhere else" on the filesystem, in a location the user would never reasonably find it. Ideally, if anything went wrong, the user would be able to take a look at the in-progress tempfile they were just working on, which should be in an easily discoverable place like the garden path. *We don't want to lose a user's work.* Additionally, the tempfile doesn't have a file extension, which means that the user's editor will be less likely to recognize it as a markdown file, so we want to add `.md` to the filepath. ```rust use color_eyre::{eyre::WrapErr, Result}; use edit::{edit_file, Builder}; use std::io::{Read, Write}; use std::path::PathBuf; const TEMPLATE: &[u8; 2] = b"# "; pub fn write(garden_path: PathBuf, title: Option<String>) -> Result<()> { let (mut file, filepath) = Builder::new() .suffix(".md") .rand_bytes(5) .tempfile_in(&garden_path) .wrap_err("Failed to create wip file")? .keep() .wrap_err("Failed to keep tempfile")?; file.write_all(TEMPLATE)?; // let the user write whatever they want in their favorite editor // before returning to the cli and finishing up edit_file(filepath)?; // Read the user's changes back from the file into a string let mut contents = String::new(); file.read_to_string(&mut contents)?; dbg!(contents); todo!() } ``` We will use the `edit::Builder` API to generate a random tempfile to let the user write content into. The suffix is going to be `.md` and the filename will be 5 random bytes. We also put the tempfile in the garden path, which ensures a user will be able to find it if necessary. `wrap_err` (which requires the `eyre::WrapErr` trait in scope) wraps the potential error resulting from these calls with additional context, making the original error the source, and we can keep chaining after that. We `keep` the tempfile, which would otherwise be deleted when all handles closed, because if anything goes wrong after the user inputs data, we want to make sure we don't lose that data. After the file is created, we write our template out to the file before passing control to the user. This requires the `std::io::Write` trait in scope. We use a const for the file template because it won't change. To make the `TEMPLATE` a const, we also need to give it a type, which is a two element byte array. Change the string to see how the byte array length is checked at compile time. Since we have access to the `file` already, we can read the contents back into a string after the user is done editing. This requires having the `std::io::Read` trait in scope. And now we've let the user write into a file which will stick around as long as we need it to, and importantly will stick around if any errors happen in the execution of the program, so we lose no user data and can remove the temporary file at the end of the program ourselves if all goes well.
lessonDuration 4m 13s
The StructOpt crate allows us to derive our human person functionality from our Struct definitions. We will create a `structop` for our `write` subcommand that will take a short and long flag for our `title` argument --- ``` cargo add structopt ``` structopt allows us to derive argument parsing functionality from our structs. The name is a play on `struct Opt {}`. To do this we need to `derive(StructOpt)` on our struct. In this case we have a subcommand, so we'll set up one of the fields on the `Opt` struct to be a `structopt(subcommand)`. This subcommand value will be an enum, indicating that only one subcommand can be used at a time. structopt also gives us tools to specify one of three argument types: * positional * short * long By default every argument is a positional argument, which means that in this case if we left it as-is, the CLI would function as ``` garden write my-title ``` We want to use a flag, so we'll use structopt to generate short and long flags for the title argument with `structopt(short, long)`. That gives the use the option of `-t` and `--title` to specify a title. structopt also contains some type processing, so all we need to do is specify that title is an optional string and the flags will become optional. That is: a user can specify or not specify a title. ```rust struct Opt { #[structopt(subcommand)] cmd: Command, } enum Command { Write { #[structopt(short, long)] title: Option<String>, }, } ``` After setting up `struct Opt`, we can parse the args and use the dbg!() macro to print them to the console so we can see what they look like. ```rust let opt = Opt::from_args(); dbg!(opt); ``` To do that we also need to `derive(Debug)` in addition to structopt on both the enum and the struct. Given input like ``` garden write ``` We will see the following output. ```rust [src/main.rs:21] opt = Opt { cmd: Write { title: None, }, } ``` We can choose to `cargo build` and then `./target/debug/garden write` or we can use `cargo run -- write`. The `--` ensures that our arguments get passed to the CLI we're building and not `cargo run`. This is especially relevant when passing something like `--help`.
lessonDuration 3m 50s
Right now we are using the `todo!()` macro which is great for simulating when our program panics. The error message that we get can be improved upon. We will look at color-eyre that will allow us to handle the errors we receive to be more visual and human-readable. --- The `todo!` macro is useful and it also exposes what happens if our application panics. ``` thread 'main' panicked at 'not yet implemented', src/main.rs:2:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` This could be both more readable and contain more information while also being colored using [color_eyre](https://docs.rs/color-eyre/0.5.10/color_eyre/). ``` The application panicked (crashed). Message: not yet implemented Location: src/main.rs:5 Backtrace omitted. Run with RUST_BACKTRACE=1 environment variable to display it. Run with RUST_BACKTRACE=full to include source snippets. ``` We'll use [cargo-edit](https://crates.io/crates/cargo-edit) to add the package to our Cargo.toml. ``` cargo install cargo-edit cargo add color_eyre ``` `main` can return `Result`, so we'll use `color_eyre`'s `Result` as our return value and `color_eyre::install` to install the default panic and error reporting hooks. `install` returns a `Result` so we can use `?` to handle any errors if necessary. We haven't shown off everything that color_eyre is capable of. In addition to panic handling, color_eyre allows us to track additional information in the context of our errors and include suggestions by taking advantage of distributed [tracing](https://github.com/tokio-rs/tracing) infrastructure. We'll see more of how this helps as we build out the CLI.
lessonDuration 3m 53s
In our subcommand match we'll add a new function called `write` to handle our `Write` subcommand. We'll pass it the argument title and we'll "import" it from a library called `digital_garden`. ```rust use digital_garden::write; fn main() -> Result<()> { color_eyre::install()?; let opt = Opt::from_args(); dbg!(&opt); match opt.cmd { Command::Write { title } => write(title), } } ``` To create this library, add a new section in `Cargo.toml`. We can give our library a name and set which file to treat as the entrypoint. `src/lib.rs` is the default file for a library crate, but we can also be explicit about what we want to happen. ```toml [lib] name = "digital_garden" path = "src/lib.rs" ``` This leaves us with two crates, a binary crate, of which we can have any amount, and a library crate, of which we can only have 0 or 1. We'll create the `src/lib.rs` file with the following contents. ```rust mod write; pub use write::write; ``` Rust's module system is explicit, so when we write `mod write`, we are saying that the library `digital_garden` has a module `write`, such that the path to the module is `digital_garden::write`. In our case `digital_garden::write` corresponds to a file at `src/write.rs`. Secondly, the `pub use write::write` says that we have a function called `write` in the module called `write` and that the function will be exposed from lib publicly, so people who have the `digital_garden` library installed will be able to use the write function as `digital_garden::write`. In JavaScript the closest analogue is exporting a function from another file that exports it. ```js export { write } from './write.js'; ``` By using use, we're shortening the public path to the write function. A private module "write" with a function "write" also exists at `digital_garden::write::write`. If you try to use this path, Rust will tell you there is a private module there. Finally, in `src/write.rs`, we can write a public function that matches the return type of our main function, since we're using it as the return value from our match function. We'll accept an `Option<String>` as an argument as well, since that's what we expect from the cli arguments. ```rust use color_eyre::Result; pub fn write(_title: Option<String>) -> Result<()> { todo!() } ``` The purpose of creating this module path is because we know that we're going to set up more modules for each subcommand in the future, and we can control both the placement of our code on disk, as well as the path users will interact with to use our module.
lessonDuration 7m 51s
Given the potential `document_title` we now want to ask the user if the title is still what they want to use so that we can write the file to disk. This will involve two paths depending on if we have an existing potential option or not. We will need to use `ask_for_filename` in `confirm_filename`, so we'll write that branch first. ```rust let filename = match document_title { Some(raw_title) => { // confirm_filename()? todo!() } None => ask_for_filename(), }; ``` `rprompt` allows us to ask for a small amount of input from the user (compared to the much larger input possible by passing control to the user's editor). We'll use `rprompt::prompt_reply_stderr` to get a response from the user, and `.wrap_err` to add context to the error if anything goes wrong. ```rust fn ask_for_filename() -> Result<String> { rprompt::prompt_reply_stderr( "\ Enter filename > ", ) .wrap_err("Failed to get filename") } ``` We'll use the same behavior for the first part of `confirm_filename`. We'll also need to use our first lifetime to account for the shared reference argument. `match` can match against multiple values for the same branch, so we'll take advantage of that to handle branches for Ns and Ys, as well as the default case. If anything goes wrong, such as someone inputting an "a", we'll fall through using `loop` and ask again until we get a usable answer ```rust fn confirm_filename(raw_title: &str) -> Result<String> { loop { // prompt defaults to uppercase character in question // this is a convention, not a requirement enforced by // the code let result = rprompt::prompt_reply_stderr(&format!( "\ current title: `{}` Do you want a different title? (y/N): ", raw_title, )) .wrap_err("Failed to get input for y/n question")?; match result.as_str() { "y" | "Y" => break ask_for_filename(), "n" | "N" | "" => { // the capital N in the prompt means "default", // so we handle "" as input here break Ok(slug::slugify(raw_title)); } _ => { // ask again because something went wrong } }; } } ``` While filenames can technically have spaces in them, we're going to slugify our filenames like urls for a few reasons. One is that when starting out, many programmers fail to quote filename arguments in their bash scripts, which results in filenames with spaces being treated as separate arguments. Another is that this is a digital garden CLI, and digital gardens are often stored in git, accessed from multiple file systems, as well as from URLs. While strictly speaking we don't need to slugify our filenames, we will here so as to adhere to a safer set of characters. ``` cargo add slug ``` We'll map over the `Result` from `rprompt` which allows us to operate on the internal value if it's `Ok`. ```rust fn ask_for_filename() -> Result<String> { rprompt::prompt_reply_stderr( "\ Enter filename > ", ) .wrap_err("Failed to get filename") .map(|title| slug::slugify(title)) } ``` We'll also use slugify in `confirm_filename` ```rust match result.as_str() { "y" | "Y" => break ask_for_filename(), "n" | "N" | "" => { // the capital N in the prompt means "default", // so we handle "" as input here break Ok(slug::slugify(raw_title)); } _ => { // ask again because something went wrong } }; ``` The fact that `confirm_filename` and `ask_for_filename` have the same return type is important because the branches of a `match` need to return the same type.
lessonDuration 2m 29sFree
By writing the README first we can explore different approaches to the user experience of our CLI. We could think through the entire CLI right now, but we'll leave other subcommands for later. Instead, we'll focus on the fact that we know we will have multiple subcommands and design the command on which all others rely: `write`. We can come up with a first example subcommand. Note that by doing this we are also defining the name of the binary as `garden`. ```shell garden write ``` When writing, users will not necessarily know the title of what they're writing in advance, so we will not require them to provide it. This leads us to an optional title argument. We could have chosen to make this a positional argument, but we made it a flag instead to delineate from other potential future positional arguments (such as `--message`, which we have chosen not to implement now). ```shell garden write -t "Writing about Rust" ```
course
In this course, Chris takes a README-driven approach to build out a Rust CLI that supports content authoring for a digital garden. Specifically, you'll work through the first command for the CLI, writing files. You start by initializing a new Cargo binary crate through creating the `write` command that allows you to create files (and their contents) to the folder that you set. Step by step you'll learn about: - Handling user input - Error handling - Rust Move semantics - Rust Copy semantics - Integration testing ...and more!
lessonDuration 3m 8s
While we have `test_write_with_title` which tests the garden CLI with a given title flag, we can also set up additional tests, such as for using a written title in the document for the filename. Copy/pasting the code from test one into test two is a lot of duplication, and setting up the fake editor isn't going to change across tests, so let's abstract the creation of the temporary directory, the fake editor script path, and the `Command` itself into a utility function. The port is relatively straightforward, with the only changes being that we cut off the `cmd` modifications before the `.arg` calls, and now have to return the `cmd` and the `temp_dir` in a tuple. We return the actual `Command` and `TempDir`, yielding ownership to the calling function because we have no further use for them here, but the calling function will need to mutate the `Command` more, and use `TempDir` to test. ```rust fn setup_command() -> (Command, assert_fs::TempDir) { let temp_dir = assert_fs::TempDir::new().unwrap(); let mut cmd = Command::cargo_bin("garden").unwrap(); let fake_editor_path = std::env::current_dir() .expect("expect to be in a dir") .join("tests") .join("fake-editor.sh"); if !fake_editor_path.exists() { panic!( "fake editor shell script could not be found" ) } cmd.env("EDITOR", fake_editor_path.into_os_string()) .env("GARDEN_PATH", temp_dir.path()); (cmd, temp_dir) } ``` The new write tests are considerably shorter now and focus mostly on which subcommand to call, and what the user interaction with that subcommand is. ```rust fn test_write_with_title() { let (mut cmd, temp_dir) = setup_command(); let assert = cmd .arg("write") .arg("-t") .arg("atitle") .write_stdin("N\n".as_bytes()) .assert(); assert.success(); temp_dir .child("atitle.md") .assert(predicate::path::exists()); } fn test_write_with_written_title() { let (mut cmd, temp_dir) = setup_command(); let assert = cmd .arg("write") .write_stdin("N\n".as_bytes()) .assert(); assert.success(); temp_dir .child("testing.md") .assert(predicate::path::exists()); } ```
lessonDuration 2m 27s
We can print lines to the terminal and ask the user for various input. So let's make the interface a bit more usable by using colored output. We can do this by bringing an extension trait for formatting into scope: `OwoColorize`. Extension traits are one-off traits that are used to add functions to a type that our crate doesn't own. A crate can create the new trait, then implement the functions defined by that trait on a type the crate doesn't own and if we bring that trait into scope, the type will get the extra functions. In this case, `OwoColorize` is used for adding color functions to formatters like Display and Debug. We'll start with `ask_for_filename` ```rust use color_eyre::owo_colors::OwoColorize; fn ask_for_filename() -> Result<String> { rprompt::prompt_reply_stderr(&format!( "{}", "\ Enter filename > " .blue() .bold(), )) .wrap_err("Failed to get filename") .map(|title| slug::slugify(title)) } ``` In `confirm_filename` we can use multiple formatters to get different colors: ```rust let result = rprompt::prompt_reply_stderr(&format!( "\ {} {} Do you want a different title? (y/N): ", "current title:".green().bold(), raw_title, )) .wrap_err("Failed to get input for y/n question")?; ```
lessonDuration 5m 46s
`PathBuf` lets us check to see if a file exists before writing to it, so we can take advantage of that to make sure that we don't overwrite a file that already exists, even if the user has indicated a title that would overwrite another file. ``` let mut i: usize = 0; loop { let dest_filename = format!( "{}{}", filename, if i == 0 { "".to_string() } else { i.to_string() } ); let mut dest = garden_path.join(dest_filename); dest.set_extension("md"); if dest.exists() { i = i + 1; } else { fs::rename(garden_tmpfile, &dest)?; break; } } ```
lessonDuration 6m 29s
We want to build out functionality to let the user write into a file in their garden. To do that, we have to know the location of their garden. We'll start by implementing a function to get the default garden path. ```rust fn get_default_garden_dir() -> Result<PathBuf> { let user_dirs = UserDirs::new().ok_or_else(|| eyre!("Could not find home directory"))?; Ok(user_dirs.home_dir().join(".garden")) } ``` This uses the user's system directories via the `directories` crate to find their home dir. We then add `.garden` to the home dir for the default garden. Ideally, we would want the user to be able to specify their garden path. Using structopt, we can let them specify it as a short, long, or env var. In our README, we'll specify how this should work. ```` ```shell GARDEN_PATH=~/github/my-digital-garden garden write garden -p ~/github/my-digital-garden write garden --garden_path ~/github/my-digital-garden write ``` ```` And in our `Opt` struct, we can tell structopt how to handle it. Putting this in our `Opt` struct instead of our `Command` enum make it a global flag that can be specified for all subcommands. ```rust struct Opt { #[structopt(parse(from_os_str), short = "p", long, env)] garden_path: Option<PathBuf>, #[structopt(subcommand)] cmd: Command, } ``` structopt is only handling the user input, so in `main()` we still need to fall back to the default if the `garden_path` is not specified. ```rust let garden_path = match opt.garden_path { Some(pathbuf) => Ok(pathbuf), None => get_default_garden_dir().wrap_err("`garden_path` was not supplied"), }?; ``` if we force an `Err` in `get_default_garden_dir` We can see how the wrapped errors end up stacking. ``` Error: 0: `garden_path` was not supplied 1: Could not find home directory ``` We'll also change the signature of `write` to accept the pathbuf. ``` Command::Write { title } => write(garden_path, title), ``` Note that we need to import `PathBuf`. We can also `dbg!` the garden path and title to see their values. ```rust use std::path::PathBuf; pub fn write(garden_path: PathBuf, title: Option<String>) -> Result<()> { dbg!(garden_path, title); todo!() } ```