Screenshots of live websites. Minimal interface, powerful engine.
Prepare for open source
Bridger Tower544c269e25e2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..3185492--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,19 @@+name: CI++on:+ push:+ branches: [main]+ pull_request:++jobs:+ check:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: dtolnay/rust-toolchain@stable+ with:+ components: rustfmt, clippy+ - uses: Swatinem/rust-cache@v2+ - run: cargo fmt --check+ - run: cargo clippy -- -D warnings+ - run: cargo builddiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..45250ab--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,46 @@+name: Release++on:+ push:+ tags: ["v*"]++permissions:+ contents: write++jobs:+ build:+ strategy:+ matrix:+ include:+ - target: aarch64-apple-darwin+ runner: macos-latest+ - target: x86_64-apple-darwin+ runner: macos-13+ - target: x86_64-unknown-linux-musl+ runner: ubuntu-latest+ runs-on: ${{ matrix.runner }}+ steps:+ - uses: actions/checkout@v4+ - uses: dtolnay/rust-toolchain@stable+ with:+ targets: ${{ matrix.target }}+ - if: contains(matrix.target, 'musl')+ run: sudo apt-get update && sudo apt-get install -y musl-tools+ - run: cargo build --release --target ${{ matrix.target }}+ - run: tar -C target/${{ matrix.target }}/release -czf snap-${{ matrix.target }}.tar.gz snap+ - uses: actions/upload-artifact@v4+ with:+ name: snap-${{ matrix.target }}+ path: snap-${{ matrix.target }}.tar.gz++ release:+ needs: build+ runs-on: ubuntu-latest+ steps:+ - uses: actions/download-artifact@v4+ with:+ merge-multiple: true+ - uses: softprops/action-gh-release@v2+ with:+ files: snap-*.tar.gz+ generate_release_notes: truediff --git a/Cargo.toml b/Cargo.tomlindex 878ac7f..0d75218 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -2,7 +2,13 @@name = "snap"version = "0.1.0"edition = "2024"+rust-version = "1.85"description = "Minimal, powerful screenshots of live websites"+license = "MIT"+repository = "https://github.com/brijr/snap"+readme = "README.md"+keywords = ["screenshot", "cli", "chrome", "headless", "web"]+categories = ["command-line-utilities"][dependencies]anyhow = "1"diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..cd1af03--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Bridger Tower++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdindex 5a1d009..530fad2 100644--- a/README.md+++ b/README.md@@ -11,13 +11,28 @@ cat urls.txt | snap - -o shots/ # batch from stdin (# comments ok)snap -o hero.jpg --wait-for 'h1' app.dev```+## Install++```+curl -fsSL https://raw.githubusercontent.com/brijr/snap/main/install.sh | sh+```++Or with a Rust toolchain:++```+cargo install --git https://github.com/brijr/snap+```++The only runtime dependency is an installed Chrome-family browser (Chrome, Chromium, Edge, or Brave).+## What it does for you-- Renders with your real installed Chrome (or Chromium/Edge/Brave), driven over the DevTools Protocol+- Renders with your real installed Chrome, driven over the DevTools Protocol- Waits for fonts, paint frames, and — on `--full` — scroll-triggers lazy-loaded content before capturing- Retina `@2x` output by default; full pages taller than Chrome's ~16k px render limit fall back to `@1x` automatically (the report tells you which you got)-- Image format inferred from the `-o` extension: `.png` (default), `.jpg`, `.webp`+- Image format from the `-o` extension or `--format`: `png` (default), `jpg`, `webp` (JPEG/WebP encode at quality 90)- One browser process, concurrent tabs; a failed URL prints `✗` and never kills the batch (exit code 1 if anything failed)+- Batch filenames derive from the URL (`example.com-pricing.png`); collisions get `-2`, `-3` suffixes## Flags@@ -26,6 +41,7 @@ snap -o hero.jpg --wait-for 'h1' app.dev-s, --size <SIZE> WxH, or desktop (1440x900@2x) | iphone (390x844@3x) | ipad (1024x1366@2x)--full capture the full page height--dark emulate prefers-color-scheme: dark+ --format <FMT> png | jpg | webp (a recognized --out extension wins)--wait <MS> extra settle delay after smart waiting--wait-for <CSS> wait until a selector exists before capturing--scale <N> device scale factor (overrides the preset's)@@ -34,10 +50,6 @@ snap -o hero.jpg --wait-for 'h1' app.dev--chrome <PATH> browser binary (auto-detected; also via $CHROME)```-## Install--```-cargo install --path .-```+## License-Requires an installed Chrome-family browser.+[MIT](LICENSE)diff --git a/install.sh b/install.shnew file mode 100644index 0000000..0371a55--- /dev/null+++ b/install.sh@@ -0,0 +1,30 @@+#!/bin/sh+# snap installer — https://github.com/brijr/snap+# usage: curl -fsSL https://raw.githubusercontent.com/brijr/snap/main/install.sh | sh+set -eu++REPO="brijr/snap"+DIR="${SNAP_INSTALL_DIR:-$HOME/.local/bin}"++case "$(uname -s)-$(uname -m)" in+ Darwin-arm64) TARGET="aarch64-apple-darwin" ;;+ Darwin-x86_64) TARGET="x86_64-apple-darwin" ;;+ Linux-x86_64) TARGET="x86_64-unknown-linux-musl" ;;+ *)+ echo "error: no prebuilt binary for $(uname -s) $(uname -m)" >&2+ echo "build from source instead: cargo install --git https://github.com/$REPO" >&2+ exit 1+ ;;+esac++URL="https://github.com/$REPO/releases/latest/download/snap-$TARGET.tar.gz"+echo "downloading snap ($TARGET)…"+mkdir -p "$DIR"+curl -fsSL "$URL" | tar -xz -C "$DIR"+chmod +x "$DIR/snap"+echo "installed $("$DIR/snap" --version) → $DIR/snap"++case ":$PATH:" in+ *":$DIR:"*) ;;+ *) echo "note: $DIR is not on your PATH — add it to your shell profile" ;;+esacdiff --git a/src/capture.rs b/src/capture.rsindex 29983ea..c57d13b 100644--- a/src/capture.rs+++ b/src/capture.rs@@ -42,6 +42,14 @@ impl Format {}}+ pub fn ext(self) -> &'static str {+ match self {+ Self::Png => "png",+ Self::Jpeg => "jpg",+ Self::Webp => "webp",+ }+ }+fn cdp(self) -> CaptureScreenshotFormat {match self {Self::Png => CaptureScreenshotFormat::Png,@@ -103,7 +111,11 @@ impl Session {.await.ok().map(|v| v.user_agent.replace("HeadlessChrome", "Chrome"));- Ok(Self { browser, handler, user_agent })+ Ok(Self {+ browser,+ handler,+ user_agent,+ })}pub async fn capture(&self, url: &str, out: &Path, opts: &Opts) -> Result<Shot> {@@ -132,7 +144,11 @@ impl Session {).await?;- let ua = if v.mobile { Some(IPHONE_UA.to_string()) } else { self.user_agent.clone() };+ let ua = if v.mobile {+ Some(IPHONE_UA.to_string())+ } else {+ self.user_agent.clone()+ };if let Some(ua) = ua {page.execute(SetUserAgentOverrideParams::builder()@@ -166,7 +182,8 @@ impl Session {.timeout.saturating_sub(started.elapsed()).saturating_sub(Duration::from_millis(500));- self.eval(page, wait_for_js(selector, budget.as_millis() as u64)).await?;+ self.eval(page, wait_for_js(selector, budget.as_millis() as u64))+ .await?;}if opts.full {self.eval(page, SCROLL_JS.into()).await?;@@ -203,7 +220,11 @@ impl Session {self.eval(page, SETTLE_JS.into()).await?;(doc_h, v.scale, page.screenshot(params.build()).await?)} else {- (doc_h, 1.0, page.screenshot(params.full_page(true).build()).await?)+ (+ doc_h,+ 1.0,+ page.screenshot(params.full_page(true).build()).await?,+ )}} else {(v.height, v.scale, page.screenshot(params.build()).await?)@@ -213,7 +234,11 @@ impl Session {tokio::fs::write(out, data).await.with_context(|| format!("failed to write {}", out.display()))?;- Ok(Shot { height, scale, bytes })+ Ok(Shot {+ height,+ scale,+ bytes,+ })}/// Run a JS expression (promises awaited); surface page-side exceptions as errors.@@ -233,7 +258,12 @@ impl Session {.unwrap_or_else(|| details.text.clone());bail!("{}", msg.lines().next().unwrap_or("page script failed"));}- Ok(resp.result.result.value.clone().unwrap_or(serde_json::Value::Null))+ Ok(resp+ .result+ .result+ .value+ .clone()+ .unwrap_or(serde_json::Value::Null))}async fn eval_u32(&self, page: &Page, js: &str) -> Result<u32> {@@ -268,7 +298,13 @@ fn find_chrome() -> Option<PathBuf> {"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge","/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",];- #[cfg(not(target_os = "macos"))]+ #[cfg(windows)]+ const CANDIDATES: &[&str] = &[+ r"C:\Program Files\Google\Chrome\Application\chrome.exe",+ r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",+ ];+ #[cfg(not(any(target_os = "macos", windows)))]const CANDIDATES: &[&str] = &["/usr/bin/google-chrome","/usr/bin/chromium",diff --git a/src/main.rs b/src/main.rsindex 3c24a05..ac7357b 100644--- a/src/main.rs+++ b/src/main.rs@@ -15,7 +15,16 @@ use url::Url;/// Screenshot live websites. Minimal interface, powerful engine:/// smart waiting, lazy-load handling, retina output, concurrent capture.#[derive(Parser)]-#[command(name = "snap", version, arg_required_else_help = true)]+#[command(+ name = "snap",+ version,+ arg_required_else_help = true,+ after_help = "\+Examples:+ snap example.com 1440\u{d7}900 @2x \u{2192} example.com.png+ snap --full --dark tailwindcss.com full page, dark color scheme+ cat urls.txt | snap - -o shots/ concurrent batch from stdin"+)]struct Cli {/// URLs to capture; `-` reads newline-separated URLs from stdin#[arg(required = true, value_name = "URL")]@@ -37,6 +46,10 @@ struct Cli {#[arg(long)]dark: bool,+ /// Image format (a recognized --out file extension wins) [default: png]+ #[arg(long, value_parser = ["png", "jpg", "jpeg", "webp"], value_name = "FMT")]+ format: Option<String>,+/// Extra settle delay in ms after smart waiting#[arg(long, default_value_t = 0, value_name = "MS")]wait: u64,@@ -68,7 +81,8 @@ async fn main() -> Result<()> {let urls = collect_urls(&cli.urls)?;let viewport = parse_size(&cli.size, cli.scale)?;- let targets = resolve_outputs(&urls, cli.out.as_deref()).await?;+ let flag_format = cli.format.as_deref().and_then(Format::from_ext);+ let (targets, format) = resolve_outputs(&urls, cli.out.as_deref(), flag_format).await?;let jobs = cli.jobs.unwrap_or_else(|| urls.len().min(4)).max(1);let opts = Arc::new(Opts {@@ -78,11 +92,7 @@ async fn main() -> Result<()> {wait_ms: cli.wait,wait_for: cli.wait_for,timeout: Duration::from_secs(cli.timeout.max(1)),- format: targets- .first()- .and_then(|(_, p)| p.extension())- .and_then(|e| Format::from_ext(&e.to_string_lossy()))- .unwrap_or(Format::Png),+ format,});let session = Arc::new(Session::launch(cli.chrome, viewport).await?);@@ -155,7 +165,11 @@ fn collect_urls(args: &[String]) -> Result<Vec<Url>> {}raw.iter().map(|s| {- let s = if s.contains("://") { s.clone() } else { format!("https://{s}") };+ let s = if s.contains("://") {+ s.clone()+ } else {+ format!("https://{s}")+ };Url::parse(&s).with_context(|| format!("invalid URL: {s}"))}).collect()@@ -171,31 +185,44 @@ fn parse_size(size: &str, scale: Option<f64>) -> Result<Viewport> {.split_once(['x', 'X']).and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?))).with_context(|| {- format!("invalid --size {custom:?}: use WxH (e.g. 1440x900) or desktop|iphone|ipad")+ format!(+ "invalid --size {custom:?}: use WxH (e.g. 1440x900) or desktop|iphone|ipad"+ )})?;(w, h, 2.0, false)}};- Ok(Viewport { width, height, scale: scale.unwrap_or(preset_scale), mobile })+ Ok(Viewport {+ width,+ height,+ scale: scale.unwrap_or(preset_scale),+ mobile,+ })}-/// Pair each URL with its output path. Single URL + `--out file.ext` writes that exact-/// file; anything else treats --out (default `.`) as a directory of derived names.-async fn resolve_outputs(urls: &[Url], out: Option<&std::path::Path>) -> Result<Vec<(Url, PathBuf)>> {+/// Pair each URL with its output path and settle the image format. Single URL ++/// `--out file.ext` writes that exact file (its extension beats --format); anything+/// else treats --out (default `.`) as a directory of derived names in the chosen format.+async fn resolve_outputs(+ urls: &[Url],+ out: Option<&std::path::Path>,+ flag_format: Option<Format>,+) -> Result<(Vec<(Url, PathBuf)>, Format)> {if let (1, Some(path)) = (urls.len(), out)&& let Some(ext) = path.extension()- && Format::from_ext(&ext.to_string_lossy()).is_some()+ && let Some(format) = Format::from_ext(&ext.to_string_lossy()){if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {tokio::fs::create_dir_all(dir).await?;}- return Ok(vec![(urls[0].clone(), path.to_path_buf())]);+ return Ok((vec![(urls[0].clone(), path.to_path_buf())], format));}+ let format = flag_format.unwrap_or(Format::Png);let dir = out.unwrap_or_else(|| std::path::Path::new("."));tokio::fs::create_dir_all(dir).await?;let mut seen: HashMap<String, u32> = HashMap::new();- Ok(urls+ let targets = urls.iter().map(|url| {let mut name = derived_name(url);@@ -204,18 +231,29 @@ async fn resolve_outputs(urls: &[Url], out: Option<&std::path::Path>) -> Result<if *n > 1 {name = format!("{name}-{n}");}- (url.clone(), dir.join(format!("{name}.png")))+ (url.clone(), dir.join(format!("{name}.{}", format.ext())))})- .collect())+ .collect();+ Ok((targets, format))}/// `https://example.com/pricing/` -> `example.com-pricing`fn derived_name(url: &Url) -> String {let host = url.host_str().unwrap_or("page");let path = url.path().trim_matches('/').replace('/', "-");- let name = if path.is_empty() { host.to_string() } else { format!("{host}-{path}") };+ let name = if path.is_empty() {+ host.to_string()+ } else {+ format!("{host}-{path}")+ };name.chars()- .map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { c } else { '-' })+ .map(|c| {+ if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {+ c+ } else {+ '-'+ }+ }).collect()}