Package {framework}


Type: Package
Title: Structured Data Science Project Scaffolding
Version: 2.0.0
Maintainer: Erik Westlund <erik@framework.pub>
Description: Project scaffolding and workflow tools for reproducible data science. Manages packages, tracks data integrity, handles database connections, generates notebooks, and publishes to S3-compatible storage. More information at https://framework.table1.org.
License: MIT + file LICENSE
URL: https://framework.table1.org, https://github.com/frameworktools/framework
BugReports: https://github.com/frameworktools/framework/issues
Encoding: UTF-8
Imports: checkmate, DBI, RSQLite, yaml, fs, readr, openssl, lubridate, jsonlite, digest
Suggests: bit64, gt, gtsummary, flextable, testthat (≥ 3.0.0), arrow, aws.s3, aws.signature, BiocManager, cli, curl, cyclocomp, devtools, dplyr, DT, duckdb, ggplot2, haven, htmltools, htmlwidgets, httr2, IRkernel, keyring, jsonvalidate, askpass, knitr, languageserver, odbc, pool, prismjs, R.utils, readxl, remotes, renv, RMariaDB, rlang, rmarkdown, RPostgres, tm, usethis, withr, writexl, data.table, fixest, lattice, lme4, MASS, mgcv, nnet, patchwork, plotly, ragg, survival, svglite, tibble, vegawidget
Config/testthat/edition: 3
Depends: R (≥ 4.1.0)
Config/roxygen2/version: 8.1.0
NeedsCompilation: no
Packaged: 2026-11-07 15:00:06 UTC; erik
Author: Erik Westlund [aut, cre, cph]
Repository: CRAN
Date/Publication: 2026-11-07 17:30:09 UTC

framework: Structured Data Science Project Scaffolding

Description

Project scaffolding and workflow tools for reproducible data science. Manages packages, tracks data integrity, handles database connections, generates notebooks, and publishes to S3-compatible storage. More information at https://framework.table1.org.

Author(s)

Maintainer: Erik Westlund erik@framework.pub [copyright holder]

Authors:

See Also

Useful links:


Where each AI assistant reads skills and which stub file it gets

Description

Adding an assistant means adding a row here and to ASSISTANTS in data-raw/spec_schema.R. Claude Code does not read ⁠.agents/skills/⁠ (tested with 2.1.312), so it has its own folder. Copilot reads ⁠.agents/skills/⁠ as well as ⁠.github/skills/⁠.

Usage

.ai_assistant_table()

Install Framework skills into a project

Description

Copies the SKILL.md files shipped with the package into ⁠<project>/.claude/skills/<skill-name>/SKILL.md⁠.

Usage

.ai_install_skills(project_dir = ".", project_type = "project", verbose = TRUE)

Arguments

project_dir

Path to the project directory

project_type

Project type ("project", "project_sensitive", "course", "presentation")

verbose

Logical; print a message per installed skill

Value

Invisible character vector of installed skill names


Pointer stub content for non-canonical AI files

Description

Pointer stub content for non-canonical AI files

Usage

.ai_pointer_stub(project_name)

Skills that apply to a given project type

Description

Skills that apply to a given project type

Usage

.ai_skills_for_type(project_type)

Apply auto-fix for common issues

Description

Apply auto-fix for common issues

Usage

.apply_auto_fix(findings, verbose)

Build directory table from config

Description

Build directory table from config

Usage

.build_directory_table(dirs, project_type)

Calculate hash of a file

Description

Calculate hash of a file

Usage

.calculate_file_hash(file_path)

Arguments

file_path

Path to the file

Value

The hash of the file as a character string


Retrieve a default value from the catalog, falling back when missing

Description

Retrieve a default value from the catalog, falling back when missing

Usage

.catalog_field_default(catalog, field_id, fallback = NULL)

Convenience accessor for catalog field definitions

Description

Convenience accessor for catalog field definitions

Usage

.catalog_find_field(catalog, field_id)

Convert catalog project type metadata into default configuration values

Description

Convert catalog project type metadata into default configuration values

Usage

.catalog_project_type_defaults(project_types)

Check if a DuckDB database exists

Description

Check if a DuckDB database exists

Usage

.check_duckdb_exists(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if database exists, FALSE otherwise


Check if .env is gitignored

Description

Checks if .env is listed in .gitignore and warns if not.

Usage

.check_env_gitignored()

Value

Invisibly returns logical indicating if .env is gitignored


Check if git is available

Description

Check if git is available

Usage

.check_git_available()

Check git history for leaked data files

Description

Check git history for leaked data files

Usage

.check_git_history(data_dirs, extensions, history_depth, verbose)

Check git status and provide helpful reminder

Description

Check git status and provide helpful reminder

Usage

.check_git_status()

Check gitignore coverage for data files

Description

Check gitignore coverage for data files

Usage

.check_gitignore_coverage(data_dirs, extensions, verbose)

Check if a MySQL/MariaDB database exists

Description

Check if a MySQL/MariaDB database exists

Usage

.check_mysql_exists(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if database exists, FALSE otherwise


Check if path is ignored by .gitignore patterns

Description

Follows the gitignore rules that matter here: a pattern without a slash (apart from a trailing one) matches at any depth, and a matched folder ignores everything inside it.

Usage

.check_path_ignored(path, gitignore_patterns)

Check if a PostgreSQL database exists

Description

Check if a PostgreSQL database exists

Usage

.check_postgres_exists(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if database exists, FALSE otherwise


Check if private data is tracked by git

Description

Check if private data is tracked by git

Usage

.check_private_data_exposure(
  data_dirs,
  git_available,
  verbose,
  extensions = character()
)

Check for secrets files tracked by git

Description

Flags .env files (and variants such as .env.local) that git tracks. Example files (.env.example, .env.template, .env.sample) are allowed.

Usage

.check_secrets_exposure(git_available)

Check if a SQLite database exists

Description

Check if a SQLite database exists

Usage

.check_sqlite_exists(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if database exists, FALSE otherwise


Check if a SQL Server database exists

Description

Check if a SQL Server database exists

Usage

.check_sqlserver_exists(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if database exists, FALSE otherwise


Remove .gitkeep files from data/ and functions/ directories

Description

Remove .gitkeep files from data/ and functions/ directories

Usage

.cleanup_gitkeep_files(target_dir = ".")

Collect all S3 connections from config

Description

Gathers all S3/storage bucket connections from configuration, along with the default bucket name if specified.

Usage

.collect_all_s3_connections(config)

Arguments

config

Configuration object from settings_read().

Value

List with connections and default_bucket fields.


Create initial commit after first successful scaffold

Description

Create initial commit after first successful scaffold

Usage

.commit_after_scaffold()

Note

This function is now deprecated. Initial commits are created during project_create() instead of scaffold(). Kept for backward compatibility with older projects.


Configure git hooks based on environment variables

Description

Configure git hooks based on environment variables

Usage

.configure_git_hooks(target_dir = ".")

Connect to a DuckDB database

Description

Connect to a DuckDB database

Usage

.connect_duckdb(config)

Arguments

config

Connection configuration from settings.yml

Value

A DuckDB database connection


Connect to a MySQL or MariaDB database

Description

Connect to a MySQL or MariaDB database

Usage

.connect_mysql(config)

Arguments

config

Connection configuration from settings.yml

Value

A MySQL/MariaDB database connection


Connect to a PostgreSQL database

Description

Connect to a PostgreSQL database

Usage

.connect_postgres(config)

Arguments

config

Connection configuration from settings.yml

Value

A PostgreSQL database connection


Connect to a SQLite database

Description

Connect to a SQLite database

Usage

.connect_sqlite(config)

Arguments

config

Connection configuration from settings.yml

Value

A SQLite database connection


Connect to a SQL Server database

Description

Connect to a SQL Server database

Usage

.connect_sqlserver(config)

Arguments

config

Connection configuration from settings.yml

Value

A SQL Server database connection via ODBC


Copy config files between directories

Description

Copy config files between directories

Usage

.copy_config_files(from_dir, to_dir, overwrite = FALSE)

Arguments

from_dir

Source directory

to_dir

Destination directory

overwrite

Whether to overwrite existing files (default FALSE)


Create AI context files

Description

AGENTS.md is always the canonical context file, and Framework skills are installed into .claude/skills/. If the user also selected Claude Code or Copilot, those files are written as thin pointers to AGENTS.md rather than duplicated copies.

Usage

.create_ai_files(
  project_dir,
  assistants,
  canonical_content,
  type,
  project_name = NULL
)

Create AI Assistant Instruction Files

Description

Internal function called during project_create() to create AI assistant instruction files. AGENTS.md is always written as the canonical context file and Framework skills are installed into .claude/skills/. Claude Code and Copilot selections get thin pointer files referencing AGENTS.md.

Usage

.create_ai_instructions(
  assistants,
  target_dir = ".",
  project_name = NULL,
  project_type = "project"
)

Arguments

assistants

Character vector of assistants: "claude", "copilot", "agents"

target_dir

Target directory (default: current directory)

project_name

Project name for template substitution

project_type

Project type for template selection ("project", "project_sensitive", "course", "presentation")


Create .code-workspace file for VSCode/Positron

Description

Create .code-workspace file for VSCode/Positron

Usage

.create_code_workspace(project_dir, name)

Create settings.yml from template

Description

Create settings.yml from template

Usage

.create_config_file(type = "analysis", attach_defaults = TRUE, subdir = NULL)

Create development .Rprofile

Description

Create development .Rprofile

Usage

.create_dev_rprofile(subdir = NULL)

Create a new DuckDB database

Description

Create a new DuckDB database

Usage

.create_duckdb_db(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if successful


Create .gitignore file

Description

Create .gitignore file

Usage

.create_gitignore(project_dir, content)

Create IDE configuration files

Description

Create IDE configuration files

Usage

.create_ide_configs(project_name, target_dir = ".", python = FALSE)

Arguments

project_name

Project name

target_dir

Target directory

python

Include Python configuration


Create init.R from template

Description

Create init.R from template

Usage

.create_init_file(project_name, type, lintr, subdir = NULL)

Create initial git commit after all initialization is complete

Description

Create initial git commit after all initialization is complete

Usage

.create_initial_commit(target_dir = ".")

Create a new MySQL/MariaDB database

Description

Create a new MySQL/MariaDB database

Usage

.create_mysql_db(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if successful


Create a new PostgreSQL database

Description

Create a new PostgreSQL database

Usage

.create_postgres_db(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if successful


Create project config.yml

Description

Create project config.yml

Usage

.create_project_config(
  project_dir,
  name,
  type,
  author,
  packages,
  directories,
  extra_directories,
  ai,
  git,
  scaffold,
  settings_dir,
  connections = NULL,
  connections_file = NULL,
  render_dirs = NULL,
  quarto = NULL,
  security = NULL,
  data_hooks = NULL,
  tools = NULL,
  settings_layout = NULL,
  publish = NULL
)

Create project subdirectories

Description

Create project subdirectories

Usage

.create_project_directories(
  project_dir,
  directories,
  extra_directories,
  render_dirs = NULL
)

Create .renvignore file for Framework projects

Description

Creates a .renvignore file that excludes Framework data and output directories from renv dependency scanning.

Usage

.create_renvignore()

Value

Invisibly returns NULL


Create .Rproj file

Description

Create .Rproj file

Usage

.create_rproj_file(project_dir, name)

Create scaffold.R file

Description

Create scaffold.R file

Usage

.create_scaffold_file(project_dir, scaffold)

Create a new SQLite database

Description

Create a new SQLite database

Usage

.create_sqlite_db(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if successful


Create a new SQL Server database

Description

Create a new SQL Server database

Usage

.create_sqlserver_db(config)

Arguments

config

Connection configuration from settings.yml

Value

TRUE if successful


Create stub files for specific project types

Description

Create stub files for specific project types

Usage

.create_stub_files(project_dir, type, name, author)

Create the template SQLite database

Description

Create the template SQLite database

Usage

.create_template_db(delete_existing = FALSE)

Create VS Code settings.json

Description

Create VS Code settings.json

Usage

.create_vscode_settings(target_dir = ".", python = FALSE)

Arguments

target_dir

Target directory (defaults to current)

python

Include Python configuration


Create VS Code workspace file

Description

Create VS Code workspace file

Usage

.create_vscode_workspace(project_name, target_dir = ".", python = FALSE)

Arguments

project_name

Project name

target_dir

Target directory (defaults to current)

python

Include Python configuration


Customize project files with user-specific substitutions

Description

Customize project files with user-specific substitutions

Usage

.customize_project_files(
  target_dir,
  author_name = NULL,
  author_email = NULL,
  author_affiliation = NULL
)

Update data spec in the correct YAML file

Description

Traverses a dot-notated key like "final.public.test" and updates or inserts the given spec in the corresponding YAML file (either embedded in settings.yml or in an external settings/data.yml file). Automatically handles nested paths and creates intermediate structures as needed.

Usage

.data_spec_update(path, spec)

Arguments

path

Dot notation key (e.g., "final.public.test") indicating where to place the spec in the configuration hierarchy

spec

A named list containing the data spec fields (path, type, delimiter, locked, encrypted, etc.)

Value

Invisibly returns NULL. Function is called for its side effect of updating the YAML configuration file.


Get default directory table for project type

Description

Get default directory table for project type

Usage

.default_directory_table(project_type)

Resolve default render directory mappings for a project type from the catalog

Description

Resolve default render directory mappings for a project type from the catalog

Usage

.default_render_dirs_for_type(type)

Resolve default root render_dir (if defined) for a project type

Description

Resolve default root render_dir (if defined) for a project type

Usage

.default_root_render_dir_for_type(type)

Delete init.R after successful initialization

Description

Delete init.R after successful initialization

Usage

.delete_init_file(subdir = NULL)

Convert data frame to list of lists for YAML serialization JSON arrays of objects become data frames in R, but YAML needs list of lists

Description

Convert data frame to list of lists for YAML serialization JSON arrays of objects become data frames in R, but YAML needs list of lists

Usage

.df_to_list_of_lists(df)

Display next steps after initialization

Description

Display next steps after initialization

Usage

.display_next_steps(project_name = NULL, type = "project", use_renv = FALSE)

Ensure framework database exists with all required tables

Description

Ensure framework database exists with all required tables

Usage

.ensure_framework_db(project_root = NULL)

Arguments

project_root

Optional project root used to resolve the database path.


Ensure the requested template exists in the user config directory

Description

Ensure the requested template exists in the user config directory

Usage

.ensure_framework_template(name)

Ensure a directory exists, creating it lazily with feedback

Description

Ensure a directory exists, creating it lazily with feedback

Usage

.ensure_output_dir(dir_path, dir_type = "output")

Arguments

dir_path

The directory path to ensure exists

dir_type

Human-readable type for messaging (e.g., "tables", "figures")

Value

The directory path (invisibly)


Find project root by walking up directory tree

Description

Find project root by walking up directory tree

Usage

.find_project_root(start_dir)

Arguments

start_dir

Starting directory for search

Value

Path to project root, or NULL if not found


Find Stub Template

Description

Searches for stub templates in user stubs/ directory first, then framework inst/stubs/ directory.

Usage

.find_stub_template(stub, ext)

Arguments

stub

Character. Stub name (e.g., "default", "analysis")

ext

Character. File extension ("qmd", "Rmd", or "R")

Value

Path to stub template file


Get the path to the packaged settings catalog YAML

Description

Get the path to the packaged settings catalog YAML

Usage

.framework_catalog_default_path()

Get the path to the user-editable settings catalog override

Description

Get the path to the user-editable settings catalog override

Usage

.framework_catalog_user_path()

Get the Framework templates directory

Description

Get the Framework templates directory

Usage

.framework_templates_dir(...)

Serialize settings to YAML text

Description

Like yaml::as.yaml(), but writes logicals as true/false and keeps sequences that were read with .fw_read_yaml() as sequences.

Usage

.fw_as_yaml(x)

Arguments

x

The value to write.

Value

A YAML string.


Whether a connection was opened read-only

Description

SQLite connections opened with read_only: true (SQLITE_RO) and DuckDB connections opened with read_only: true.

Usage

.fw_connection_read_only(con)

Arguments

con

A DBI connection

Value

TRUE or FALSE


Which paths git ignores

Description

In a git work tree, asks ⁠git check-ignore⁠ (which reads every .gitignore, .git/info/exclude, and the global excludes file; tracked files are never ignored). Elsewhere, matches the project's .gitignore patterns.

Usage

.fw_gitignored(paths)

Arguments

paths

Paths relative to the working directory

Value

Logical vector, TRUE where the path is ignored


Read a YAML settings file for editing

Description

Read a YAML settings file for editing

Usage

.fw_read_yaml(file)

Arguments

file

Path to the file.

Value

The parsed content, with sequences marked so they write back as sequences.


Secret-looking variables with values in .env text or a named list

Description

Secret-looking variables with values in .env text or a named list

Usage

.fw_secret_env_values(raw = NULL, variables = NULL)

Whether an environment variable name looks like it holds a secret

Description

Specs and global settings may name these variables but must leave them empty. The pattern is shared with framework-py and framework-cloud.

Usage

.fw_secret_name(name)

Write settings to a YAML file

Description

Write settings to a YAML file

Usage

.fw_write_yaml(x, file)

Arguments

x

The value to write.

file

Path to the file.

Value

Invisibly returns file.


Set one section of a YAML settings file

Description

Replaces the value at keys (one or two levels, such as "data" or c("default", "data")) and rewrites only that block of lines; comments and formatting elsewhere in the file stay as they were. When the block can't be found safely (flow style, unusual layout), the whole file is rewritten instead.

Usage

.fw_yaml_set(file, keys, value)

Arguments

file

Path to the YAML file.

keys

Character vector of one or two keys.

value

The new value (NULL removes the key).

Value

Invisibly returns file.


Generate Data Management section

Description

Generate Data Management section

Usage

.generate_data_section(config, project_type)

Generate Framework Environment section

Description

Generate Framework Environment section

Usage

.generate_environment_section(config, project_type)

Generate Function Reference section

Description

Generate Function Reference section

Usage

.generate_function_reference()

Generate header section

Description

Generate header section

Usage

.generate_header_section(project_name)

Generate notes section (user-editable)

Description

Generate notes section (user-editable)

Usage

.generate_notes_section()

Generate Installed Packages section

Description

Generate Installed Packages section

Usage

.generate_packages_section(config)

Generate project-type specific section

Description

Generate project-type specific section

Usage

.generate_project_type_section(project_type, sensitive = FALSE)

Generate the skills index section for AGENTS.md

Description

Lists installed skills with their paths so agents that don't discover ⁠.claude/skills/⁠ natively can still find and read them.

Usage

.generate_skills_section(
  project_type = "project",
  skills = NULL,
  skills_dir = ".claude/skills"
)

Arguments

project_type

Project type

Value

Character string with the skills section content


Get a cache value

Description

Get a cache value

Usage

.get_cache(name, file = NULL, expire_after = NULL)

Arguments

name

The cache name

file

Optional file path to store the cache (default: ⁠cache/{name}.rds⁠)

expire_after

Optional expiration time in hours (default: from config)

Value

The cached result, or NULL if not found, expired, or hash mismatch


Get the cache directory, respecting FW_CACHE_DIR environment variable

Description

Every cache function uses this, so reads, writes, and deletes agree. A relative folder is relative to the project root.

Usage

.get_cache_dir()

Value

The cache directory path


Get data directories from config

Description

Get data directories from config

Usage

.get_data_directories(config, verbose)

Get suggestions for available data paths

Description

Helper function that extracts all available data paths from config. Used to provide helpful suggestions when data_read() fails.

Usage

.get_data_path_suggestions(attempted_path = NULL)

Arguments

attempted_path

The path that the user tried (optional, for future fuzzy matching)

Value

Character vector of available data paths


Get a data value

Description

Get a data value

Usage

.get_data_record(name)

Arguments

name

The data name

Value

The data metadata (hash), or NULL if not found


Get a connection to the framework database

Description

Get a connection to the framework database

Usage

.get_db_connection(project_root = NULL)

Arguments

project_root

Optional project root used to resolve the database path.


Get driver information for a given database type

Description

Internal helper to map database driver names to their R packages and human-readable names.

Usage

.get_driver_info(driver)

Arguments

driver

Character. Database driver name (e.g., "postgres", "mysql", "sqlite")

Value

Named list with package, name, and optionally install_command


Get git hook setting with optional alias fallback

Description

Get git hook setting with optional alias fallback

Usage

.get_hook_setting(key, alias = NULL, config_file = NULL, default = FALSE)

Get a metadata value

Description

Get a metadata value

Usage

.get_metadata(key, project_root = NULL)

Arguments

key

The metadata key

project_root

Optional project root for database resolution

Value

The metadata value, or NULL if not found


Get Notebook Directory from Config

Description

Reads config to determine where notebooks should be created. Falls back to "notebooks", "work", or current directory if config unavailable.

Usage

.get_notebook_dir_from_config()

Value

Character path to notebook directory


Extract package list from config

Description

Handles two config structures:

  1. New: packages = list(use_renv = ..., default_packages = ...)

  2. Old: packages as a flat list of package specs

Usage

.get_package_list_from_config(config)

Arguments

config

Configuration object from settings_read()

Value

List of package specifications, or empty list if none


Get package requirements from config

Description

Get package requirements from config

Usage

.get_package_requirements(config)

Arguments

config

Configuration object from settings_read()


Generate database-appropriate parameter placeholders

Description

Generate database-appropriate parameter placeholders

Usage

.get_placeholders(conn, n)

Arguments

conn

Database connection

n

Number of placeholders needed

Value

Character vector of placeholders


Retrieve scaffold metadata from the database

Description

Retrieve scaffold metadata from the database

Usage

.get_scaffold_history(project_root = NULL)

Get settings file path

Description

Returns path to settings.yml (preferred) or config.yml (backward compatibility). Walks up directory tree to find project root if not found in current directory.

Usage

.get_settings_file(path = ".")

Arguments

path

Optional path to check in (default: current directory)

Value

Path to settings file, or NULL if neither exists


Check if git is available on the system

Description

Check if git is available on the system

Usage

.git_available()

Value

TRUE if git is available, FALSE otherwise


Guess content type from file extension

Description

Guess content type from file extension

Usage

.guess_content_type(file)

Arguments

file

Character. File path.

Value

Character. MIME type.


Check if settings file exists

Description

Checks for settings.yml (preferred) or settings.yml (backward compatibility).

Usage

.has_settings_file(path = ".")

Arguments

path

Optional path to check in (default: current directory)

Value

TRUE if either file exists, FALSE otherwise


Run the checks for a git hook

Description

Called by the shared pre-commit script (inst/hooks/pre-commit) as framework:::.hook_run("pre-commit"), from the repository root. Runs the checks enabled under ⁠git: hooks:⁠ in the settings. A folder without a settings file passes, so the hook never blocks commits outside a Framework project.

Usage

.hook_run(name = "pre-commit")

Arguments

name

The hook. Only "pre-commit" exists.

Value

The exit status for git: 0 to allow the commit, 1 to block it.


Identify directories that should be treated as private/sensitive

Description

Identify directories that should be treated as private/sensitive

Usage

.identify_private_dirs(data_dirs)

Initialize the framework database

Description

Initialize the framework database

Usage

.init_db()

Initialize git repository

Description

Initialize git repository

Initialize git repository

Usage

.init_git_repo(project_dir, hooks)

.init_git_repo(project_dir, hooks)

Initialize renv

Description

Initialize renv

Usage

.init_renv(project_dir)

Standard initialization process (shared by both paths)

Description

Standard initialization process (shared by both paths)

Usage

.init_standard(
  project_name,
  type,
  lintr,
  author_name = NULL,
  author_email = NULL,
  author_affiliation = NULL,
  default_notebook_format = NULL,
  subdir,
  force,
  use_git = TRUE
)

Install a package if not already installed

Description

Install a package if not already installed

Usage

.install_package(pkg_spec)

Arguments

pkg_spec

Package specification (may include version pin)


Install package without renv

Description

Installs a package using base R functions, handling version pinning and GitHub sources.

Usage

.install_package_base(spec)

Arguments

spec

Parsed package specification from .parse_package_spec()

Value

Invisibly returns TRUE on success


Install package via renv

Description

Installs a package using renv, handling version pinning and GitHub sources.

Usage

.install_package_renv(spec)

Arguments

spec

Parsed package specification from .parse_package_spec()

Value

Invisibly returns TRUE on success


Install required packages from config

Description

Install required packages from config

Usage

.install_required_packages(config)

Arguments

config

Configuration object from settings_read()


Check if file is a data file based on extension

Description

Check if file is a data file based on extension

Usage

.is_data_file(file, extensions)

Check if current directory is a git repository

Description

Check if current directory is a git repository

Usage

.is_git_repo()

Check if project is initialized

Description

Checks for existence of settings.yml/settings.yml to determine initialization status.

Usage

.is_initialized(subdir = NULL)

Arguments

subdir

Optional subdirectory to check.

Value

Logical indicating if project is initialized.


List Available Stub Templates

Description

List Available Stub Templates

Usage

.list_available_stubs(ext = NULL)

Arguments

ext

Character. File extension to filter by

Value

Character vector of stub names


Load AI context template for a project type

Description

Load AI context template for a project type

Usage

.load_ai_template(project_type, project_name = "My Project")

Arguments

project_type

Project type

project_name

Project name for placeholder substitution

Value

Character string with template content


Load configuration from settings file

Description

Load configuration from settings file

Usage

.load_configuration(config_file = NULL)

Load environment variables from .env file

Description

Load environment variables from .env file

Usage

.load_environment(config_file = NULL, project_root = NULL)

Load all R files from functions directories

Description

Load all R files from functions directories

Usage

.load_functions(config_file = NULL, project_root = NULL)

Load all libraries specified in config

Description

Load all libraries specified in config

Usage

.load_libraries(config)

Arguments

config

Configuration object from settings_read()


Load template content from inst/templates

Description

Load template content from inst/templates

Usage

.load_template_content(template_name)

Create or append to .env file

Description

Creates a .env file (if it doesn't exist) and appends environment variables. Warns if .env is not in .gitignore to prevent accidental secret exposure.

Usage

.make_env(..., comment = NULL, check_gitignore = TRUE)

Arguments

...

Named arguments for environment variables (e.g., DB_PASSWORD = "secret")

comment

Optional comment to add before the variables

check_gitignore

Logical; if TRUE (default), warns if .env not gitignored

Value

Invisibly returns TRUE on success


Mark project as scaffolded

Description

Mark project as scaffolded

Usage

.mark_scaffolded(project_root = NULL)

Arguments

project_root

Optional project root where the scaffold marker should be written. Falls back to the current working directory when NULL.


Migrate config from previous R versions or legacy location

Description

Checks for configs in legacy ~/.config/framework location and copies them to the current R_user_dir location if found.

Usage

.migrate_config_from_previous(target_dir)

Arguments

target_dir

Target config directory

Value

TRUE if migration occurred, FALSE otherwise


Normalize expire_after input to numeric hours

Description

Normalize expire_after input to numeric hours

Usage

.normalize_expire_after(expire_after, default = NULL)

Arguments

expire_after

Numeric hours or character (e.g., "30 minutes", "12 hours", "1 day", "1 week", "45 seconds")

default

Default value if expire_after is NULL/empty


Normalize Notebook Name and Detect Type

Description

Normalize Notebook Name and Detect Type

Usage

.normalize_notebook_name(name, type = c("quarto", "rmarkdown", "script"))

Arguments

name

Character. File name with or without extension

type

Character. Type preference

Value

List with name, type, and ext


Normalize package specification from config

Description

Converts the various package representations supported in settings.yml into a consistent structure that downstream helpers can rely on.

Usage

.normalize_package_spec(spec)

Arguments

spec

Character string or list describing a package dependency

Value

List with fields: name, source, version, repo, ref, auto_attach


Parse Assistant Selection from User Input

Description

Helper to convert user input like "1,3" or "4" into assistant names.

Usage

.parse_assistant_selection(selection)

Arguments

selection

User input string

Value

Character vector of assistant names


Parse package specification with source detection

Description

Parses package specifications that may include explicit sources, version pins, or GitHub/Bioconductor references. Supports both scalar strings and list-style entries from settings.yml.

Usage

.parse_package_spec(spec)

Arguments

spec

Character or list describing the package

Details

Examples:

Value

List with normalized components (name, source, version, repo, ref, auto_attach)


Parse markdown into sections based on ## headings

Description

Parse markdown into sections based on ## headings

Usage

.parse_sections(content)

Pretty-print configuration values (internal)

Description

Intelligently formats configuration output based on session type. In interactive sessions, pretty-prints nested structures. In scripts, returns raw values.

Usage

.pretty_print_config(value)

Arguments

value

Configuration value to format

Value

In interactive mode with complex values: invisible return after printing. Otherwise: raw value.


Print audit summary

Description

Print audit summary

Usage

.print_audit_summary(result)

Create a project from a resolved spec

Description

Create a project from a resolved spec

Usage

.project_create_from_spec(spec, location, headless = FALSE)

Get AI Support Preferences (Non-interactive)

Description

Called during project_create() to check if AI instructions should be created. NO prompting - just returns saved preferences.

Usage

.prompt_ai_support_init()

Set AI Support Preferences (Non-interactive)

Description

Called from bash CLI to set AI preferences. NO prompting - bash handles all user interaction.

Usage

.prompt_ai_support_install(support = "never", assistants = character(0))

Arguments

support

"yes" or "never"

assistants

Character vector like c("claude", "copilot")


Read a framework template

Description

Read a framework template

Usage

.read_framework_template(name)

Remove a cache value

Description

Remove a cache value

Usage

.remove_cache(name, file = NULL)

Arguments

name

The cache name to remove

file

Optional file path of the cache (default: ⁠cache/{name}.rds⁠)


Remove a data value

Description

Remove a data value

Usage

.remove_data(name)

Arguments

name

The data name to remove


Remove initialization

Description

Removes settings.yml/settings.yml to mark project as uninitialized. WARNING: This will delete your project configuration!

Usage

.remove_init(subdir = NULL)

Arguments

subdir

Optional subdirectory to check.

Value

Logical indicating if removal was successful.


Remove a metadata value

Description

Remove a metadata value

Usage

.remove_metadata(key, project_root = NULL)

Arguments

key

The metadata key to remove

project_root

Optional project root for database resolution


Replace moustache-style placeholders in template content

Description

Supports both {{name}} and {{ name }} styles by trimming whitespace around the variable identifier before replacement.

Usage

.replace_moustache_placeholders(content, replacements)

Arguments

content

Character vector containing template lines.

replacements

Named list or vector of replacements.

Value

Character vector with placeholders replaced.


Replace content of a specific section

Description

Replace content of a specific section

Usage

.replace_section(content, heading, new_content)

Check if a database driver package is available

Description

Internal helper to check if a required database driver package is installed. Throws an informative error if the package is missing.

Usage

.require_driver(driver_name, package_name, install_command = NULL)

Arguments

driver_name

Character. Human-readable name of the database (e.g., "PostgreSQL", "MySQL")

package_name

Character. Name of the R package required (e.g., "RPostgres", "RMariaDB")

install_command

Character. Optional custom install command. Defaults to install.packages()

Value

NULL (invisible). Throws error if package not available.


Require git repository or stop

Description

Require git repository or stop

Usage

.require_git_repo()

Reset a template back to its packaged default

Description

Reset a template back to its packaged default

Usage

.reset_framework_template(name)

Create an S3 client from connection configuration

Description

Creates an S3 client object using credentials from the connection configuration. Credentials are resolved from connection config, falling back to environment variables. Loads .env file if present to ensure env vars are available.

Usage

.s3_client(conn_config)

Arguments

conn_config

List. Connection configuration from config.yml

Value

An S3 client object (from aws.s3 package)


Generate public URL for S3 object

Description

Generate public URL for S3 object

Usage

.s3_public_url(key, s3_config)

Arguments

key

Character. Object key in S3.

s3_config

List. S3 configuration.

Value

Character. Public URL.


Upload a directory to S3

Description

Recursively uploads all files in a directory to S3.

Usage

.s3_upload_dir(dir, dest, s3_config, pattern = NULL)

Arguments

dir

Character. Local directory path to upload.

dest

Character. Destination prefix in S3 bucket.

s3_config

List. S3 configuration from .resolve_s3_connection().

pattern

Character or NULL. Optional file pattern filter.

Value

Character vector. S3 URIs of uploaded files.


Upload a file to S3

Description

Uploads a single file to an S3 bucket.

Usage

.s3_upload_file(file, dest, s3_config, content_type = NULL)

Arguments

file

Character. Local file path to upload.

dest

Character. Destination key (path) in S3 bucket.

s3_config

List. S3 configuration from .resolve_s3_connection().

content_type

Character or NULL. MIME type (auto-detected if NULL).

Value

Character. The S3 URI of the uploaded file.


Save audit result to framework database

Description

Save audit result to framework database

Usage

.save_audit_result(result)

Log a saved result to the framework database

Description

Internal function called by save_table(), save_figure(), etc. to track saved outputs in the results table.

Usage

.save_result(name = NULL, path, type, public = FALSE, comment = NULL)

Arguments

name

Ignored; kept so older callers still work. The name is the project-relative path.

path

Full file path to the saved result

type

Result type: "table", "figure", "model", "report", "notebook"

public

Whether saved to public outputs directory

comment

Optional description

Details

The result is named by its path from the project root, such as outputs/tables/summary.csv, as in framework-py, so files with the same name in different folders stay apart. A row from an older save, named by the file name alone, is renamed to the path when the file is saved again.

Value

NULL invisibly


Scan for orphaned data files outside configured directories

Description

Scan for orphaned data files outside configured directories

Usage

.scan_for_orphaned_files(data_dirs, extensions, verbose)

Set a cache value

Description

Set a cache value

Usage

.set_cache(name, value, file = NULL, expire_after = NULL)

Arguments

name

The cache name

value

The value to cache

file

Optional file path to store the cache (default: ⁠cache/{name}.rds⁠)

expire_after

Optional expiration time in hours (default: from config)


Set a data value

Description

Set a data value

Usage

.set_data(
  name,
  path = NULL,
  type = NULL,
  delimiter = NULL,
  locked = FALSE,
  hash = NULL
)

Arguments

name

The data name

path

The file path

type

The data type (csv, rds, etc.)

delimiter

The delimiter for CSV files

locked

Whether the data is locked

hash

The hash of the data


Set ggplot2 theme for consistent styling

Description

Sets ggplot2 theme if configured. Checks for theme settings in this order:

  1. Project settings (scaffold:, then options:, then the top level)

  2. Skip if set_theme_on_scaffold is FALSE or theme is empty

Usage

.set_ggplot_theme(config)

Arguments

config

Configuration object from settings_read()


Set a metadata value

Description

Set a metadata value

Usage

.set_metadata(key, value, project_root = NULL)

Arguments

key

The metadata key

value

The metadata value

project_root

Optional project root for database resolution


Set random seed for reproducibility

Description

Sets the random seed for reproducibility. Checks for seed in this order:

  1. Project settings.yml (seed: value)

  2. Global ~/.frameworkrc (FW_SEED)

  3. Skip seeding if both are NULL or empty

Usage

.set_random_seed(config)

Arguments

config

Configuration object from settings_read()


Slugify a String

Description

Converts a string to a filesystem-safe slug:

Usage

.slugify(text)

Arguments

text

Character. String to slugify

Value

Character. Slugified string


Sync packages from settings.yml to renv

Description

Reads the packages list from settings.yml and installs them via renv, then snapshots the result to renv.lock.

Usage

.sync_packages_to_renv()

Value

Invisibly returns TRUE on success


Convert string to kebab-case

Description

Convert string to kebab-case

Usage

.to_kebab_case(str)

Update data with hash in the data table

Description

Update data with hash in the data table

Update data with hash in the data table

Usage

.update_data_with_hash(name, hash)

.update_data_with_hash(name, hash)

Arguments

name

The data name

hash

The hash to store


Update ~/.frameworkrc with AI Preferences

Description

Helper to update the frameworkrc file with AI support settings.

Usage

.update_frameworkrc(frameworkrc_path, support, assistants)

Arguments

frameworkrc_path

Path to .frameworkrc file

support

"yes", "never", or ""

assistants

Character vector of assistant names


Update .gitignore for renv

Description

Adds renv-related entries to .gitignore if they don't already exist.

Usage

.update_gitignore_for_renv()

Value

Invisibly returns NULL


Update hook configuration in settings.yml, or in its split git file

Description

Projects made by new_project() store git: settings/git.yml. The hook setting is then written to that file, as framework-py does. The legacy alias warn_unignored_sensitive is stored as check_sensitive_dirs.

Usage

.update_hook_config(hook_name, enabled, config_file)

Determine if a project field uses split file or inline settings

Description

Determine if a project field uses split file or inline settings

Usage

.uses_split_file(project_path, field_name)

Arguments

project_path

Path to project directory

field_name

Name of the field to check (e.g., "packages", "connections")

Value

List with use_split, main_file, split_file, and has_default


Validate driver availability before connection

Description

Internal helper that combines driver info lookup and availability check. Used by connection functions to ensure required packages are installed.

Usage

.validate_driver(driver)

Arguments

driver

Character. Database driver name

Value

NULL (invisible). Throws error if driver package not available.


Validate refresh parameter

Description

Validate refresh parameter

Usage

.validate_refresh(refresh)

Arguments

refresh

Boolean or function that returns boolean

Value

Boolean indicating if refresh is needed


Basic validation for the settings catalog structure

Description

Basic validation for the settings catalog structure

Usage

.validate_settings_catalog(catalog)

Write (overwrite) a framework template

Description

Write (overwrite) a framework template

Usage

.write_framework_template(name, contents)

Add project to global configuration

Description

Adds a project folder to the registry (projects.yml in fw_config_dir()). The registry stores only the ID, the path, and the date. The project's name and type are read from its settings.yml when needed.

Usage

add_project_to_config(project_dir, project_name = NULL, project_type = NULL)

Arguments

project_dir

Path to project directory

project_name

Not stored. Kept so older code still runs.

project_type

Not stored. Kept so older code still runs.

Value

Invisibly returns the project ID. For a folder already in the registry, that project's existing ID.


Adopt an Existing Project Folder

Description

Turns a folder you already work in into a Framework project without moving anything. adopt() looks at the folder names (never file names or contents, and at most three levels deep), proposes which Framework directory each one is, and lets you accept, change a role, or leave a folder out. It then writes settings.yml (a single file) and .framework/spec.json describing the folders as they are. Nothing else is created, moved, or overwritten, and scaffold() works afterwards.

Usage

adopt(path = ".", yes = FALSE)

Arguments

path

The project folder (default: the working directory).

yes

If TRUE, accept the proposed mapping without asking. Required in a non-interactive session.

Details

Folders whose path contains "private" are flagged: consider the Privacy Sensitive structure for that project, and keep those folders out of git.

When you are signed in to Framework Cloud and run adopt() interactively, it then offers to register the project (which writes its project token to .env, making sure git ignores .env first) and to save the layout as a structure. Both default to No.

Value

Invisibly, a list with directories and extra_directories as written.

See Also

structure_import() to save the layout as a structure on Framework Cloud.

Examples


if (FALSE) {
adopt("~/projects/old-study")
adopt(yes = TRUE)
}



Generate AI Context File

Description

Generates the canonical AI context file (AGENTS.md) for a project. The file is intentionally thin: it carries project-specific facts (environment, packages, directories) plus an index of the Framework skills installed in ⁠.claude/skills/⁠, which hold the detailed workflow instructions.

Usage

ai_generate_context(
  project_path = ".",
  project_name = NULL,
  project_type = NULL,
  config = NULL,
  skills = NULL,
  skills_dir = ".claude/skills"
)

Arguments

project_path

Path to the project directory (default: current directory)

project_name

Name of the project (for header)

project_type

Project type: "project", "project_sensitive", "course", "presentation"

config

Project configuration (if NULL, reads from settings.yml)

skills

Character vector of the skills installed in the project, for the skills table. NULL lists the default skills for project_type.

skills_dir

Folder the skills are installed in, for the paths in the skills table.

Value

Character string with the complete AI context content

Examples


if (FALSE) {
# Generate AI context for current project
content <- ai_generate_context()

# Generate for a specific project type
content <- ai_generate_context(project_type = "project_sensitive")
}


Regenerate Dynamic Sections in AI Context File

Description

Updates only the sections marked with ⁠<!-- @framework:regenerate -->⁠ in an existing AI context file, preserving user customizations in unmarked sections.

Usage

ai_regenerate_context(project_path = ".", sections = NULL, ai_file = NULL)

Arguments

project_path

Path to the project directory

sections

Which sections to regenerate. NULL = all regeneratable sections. Options: "environment", "packages", "data", "functions". A section is regenerated only when the file has its marked heading; files made by Framework 2.0 have no "functions" section.

ai_file

Name of the AI context file (default: ai.canonical_file from settings, then "AGENTS.md", then "CLAUDE.md" for older projects)

Value

Invisible TRUE on success

Examples


if (file.exists("AGENTS.md")) {
  # Regenerate all dynamic sections
  ai_regenerate_context()

  # Regenerate only packages section
  ai_regenerate_context(sections = "packages")
}


AI Skills Management

Description

Framework ships agent "skills" - focused instruction files (SKILL.md) that AI coding assistants load on demand. Skills are installed into a project's ⁠.claude/skills/⁠ directory and indexed from AGENTS.md, so both Claude Code (which discovers them natively) and other agents (which follow the paths listed in AGENTS.md) can use them.


Update Framework Skills in a Project

Description

Re-copies the skill files Framework ships for the project's type (the ⁠framework-*⁠ skills and the ggplot2 skills) from the installed package version into ⁠.claude/skills/⁠. Run this after upgrading the framework package to pick up improved skill instructions.

Usage

ai_skills_update(project_path = ".")

Arguments

project_path

Path to the project directory (default: current directory)

Details

Locally edited skills and account-owned forks are preserved. Unchanged package skills receive the new package version. Custom skills are left alone.

Value

Invisible character vector of the package skills now in the project (created, updated, or already up to date). Its status attribute names what happened to each skill, including preserved ones.

Examples


if (FALSE) {
# Refresh skills after upgrading the framework package
ai_skills_update()
}


Sync AI Assistant Context Files (Deprecated)

Description

Deprecated in framework 2.0. Projects now keep one AGENTS.md, which CLAUDE.md points to, plus skills, so there is nothing to sync.

Usage

ai_sync_context(config_file = NULL, force = FALSE, verbose = TRUE)

Arguments

config_file

Path to configuration file (default: auto-detect settings.yml/settings.yml)

force

Logical; if TRUE, overwrite even if target is newer (default: FALSE). A file that only points to the canonical file, such as a CLAUDE.md holding ⁠@AGENTS.md⁠, is never overwritten.

verbose

Logical; if TRUE (default), show sync messages

Details

Copies content from the canonical AI assistant file to all other AI files, adding a warning header to non-canonical files.

This function reads the ai.canonical_file setting from settings.yml and copies its content to all other AI assistant instruction files that exist in the project.

The canonical file is copied as-is. Non-canonical files receive a warning header indicating they are auto-synced and should not be edited directly.

Supported files:

Value

Invisible list with sync results

Examples


if (FALSE) {
# Sync AI context files
ai_sync_context()

# Force sync even if targets are newer
ai_sync_context(force = TRUE)

# Silent sync (for git hooks)
ai_sync_context(verbose = FALSE)
}



Prepare a Cloned Project

Description

Gets a project ready to work in after ⁠git clone⁠, on a new machine or a cluster. Every step is safe to repeat, and none contacts Framework Cloud:

Usage

bootstrap(path = ".", interactive = base::interactive(), packages = TRUE)

Arguments

path

The project folder (default: the current directory).

interactive

If TRUE, ask for the values of empty .env variables the settings use. If FALSE, never prompt and list them as to-dos instead.

packages

If FALSE, skip package installation.

Details

  1. Make sure .gitignore ignores .env.

  2. Create .env from .env.example when it is missing, and list the empty variables that the project's settings use (through env("NAME"), Sys.getenv("NAME"), or ⁠${NAME}⁠). Unused examples are not to-dos.

  3. Create the project folders, which git does not carry when they are empty or ignored. Absolute paths (shared drives) are left alone, and so are folders under ⁠outputs/⁠, which are made when first written to, as in a new project.

  4. Create framework.db, or add the tables a newer version needs.

  5. Install packages: renv::restore() when the project has renv.lock, otherwise the packages listed in settings.yml.

  6. Install the git hooks enabled in settings.yml.

The Python package and ⁠fw bootstrap⁠ follow the same contract. From a shell: ⁠Rscript -e 'framework::bootstrap(interactive = FALSE)'⁠, which exits with status 0 when the project is ready (even with to-dos left) and 1 when a step failed.

Value

Invisibly, a list with root, done (the steps that changed something), and todo (things left to do by hand).

See Also

new(), git_hooks_install(), packages_restore()

Examples


if (FALSE) {
# After cloning a project
framework::bootstrap()

# In a job script on a cluster
framework::bootstrap(interactive = FALSE)
}



Bootstrap project initialization file

Description

Generates an init.R file showing the initialization logic. Useful for documentation and understanding how the project was set up.

Usage

bootstrap_project_init(output_file = "init.R")

Arguments

output_file

Path where init.R should be written. Default: "init.R"

Value

Invisibly returns TRUE on success


Cache a value

Description

Cache a value

Usage

cache(name, value, file = NULL, expire_after = NULL)

Arguments

name

The cache name

value

The value to cache

file

Optional file path to store the cache (default: ⁠cache/{name}.rds⁠)

expire_after

Optional expiration time in hours (default: from config)

Value

The cached value


Clear all cached values

Description

Clear all cached values

Usage

cache_flush()

Value

Invisibly returns NULL.


Remove a cached value

Description

Remove a cached value

Usage

cache_forget(name, file = NULL)

Arguments

name

The cache name to remove

file

Optional file path of the cache (default: ⁠cache/{name}.rds⁠)

Value

Invisibly returns NULL.


Get a cached value

Description

Get a cached value

Usage

cache_get(name, file = NULL, expire_after = NULL)

Arguments

name

The cache name

file

Optional file path to store the cache (default: ⁠cache/{name}.rds⁠)

expire_after

Not used. Expiry is set when the value is stored, with cache() or cache_remember(). Kept so older code still runs.

Value

The cached value, or NULL if not found, expired, or hash mismatch


List all cached values

Description

Returns a data frame of all cache entries with their names, expiration times, and status (expired or active).

Usage

cache_list()

Value

A data frame with columns:

name

Cache key name

expire_at

Expiration timestamp (NA if no expiration)

created_at

When the cache was created

updated_at

When the cache was last updated

last_read_at

When the cache was last read

status

Either "active" or "expired"

Returns an empty data frame if no cache entries exist.

Examples


if (FALSE) {
# List all cache entries
cache_list()

# Filter to see only expired caches
cache_list() |> dplyr::filter(status == "expired")
}



Remember a value (get from cache or compute and store)

Description

Attempts to retrieve a cached value by name. If the cache doesn't exist, is expired, or a refresh is requested, evaluates the expression and caches the result. This is the primary caching interface for expensive computations.

Usage

cache_remember(
  name,
  expr,
  file = NULL,
  expire_after = NULL,
  refresh = FALSE,
  expire = NULL
)

Arguments

name

The cache name (non-empty string identifier)

expr

The expression to evaluate and cache if cache miss occurs. Expression is evaluated in the parent frame.

file

Optional file path to store the cache (default: ⁠cache/{name}.rds⁠)

expire_after

Optional expiration time in hours (default: from config). Character durations like "30 minutes", "2 hours", "1 day", or "1 week" are accepted (also seconds).

refresh

Optional boolean or function that returns boolean to force refresh. If TRUE or if function returns TRUE, cache is invalidated and expression is re-evaluated.

expire

Optional alias for expire_after (accepts the same formats)

Value

The cached value (if cache hit) or the result of evaluating expr (if cache miss or refresh requested)

Examples


if (FALSE) {
# Cache expensive computation
result <- cache_remember("my_analysis", {
  expensive_computation()
})

# Force refresh when data changes
result <- cache_remember("analysis", {
  run_analysis()
}, refresh = file.mtime("data.csv") > cache_time)
}



Capture console output and errors from an expression

Description

Capture console output and errors from an expression

Usage

capture_output(expr)

Arguments

expr

Expression to evaluate

Value

List containing status (boolean), console_output (character vector), and result (return value or error)


Log In to Framework Cloud

Description

Shows what connecting shares, asks for confirmation, then verifies the token and stores it in the native credential store for your platform – the macOS Keychain (through ⁠/usr/bin/security⁠, as fw does), or Windows Credential Manager or Linux Secret Service (through the keyring package), falling back to a permission-restricted file in the Framework config directory. This is the whole onboarding:

Usage

cloud_login(
  token = NULL,
  url = NULL,
  verify = TRUE,
  consent = NULL,
  browser = TRUE
)

Arguments

token

Your user token from Framework Cloud (Settings -> API tokens). Omit it to approve this computer in the browser.

url

The Framework Cloud server. Defaults to FW_CLOUD_URL, then the server you last logged in to, then https://framework.pub. Plain http is accepted only for localhost and ⁠127.0.0.1⁠.

verify

Check the token against the server before saving (default TRUE).

consent

Set TRUE to confirm non-interactively (scripts, CI). In an interactive session you are prompted instead. What connecting shares is printed first and documented at the server's ⁠/privacy⁠ page.

browser

Open the approval page when no token is given. FALSE prints the link only.

Details

framework::cloud_login("fw_...")

# A self-hosted server, or single-user mode on this machine
framework::cloud_login("fw_...", url = "https://framework.example.edu")
framework::cloud_login("fw_...", url = "http://localhost:8080")

Tokens are stored per server, and the server you log in to becomes this machine's default for cloud_status(), cloud_sync(), and new(). The FW_CLOUD_URL environment variable overrides that default.

Without a token, cloud_login() opens the server's approval page in your browser. Sign in, or create a free account, and approve this computer; the token comes back to R. With a token from the server's token page, cloud_login(token) stores that token instead.

Value

Invisibly, where the token was stored ("keyring" or the file path).

See Also

cloud_status(), cloud_logout(), cloud_settings()


Log Out of Framework Cloud

Description

Revokes this machine's stored token for a server on that server, then removes it from the system keyring and any token files. When FW_TOKEN_FILE is set, only that file is used, because it is the only place cloud_login() wrote. A token in FW_CLOUD_TOKEN is neither revoked nor removed. When the server can't be reached, the local copy is still removed and the token can be revoked on the server's tokens page. The default server saved by cloud_login() is kept.

Usage

cloud_logout(url = NULL)

Arguments

url

The server to log out of. Defaults to the server cloud_login() would use.

Value

Invisibly, TRUE.


Fetch Your Cloud Settings

Description

Retrieves your settings document from Framework Cloud. These settings are overlaid on local defaults when creating projects with new().

Usage

cloud_settings()

Value

A list with revision, schema_version, and document.


Check Cloud Connection Status

Description

Reports which Framework Cloud server is in use and where that setting came from, whether a token is stored for it, and who the token authenticates as. Inside a project set up from a different server, the project's server is reported too.

Usage

cloud_status(url = NULL)

Arguments

url

Check this server instead of the default.

Value

Invisibly, TRUE if connected, FALSE otherwise.


Sync Your Settings with Framework Cloud

Description

Your cloud settings document is mirrored to cloud-settings.yml in the Framework config directory. Edit it there (or on the website) and sync. Your main settings.yml is never touched.

Usage

cloud_sync(direction = c("auto", "pull", "push"))

Arguments

direction

One of "auto", "pull", "push".

Details

Value

Invisibly, the current revision number.

See Also

cloud_login(), cloud_settings()


Get configuration value (alias for settings)

Description

Internal alias for settings.

Usage

config(key = NULL, default = NULL, config_file = NULL)

Arguments

key

Character. Dot-notation key path

default

Optional default value if key is not found

config_file

Configuration file path (default: auto-discover)

Value

The configuration value


Sync Settings from the Python Package and fw

Description

The Python package and the fw command-line tool keep their settings in ⁠~/.config/framework⁠, and the R package keeps its own in fw_config_dir(). config_sync() brings R in line with them: files that are missing from R's folder, or newer in theirs, are copied into R's folder. This covers user settings, the saved Framework Cloud server, and token files. The cloud settings mirror and its sync state stay separate, because each tool keeps its own. R only reads their folder and never writes to it.

Usage

config_sync(from = NULL, dry_run = FALSE)

Arguments

from

The folder to sync from. Defaults to ⁠$XDG_CONFIG_HOME/framework⁠, or ⁠~/.config/framework⁠ when XDG_CONFIG_HOME is unset.

dry_run

Logical. List what would be copied without copying it.

Details

Logins stored in the system keyring are already shared and need no sync.

Value

Invisibly, the relative paths copied (or that would be copied).

See Also

fw_config_dir(), cloud_login()

Examples


if (FALSE) {
config_sync(dry_run = TRUE)
config_sync()
}



Configure AI Assistant Support

Description

Non-interactive function to configure AI assistant support. Should be called from bash CLI with parameters, not directly from R.

Usage

configure_ai_agents(support = NULL, assistants = NULL)

Arguments

support

"yes", "never", or NULL (show current status)

assistants

Character vector of assistants: "claude", "copilot", "agents"

Details

Supported AI assistants:


Configure Author Information

Description

Interactively set author information in settings.yml (or settings.yml for legacy projects). This information is used in notebooks, reports, and other documents.

Usage

configure_author(
  name = NULL,
  email = NULL,
  affiliation = NULL,
  interactive = TRUE
)

Arguments

name

Character. Author name (optional, prompts if not provided)

email

Character. Author email (optional, prompts if not provided)

affiliation

Character. Author affiliation/institution (optional, prompts if not provided)

interactive

Logical. If TRUE, prompts for missing values. Default TRUE.

Value

Invisibly returns updated config


Configure Database Connection

Description

Interactively add a database connection to settings.yml (or settings.yml for legacy projects). Connections can be defined inline or in a split file (settings/connections.yml).

Usage

configure_connection(
  name = NULL,
  driver = NULL,
  host = NULL,
  port = NULL,
  database = NULL,
  user = NULL,
  password = NULL,
  interactive = TRUE
)

Arguments

name

Character. Connection name (e.g., "db", "warehouse")

driver

Character. Database driver: "sqlite", "postgresql", "mysql", etc.

host

Character. Database host (for network databases)

port

Integer. Database port (for network databases)

database

Character. Database name

user

Character. Database user (for network databases)

password

Character. Database password (stored in .env)

interactive

Logical. If TRUE, prompts for missing values. Default TRUE.

Value

Invisibly returns updated config


Configure Data Source

Description

Interactively add a data source to settings.yml (or settings.yml for legacy projects). Data sources are defined with dot-notation paths (e.g., "source.private.survey") and include metadata like file path, type, and whether the data is locked.

Usage

configure_data(
  path = NULL,
  file = NULL,
  type = NULL,
  locked = FALSE,
  interactive = TRUE
)

Arguments

path

Character. Dot-notation path for the data source (e.g., "source.private.survey")

file

Character. File path to the data file

type

Character. Data type: "csv", "tsv", "rds", "excel", "stata", "spss", "sas", or "auto"

locked

Logical. If TRUE, file is read-only and errors on changes

interactive

Logical. If TRUE, prompts for missing values. Default TRUE.

Value

Invisibly returns updated config


Configure Project Directories

Description

Interactively configure project directory structure in settings.yml (or settings.yml for legacy projects). Directories control where Framework creates and looks for files.

Usage

configure_directories(directory = NULL, path = NULL, interactive = TRUE)

Arguments

directory

Character. Directory name to configure (e.g., "notebooks", "scripts")

path

Character. Path for the directory

interactive

Logical. If TRUE, prompts for missing values. Default TRUE.

Details

Standard Directories

Value

Invisibly returns updated config


Configure Global Framework Settings

Description

Unified function for reading and writing global Framework settings. They are stored in settings.yml and the project registry in projects.yml, both in fw_config_dir(). This function provides a single source of truth for global configuration, used by both the CLI and GUI interfaces.

Usage

configure_global(settings = NULL, validate = TRUE)

Arguments

settings

List. Settings to update (partial updates supported)

validate

Logical. Validate settings before saving (default: TRUE)

Details

Global Settings Structure

Value

Invisibly returns updated global configuration

Examples


if (FALSE) {
# Update author information
configure_global(settings = list(
  author = list(
    name = "Jane Doe",
    email = "jane@example.com"
  )
))

# Update default project type
configure_global(settings = list(
  defaults = list(
    project_type = "presentation"
  )
))

# Get current settings (read-only)
current <- configure_global()
}



Configure Package Dependencies

Description

Interactively add package dependencies to settings.yml (or settings.yml for legacy projects). Packages can be installed from CRAN, GitHub, or Bioconductor, with version pinning support.

Usage

configure_packages(
  package = NULL,
  auto_attach = TRUE,
  version = NULL,
  interactive = TRUE
)

Arguments

package

Character. Package name (e.g., "dplyr", "tidyverse/dplyr")

auto_attach

Logical. If TRUE, package is loaded automatically during scaffold()

version

Character. Version constraint (e.g., "@1.1.0", "@main" for GitHub)

interactive

Logical. If TRUE, prompts for missing values. Default TRUE.

Details

Package Specifications

Value

Invisibly returns updated config


Begin a database transaction

Description

Manually begin a database transaction. You must call connection_commit() to save changes or connection_rollback() to discard them.

Usage

connection_begin(conn)

Arguments

conn

Database connection

Details

Note: Using db_transaction() is preferred as it automatically handles commit/rollback.

Value

NULL (invisible)


Check if a connection is ready to use

Description

Diagnoses whether a configured database connection can be established. Checks driver availability and configuration validity without actually connecting to the database.

Usage

connection_check(connection_name)

Arguments

connection_name

Character. Name of the connection in config.yml

Value

A list with diagnostic information:


Check for leaked database connections

Description

Scans the global environment and parent frames for open database connections. Useful for debugging connection leaks in interactive sessions or long-running scripts.

Usage

connection_check_leaks(warn = TRUE)

Arguments

warn

Logical. If TRUE (default), emits a warning if leaked connections found

Value

A data frame with information about open connections:


Close all open database connections

Description

Safely closes all open database connections in the global environment. Useful for cleaning up after interactive sessions or when resetting state.

Usage

connection_close_all(force = FALSE, quiet = FALSE)

Arguments

force

Logical. If TRUE, closes even invalid connections. Default: FALSE

quiet

Logical. If TRUE, suppresses messages. Default: FALSE

Value

Invisibly returns the number of connections closed


Commit a database transaction

Description

Commits the current transaction, making all changes permanent.

Usage

connection_commit(conn)

Arguments

conn

Database connection

Value

NULL (invisible)


Delete a record from a table

Description

Deletes a record from a table. Supports soft-delete pattern where records have a deleted_at column. Hard-delete can be forced with soft = FALSE.

Usage

connection_delete(conn, table_name, id, soft = TRUE)

Arguments

conn

Database connection

table_name

Name of the table

id

The ID of the record to delete

soft

Whether to use soft-delete if available (default: TRUE)

Value

Number of rows affected


Find a record by ID

Description

Finds a single record in a table by its ID. Supports soft-delete patterns where records have a deleted_at column.

Usage

connection_find(conn, table_name, id, with_trashed = FALSE)

Arguments

conn

Database connection

table_name

Name of the table to query

id

The ID to look up (integer or string)

with_trashed

Whether to include soft-deleted records (default: FALSE). Only applies if deleted_at column exists in the table.

Value

A data frame with the record, or empty data frame if not found


Find records by column values

Description

Finds records in a table matching specified column values. Supports soft-delete patterns where records have a deleted_at column.

Usage

connection_find_by(conn, table_name, ..., with_trashed = FALSE)

Arguments

conn

Database connection

table_name

Name of the table to query

...

Named arguments for column = value pairs (e.g., email = "test@example.com")

with_trashed

Whether to include soft-deleted records (default: FALSE). Only applies if deleted_at column exists in the table.

Value

A data frame with matching records, or empty data frame if none found


Insert a record into a table

Description

Inserts a new record into a table with automatic timestamp handling. If the table has created_at/updated_at columns, they will be set automatically.

Usage

connection_insert(conn, table_name, values, auto_timestamps = TRUE)

Arguments

conn

Database connection

table_name

Name of the table

values

Named list of column-value pairs

auto_timestamps

Whether to automatically set created_at/updated_at (default: TRUE)

Value

The ID of the inserted record (if auto-increment ID exists), or number of rows affected


Get or create a connection pool

Description

Returns a connection pool for the specified database connection. Connection pools automatically manage connection lifecycle, reuse connections across operations, and handle cleanup. This is the recommended way to work with databases in Framework.

Usage

connection_pool(
  name,
  min_size = 1,
  max_size = Inf,
  idle_timeout = 60,
  validation_interval = 60,
  recreate = FALSE
)

Arguments

name

Character. Name of the connection in settings.yml

min_size

Integer. Minimum number of connections to maintain (default: 1)

max_size

Integer. Maximum number of connections allowed (default: Inf)

idle_timeout

Integer. Seconds before idle connections are closed (default: 60)

validation_interval

Integer. Seconds between connection health checks (default: 60)

recreate

Logical. If TRUE, closes existing pool and creates new one (default: FALSE)

Details

Connection pools are stored in a package environment and reused across calls. You don't need to manage pool lifecycle - Framework handles it automatically.

Advantages of connection pools:

When to use:

When NOT to use:

Value

A pool object that can be used like a regular DBI connection


Close a specific connection pool

Description

Closes and removes a connection pool. All connections in the pool are gracefully closed.

Usage

connection_pool_close(name, quiet = FALSE)

Arguments

name

Character. Name of the connection pool to close

quiet

Logical. If TRUE, suppresses messages (default: FALSE)

Value

Invisibly returns TRUE if pool was closed, FALSE if it didn't exist


Close all connection pools

Description

Closes all active connection pools. Useful for cleanup when shutting down R sessions or resetting state.

Usage

connection_pool_close_all(quiet = FALSE)

Arguments

quiet

Logical. If TRUE, suppresses messages (default: FALSE)

Value

Invisibly returns the number of pools closed


List active connection pools

Description

Shows all currently active connection pools with their status.

Usage

connection_pool_list()

Value

A data frame with pool information:


Restore a soft-deleted record

Description

Restores a soft-deleted record by setting deleted_at to NULL. Only works on tables with a deleted_at column.

Usage

connection_restore(conn, table_name, id)

Arguments

conn

Database connection

table_name

Name of the table

id

The ID of the record to restore

Value

Number of rows affected


Rollback a database transaction

Description

Rolls back the current transaction, discarding all changes.

Usage

connection_rollback(conn)

Arguments

conn

Database connection

Value

NULL (invisible)


Update a record in a table

Description

Updates an existing record in a table with automatic timestamp handling. If the table has an updated_at column, it will be set automatically.

Usage

connection_update(conn, table_name, id, values, auto_timestamps = TRUE)

Arguments

conn

Database connection

table_name

Name of the table

id

The ID of the record to update

values

Named list of column-value pairs to update

auto_timestamps

Whether to automatically set updated_at (default: TRUE)

Value

Number of rows affected


Execute code with a connection pool

Description

Convenience wrapper for working with connection pools. Gets or creates a pool and makes it available as pool within the code block.

Usage

connection_with_pool(connection_name, code, ...)

Arguments

connection_name

Character. Name of the connection in settings.yml

code

Expression to evaluate with the pool

...

Additional arguments passed to connection_pool()

Value

The result of evaluating code


Execute code with transaction if not already in one

Description

Similar to db_transaction(), but only starts a new transaction if not already in one. Useful for functions that can be called both standalone and within an existing transaction.

Usage

connection_with_transaction(conn, code)

Arguments

conn

Database connection

code

Expression or code block to execute

Value

The result of the code expression


List all connections (databases and object storage)

Description

Prints both database connections defined under ⁠connections:⁠ and object storage profiles (S3-compatible buckets). Use this to see everything Framework can talk to from your config.

Usage

connections_list()

Value

Invisibly returns NULL after printing summaries.


S3 Connection Functions

Description

Functions for connecting to and interacting with S3-compatible storage.


Add an existing file to the data catalog

Description

Registers an existing data file with the Framework data catalog. This allows you to track files that were created outside of Framework (e.g., downloaded from external sources, copied from other projects) and use them with data_read() using dot notation.

Usage

data_add(
  file_path,
  name = NULL,
  type = NULL,
  delimiter = "comma",
  locked = TRUE,
  update_config = TRUE
)

Arguments

file_path

Path to the existing file (must exist)

name

Optional dot notation name for the data catalog (e.g., inputs.raw.survey_data). If NULL, a file in a configured inputs directory is named after the directory's key and the file name: inputs/private/raw/participants.csv in inputs_private_raw becomes inputs.private.raw.participants. Files elsewhere use the file name alone.

type

Optional type override. Auto-detected from file extension if NULL.

delimiter

Delimiter for CSV files ("comma", "tab", "semicolon", "space")

locked

Whether the file should be locked (hash-verified on read)

update_config

If TRUE (default), also updates the YAML config with the data spec

Value

Invisibly returns the data spec that was created

Examples


if (FALSE) {
# Add a downloaded CSV file to the catalog
data_add("inputs/raw/survey_results.csv", name = "inputs.raw.survey_results")

# Now you can read it with dot notation
data_read("inputs.raw.survey_results")

# Add with auto-generated name
data_add("inputs/intermediate/cleaned_data.rds")
# Name will be derived as "inputs.intermediate.cleaned_data"
}



Get data specification from config

Description

Gets the data specification for a given dot notation path from settings.yml. Supports dot notation (e.g., "source.private.example"), relative paths, and absolute paths. Auto-detects file type from extension and applies intelligent defaults for common formats.

Usage

data_info(path)

Arguments

path

Dot notation path (e.g. "source.private.example"), relative path, or absolute path to a data file

Value

A list with data specification including:

Examples


if (FALSE) {
# Get info from dot notation
info <- data_info("source.private.my_data")

# Get info from file path
info <- data_info("data/public/example.csv")
}



List all data entries from config

Description

Lists all data specifications defined in the configuration, showing the data key, path, type, and description (if available).

Usage

data_list()

Value

A data frame with columns: name, path, type, locked, description

Examples


if (FALSE) {
# List all data entries
data_list()
}


Read data using dot notation path or direct file path

Description

Supports CSV, TSV, RDS, Excel (.xlsx, .xls), Stata (.dta), SPSS (.sav, .zsav, .por), and SAS (.sas7bdat, .xpt) file formats.

Usage

data_read(path, delim = NULL, keep_attributes = FALSE, ...)

Arguments

path

Dot notation path (e.g. "source.private.example") or direct file path

delim

Optional delimiter for CSV files ("comma", "tab", "semicolon", "space")

keep_attributes

Logical flag to preserve special attributes (e.g., haven labels). Default: FALSE (strips attributes)

...

Additional arguments passed to read functions (readr::read_delim, readxl::read_excel, haven::read_*, etc.)

Value

The loaded data, typically a data frame or tibble.


Read data with caching (DEPRECATED)

Description

[Deprecated]

This function is deprecated. Use cache_remember() with data_read() instead:

df <- cache_remember("my_data", data_read("source.private.example"))

Usage

data_read_or_cache(path, expire_after = NULL, refresh = FALSE)

Arguments

path

Dot notation path to load data (e.g. "source.private.example")

expire_after

Optional expiration time in hours (default: from config)

refresh

Optional boolean or function that returns boolean to force refresh

Value

The loaded data, either from cache or file


Save data using dot notation or file path

Description

Save data using dot notation or file path

Usage

data_save(
  data,
  path,
  type = NULL,
  delimiter = "comma",
  locked = TRUE,
  force = FALSE
)

Arguments

data

Data frame to save

path

Either:

  • Dot notation: inputs.raw.filename resolves to inputs/raw/filename.rds. A name may end in the extension: inputs.raw.filename.csv is the name inputs.raw.filename saved as CSV.

  • Direct path with a /: "inputs/raw/filename.csv". A relative path starts at the project root, not the working directory. framework.db records it relative to the project root with forward slashes, so "./inputs/raw/filename.csv" and "inputs/raw/filename.csv" are the same record.

A bare file name such as "filename.csv" is an error.

Dot notation uses your configured directories (e.g., inputs.raw, inputs.intermediate, outputs.private).

type

Type of data file ("csv" or "rds"). Auto-detected from extension if path includes one.

delimiter

Delimiter for CSV files ("comma", "tab", "semicolon", "space")

locked

Whether the file should be locked after saving

force

If TRUE, creates missing directories. If FALSE (default), errors if directory doesn't exist.

Value

Invisibly returns the saved data.


Get data specification (DEPRECATED)

Description

[Deprecated]

This function has been renamed to data_info(). Please use that instead.

Usage

data_spec_get(path)

Arguments

path

Dot notation path or file path

Value

A list with data specification


Verify a Dataset Against the Integrity Ledger

Description

Hashes the file behind a catalog name (or a file path) and compares it against the local framework.db record and the project's cloud ledger on Framework Cloud. Proves "the data I have is bit-identical to what was recorded" without the data ever leaving the machine.

Usage

data_verify(name)

Arguments

name

Data catalog name (e.g. "inputs.raw.enrollment") or a file path (e.g. "outputs/public/summary.csv"), as used with data_read() / data_save(). A path is relative to the project root.

Value

Invisibly, TRUE when no available record disagrees with the file. It prints which records were compared. With no framework.db record and no cloud ledger entry, nothing is compared: it says "Not verified" and still returns TRUE, as framework-py does.


Get a database connection

Description

Gets a database connection based on the connection name in settings.yml (or settings/connections.yml). SQLite and DuckDB paths are relative to the project root. For most use cases, prefer db_query() or db_execute() which handle connection lifecycle automatically.

Usage

db_connect(name)

Arguments

name

Character. Name of the connection in settings (e.g., "postgres")

Value

A database connection object (DBIConnection)

Examples


if (FALSE) {
# Preferred: use db_query() which auto-disconnects
users <- db_query("SELECT * FROM users", "postgres")

# Manual connection management (remember to disconnect!)
conn <- db_connect("postgres")
DBI::dbListTables(conn)
DBI::dbDisconnect(conn)
}



Install database drivers

Description

Interactive helper to install one or more database drivers. Provides helpful instructions and handles special cases (like ODBC).

Usage

db_drivers_install(drivers = NULL, repos = getOption("repos"))

Arguments

drivers

Character vector. Database driver names to install (e.g., "postgres", "mysql", "duckdb"). If NULL, shows interactive menu.

repos

Character. CRAN repository URL. Default: getOption("repos")

Value

NULL (invisible). Installs packages as side effect.

Examples


if (FALSE) {
# Install specific drivers
db_drivers_install(c("postgres", "mysql"))

# Interactive mode
db_drivers_install()
}



Check if database drivers are installed

Description

Checks which database drivers are currently available on the system. Returns a data frame showing the status of all supported database drivers.

Usage

db_drivers_status(quiet = FALSE)

Arguments

quiet

Logical. If TRUE, suppresses messages. Default: FALSE

Value

A data frame with columns:

Examples


# Check all drivers
db_drivers_status()

# Quiet mode (no messages)
db_drivers_status(quiet = TRUE)



Execute a database statement

Description

Executes a SQL statement on a database without returning results. The connection is created, used, and automatically closed.

Usage

db_execute(query, connection_name, ...)

Arguments

query

SQL statement to execute

connection_name

Name of the connection in settings.yml

...

Additional arguments passed to DBI::dbExecute

Value

Number of rows affected

Examples


if (FALSE) {
rows <- db_execute("DELETE FROM cache WHERE expired = TRUE", "my_db")
}



List all database connections from configuration

Description

Lists all database connections defined in the configuration, showing the connection name, driver, host, and database name (if applicable).

Usage

db_list()

Value

Invisibly returns NULL after printing connection list

Examples


if (FALSE) {
# List all connections
db_list()
}


Get data from a database query

Description

Gets data from a database using a query and connection name. The connection is created, used, and automatically closed.

Usage

db_query(query, connection_name, ...)

Arguments

query

SQL query to execute

connection_name

Name of the connection in settings.yml

...

Additional arguments passed to DBI::dbGetQuery

Value

A data frame with the query results

Examples


if (FALSE) {
users <- db_query("SELECT * FROM users", "my_db")
}



Execute code within a database transaction

Description

Wraps code execution in a database transaction with automatic commit on success and rollback on error. This ensures atomicity of multiple database operations.

Usage

db_transaction(conn, code)

Arguments

conn

Database connection

code

Expression or code block to execute within the transaction

Details

The function automatically:

Transactions are essential for maintaining data integrity when performing multiple related operations. If any operation fails, all changes are rolled back.

Value

The result of the code expression

Examples


if (FALSE) {
conn <- db_connect("postgres")

# Basic transaction
db_transaction(conn, {
  DBI::dbExecute(conn, "INSERT INTO users (name, age) VALUES ('Alice', 30)")
  DBI::dbExecute(conn, "INSERT INTO users (name, age) VALUES ('Bob', 25)")
})

# Transaction with error handling - auto-rollback on error
tryCatch({
  db_transaction(conn, {
    DBI::dbExecute(conn, "INSERT INTO users (name) VALUES ('Alice')")
    stop("Something went wrong")  # This will trigger rollback
  })
}, error = function(e) {
  message("Transaction failed: ", e$message)
})

DBI::dbDisconnect(conn)
}



Execute code with a managed database connection

Description

Provides automatic connection lifecycle management. The connection is automatically closed when the code block finishes, even if an error occurs. This prevents connection leaks and ensures proper resource cleanup.

Usage

db_with(connection_name, code)

Arguments

connection_name

Character. Name of the connection in settings.yml

code

Expression to evaluate with the connection (use conn to access the connection)

Value

The result of evaluating code

Examples


if (FALSE) {
# Safe - connection auto-closes
users <- db_with("my_db", {
  DBI::dbGetQuery(conn, "SELECT * FROM users WHERE active = TRUE")
})

# Multiple operations with same connection
result <- db_with("my_db", {
  DBI::dbExecute(conn, "INSERT INTO users (name) VALUES ('Alice')")
  DBI::dbGetQuery(conn, "SELECT * FROM users")
})

# Connection closes even on error
tryCatch(
  db_with("my_db", {
    stop("Something went wrong")  # Connection still closes
  }),
  error = function(e) message(e$message)
)
}



Export Package Documentation to Database

Description

Parses roxygen2-generated .Rd files and exports structured documentation to SQLite or other formats. This powers the searchable documentation website.

Usage

docs_export(
  output_path = "docs.db",
  man_dir = "man",
  package_name = "framework",
  package_version = NULL,
  include_internal = FALSE,
  verbose = TRUE,
  reference_path = NULL
)

Arguments

output_path

Path to SQLite database file. Default: "docs.db"

man_dir

Directory containing .Rd files. Default: "man"

package_name

Package name for metadata. Default: "framework"

package_version

Package version for metadata. Default: NULL (auto-detect)

include_internal

Include functions that are not exported or are tagged ⁠@keywords internal⁠ (such as .has_column()). Default: FALSE

verbose

Print progress messages. Default: TRUE

reference_path

If set, also write the reference for the docs site (docs/site/reference.json) to this path, in the format of inst/schema/docs-reference.v1.json. Default: NULL

Details

The exporter reads all .Rd files from the man/ directory and extracts:

The SQLite output includes FTS5 full-text search for fast querying.

Value

Invisibly returns the database connection path

Examples


if (FALSE) {
# Export to default location (exported functions only)
docs_export()

# Export to custom location
docs_export(tempfile(fileext = ".db"))

# Include internal/private functions too
docs_export("all_docs.db", include_internal = TRUE)

# Query the exported docs
con <- DBI::dbConnect(RSQLite::SQLite(), "docs.db")
DBI::dbGetQuery(con, "SELECT name, title FROM functions WHERE name LIKE 'data_%'")
DBI::dbDisconnect(con)
}



Check if a column exists in a table (S3 generic)

Description

Cross-database method to check if a column exists in a table. Uses database-specific introspection methods via S3 dispatch.

Usage

.has_column(conn, table_name, column_name)

## S3 method for class 'SQLiteConnection'
.has_column(conn, table_name, column_name)

## S3 method for class 'PqConnection'
.has_column(conn, table_name, column_name)

## S3 method for class 'MariaDBConnection'
.has_column(conn, table_name, column_name)

## S3 method for class ''Microsoft SQL Server''
.has_column(conn, table_name, column_name)

## S3 method for class 'duckdb_connection'
.has_column(conn, table_name, column_name)

## Default S3 method:
.has_column(conn, table_name, column_name)

Arguments

conn

Database connection (DBIConnection)

table_name

Character. Name of the table

column_name

Character. Name of the column to check

Value

Logical. TRUE if column exists, FALSE otherwise. The name must match exactly, including case.

Functions

Examples


if (FALSE) {
conn <- db_connect("my_db")
has_deleted_at <- .has_column(conn, "users", "deleted_at")
DBI::dbDisconnect(conn)
}


List all columns in a table (S3 generic)

Description

Cross-database method to list all columns in a table. Uses database-specific introspection methods via S3 dispatch.

Usage

.list_columns(conn, table_name)

## S3 method for class 'SQLiteConnection'
.list_columns(conn, table_name)

## S3 method for class 'PqConnection'
.list_columns(conn, table_name)

## S3 method for class 'MariaDBConnection'
.list_columns(conn, table_name)

## S3 method for class ''Microsoft SQL Server''
.list_columns(conn, table_name)

## S3 method for class 'duckdb_connection'
.list_columns(conn, table_name)

## Default S3 method:
.list_columns(conn, table_name)

Arguments

conn

Database connection (DBIConnection)

table_name

Character. Name of the table

Value

Character vector of column names

Functions

Examples


if (FALSE) {
conn <- db_connect("my_db")
columns <- .list_columns(conn, "users")
DBI::dbDisconnect(conn)
}


List all tables in a database (S3 generic)

Description

Cross-database method to list all tables. Uses database-specific methods via S3 dispatch.

Usage

.list_tables(conn)

## Default S3 method:
.list_tables(conn)

Arguments

conn

Database connection (DBIConnection)

Value

Character vector of table names

Functions

Examples


if (FALSE) {
conn <- db_connect("my_db")
tables <- .list_tables(conn)
DBI::dbDisconnect(conn)
}


Clear R environment

Description

Cleans up the R environment by removing objects, closing plots, detaching packages, and running garbage collection. Does not clear the console. Framework itself stays attached.

Usage

env_clear(keep = character(), envir)

Arguments

keep

Character vector of object names to keep (default: empty)

envir

The environment to clear. Required, so nothing is removed by accident. Use globalenv() for your workspace.

Value

Invisibly returns NULL

Examples


if (FALSE) {
# Clean your workspace
env_clear(envir = globalenv())

# Clean a specific environment
env_clear(envir = my_env)

# Keep specific objects
env_clear(keep = c("config", "data"), envir = my_env)
}


Default Framework .env template lines

Description

Provides the baseline .env content that ships with Framework. Other helper functions (project_create(), GUI scaffolders) reuse these lines when users haven't customized their own template.

Usage

env_default_template_lines()

Convert env() configuration into file lines

Description

Convert env() configuration into file lines

Usage

env_lines_from_variables(vars)

Resolve env template lines from configuration

Description

Resolve env template lines from configuration

Usage

env_resolve_lines(env_config = NULL)

Arguments

env_config

Either a character string (raw .env content) or a list with raw and/or variables.

Value

Character vector of lines ready to be written to .env


Summarize R environment

Description

Displays a summary of the current R environment including loaded packages, objects in the global environment, and memory usage.

Usage

env_summary(envir)

Arguments

envir

The environment to summarize. Use globalenv() for your workspace.

Value

Invisibly returns a list with environment information

Examples


if (FALSE) {
env_summary(envir = my_env)
}


Get the user-editable path for a Framework template

Description

Get the user-editable path for a Framework template

Usage

framework_template_path(name)

Arguments

name

Template identifier (e.g., "notebook", "gitignore", "ai_claude")

Value

Absolute path to the template file, ensuring it exists.


(Deprecated) Use view_create() or view_detail() instead

Description

[Deprecated]

framework_view() was renamed to view_create() to follow the package's noun_verb naming convention for better discoverability and consistency.

Recommended: Use view_detail() for the clearest, most user-friendly name.

Usage

framework_view(x, title = NULL, max_rows = 5000)

Arguments

x

The data to view (data.frame, plot, list, function, or other R object)

title

Optional title for the view. If NULL, uses the object name.

max_rows

Maximum number of rows to display for data frames (default: 5000). Large data frames are automatically truncated with a warning.

Value

Opens a browser window (called for side effects)


Get Framework config directory path

Description

Returns the path to Framework's global configuration directory, which holds user settings, the saved Framework Cloud server, and token files. Uses tools::R_user_dir("framework", "config") by default (CRAN compliant). Can be overridden with the FW_CONFIG_HOME environment variable.

Usage

fw_config_dir()

Details

The Python package and the fw command-line tool keep their own folder (⁠~/.config/framework⁠). config_sync() brings their settings into R's.

Value

Character string with the config directory path


Get default global configuration structure

Description

Get default global configuration structure

Usage

get_default_global_config()

Value

List with default global configuration


Get Global Configuration Setting

Description

Retrieve a specific setting from the global configuration file (~/.frameworkrc.json). This is a helper function primarily for use by the CLI script.

Usage

get_global_setting(key, default = "", print = TRUE)

Arguments

key

Character. The setting key to retrieve (e.g., "defaults.ide", "author.name")

default

Character. Default value if setting is not found (default: "")

print

Logical. If TRUE, prints the value (for bash consumption). Default TRUE.

Value

The setting value as a character string


Stage Files for Commit

Description

Add file contents to the staging area.

Usage

git_add(files = ".")

Arguments

files

Character vector of file paths to stage, or "." for all (default)

Value

Invisibly returns TRUE on success. Stops with git's message when nothing could be staged (a missing or ignored file, for example).

Examples


if (FALSE) {
git_add()              # Stage all changes
git_add("README.md")   # Stage specific file
git_add(c("R/foo.R", "R/bar.R"))
}



Commit Staged Changes

Description

Record changes to the repository with a commit message.

Usage

git_commit(message, all = FALSE)

Arguments

message

Commit message (required)

all

Logical; if TRUE, automatically stage modified/deleted files (default: FALSE)

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
git_commit("Fix bug in data loading")
git_commit("Update README", all = TRUE)  # Stage and commit
}



Show Changes (Diff)

Description

Show changes between commits, working tree, etc.

Usage

git_diff(staged = FALSE, file = NULL)

Arguments

staged

Logical; if TRUE, show staged changes (default: FALSE shows unstaged)

file

Optional file path to show diff for specific file

Value

Invisibly returns the diff output as a character vector

Examples


if (FALSE) {
git_diff()             # Show unstaged changes
git_diff(staged = TRUE) # Show staged changes
git_diff(file = "R/foo.R")
}



Disable Specific Git Hook

Description

Disables a specific hook in settings and reinstalls the pre-commit hook.

Usage

git_hooks_disable(hook_name, config_file = NULL, verbose = TRUE)

Arguments

hook_name

Name of hook: "data_security", "check_sensitive_dirs", or "check_notebook_outputs"

config_file

Path to configuration file (default: auto-discover settings.yml or settings.yml)

verbose

Logical; if TRUE (default), show messages

Value

Invisible TRUE on success


Enable Specific Git Hook

Description

Enables a specific hook in settings and reinstalls the pre-commit hook.

Usage

git_hooks_enable(hook_name, config_file = NULL, verbose = TRUE)

Arguments

hook_name

Name of hook: "data_security", "check_sensitive_dirs", or "check_notebook_outputs"

config_file

Path to configuration file (default: auto-discover settings.yml or settings.yml)

verbose

Logical; if TRUE (default), show messages

Value

Invisible TRUE on success

Examples


if (FALSE) {
git_hooks_enable("check_sensitive_dirs")
git_hooks_enable("data_security")
}



Install Git Pre-commit Hook

Description

Creates a pre-commit hook that runs Framework checks based on settings.yml settings.

Usage

git_hooks_install(config_file = NULL, force = FALSE, verbose = TRUE)

Arguments

config_file

Path to configuration file (default: "settings.yml")

force

Logical; if TRUE, overwrite existing hook (default: FALSE)

verbose

Logical; if TRUE (default), show installation messages

Details

Installs Framework's pre-commit script where git looks for it (worktrees and core.hooksPath included). The script is shared with the Python package and fw: it finds an R or Python runtime and runs the hooks enabled in settings.yml, so enabling or disabling a hook later needs no reinstall. A pre-commit hook Framework wrote earlier is replaced; any other hook is kept unless force = TRUE. The enabled hooks:

Hook behavior is controlled by ⁠git.hooks.*⁠ settings in settings.yml. The ai_sync hook was removed in 2.0: skills and AGENTS.md replace it, and an ai_sync setting left in settings.yml is ignored.

Value

Invisible TRUE on success, FALSE on failure

Examples


if (FALSE) {
# Install hooks based on settings.yml
git_hooks_install()

# Force reinstall (overwrites existing hook)
git_hooks_install(force = TRUE)
}



List Git Hook Status

Description

Shows which hooks are enabled and their current status.

Usage

git_hooks_list(config_file = NULL)

Arguments

config_file

Path to configuration file (default: auto-discover settings.yml or settings.yml)

Value

Data frame with hook information


Uninstall Git Pre-commit Hook

Description

Removes the Framework-managed pre-commit hook.

Usage

git_hooks_uninstall(verbose = TRUE)

Arguments

verbose

Logical; if TRUE (default), show messages

Value

Invisible TRUE if hook was removed, FALSE otherwise


Show Commit Log

Description

Show recent commit history.

Usage

git_log(n = 10, oneline = TRUE)

Arguments

n

Number of commits to show (default: 10)

oneline

Logical; if TRUE, show condensed one-line format (default: TRUE)

Value

Invisibly returns the log output as a character vector

Examples


if (FALSE) {
git_log()
git_log(n = 5)
git_log(oneline = FALSE)  # Full format
}



Pull from Remote

Description

Fetch and integrate changes from the remote repository.

Usage

git_pull(remote = "origin", branch = NULL)

Arguments

remote

Remote name (default: "origin")

branch

Branch name (default: current branch)

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
git_pull()
git_pull(remote = "origin", branch = "main")
}



Push to Remote

Description

Push commits to the remote repository.

Usage

git_push(remote = "origin", branch = NULL)

Arguments

remote

Remote name (default: "origin")

branch

Branch name (default: current branch). When the branch has no upstream yet, it is pushed with --set-upstream, so later pulls and pushes need no arguments.

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
git_push()
git_push(remote = "origin", branch = "main")
}



Security audit for Framework projects

Description

Performs a comprehensive security audit of data files in Framework projects, checking for unignored data files, git history leaks, and orphaned data files outside configured directories.

Usage

git_security_audit(
  config_file = NULL,
  check_git_history = TRUE,
  history_depth = "all",
  auto_fix = FALSE,
  verbose = TRUE,
  extensions = c("csv", "rds", "tsv", "txt", "dat", "xlsx", "xls", "sqlite", "db", "dta",
    "sav", "zsav", "por", "sas7bdat", "sas7bcat", "xpt", "parquet", "feather", "arrow",
    "json", "xml", "h5", "hdf5")
)

Arguments

config_file

Path to configuration file (default: auto-detect settings.yml/settings.yml)

check_git_history

Logical; if TRUE (default), check git history for leaked data files

history_depth

Character or numeric. "all" for full history, "shallow" for recent 100 commits, or numeric for specific commit count (default: "all")

auto_fix

Logical; if TRUE, automatically update .gitignore (default: FALSE)

verbose

Logical; if TRUE (default), show progress messages

extensions

Character vector of data file extensions to detect (default: common data formats)

Details

The security audit performs the following checks. Each is a row of summary (named by its check), and its details are in findings under the key in brackets:

Status levels:

Value

A structured list containing:

summary

Data frame with check names, status (pass/warning/fail), and counts

findings

List of data frames with detailed findings for each check

recommendations

Character vector of actionable recommendations

audit_metadata

List with audit timestamp, Framework version, and config info

Examples


if (FALSE) {
# Basic audit (report only)
audit <- git_security_audit()
print(audit$summary)
View(audit$findings$orphaned_files)

# Quick scan without git history
audit <- git_security_audit(check_git_history = FALSE)

# Verbose with limited git history
audit <- git_security_audit(history_depth = 100, verbose = TRUE)

# Auto-fix mode (updates .gitignore)
audit <- git_security_audit(auto_fix = TRUE)
}



Show Git Status

Description

Display the working tree status from the R console.

Usage

git_status(short = FALSE)

Arguments

short

Logical; if TRUE, show short format (default: FALSE)

Details

For a project inside another git repository (the project folder is not the repository's top folder), it says so: the status is the enclosing repository's.

Value

Invisibly returns the status output as a character vector

Examples


if (FALSE) {
git_status()
git_status(short = TRUE)
}



Framework GUI (deprecated)

Description

The local GUI is retired. Framework Cloud at https://framework.pub manages projects, defaults, and settings.

Usage

gui(...)

Arguments

...

Ignored.

Value

Invisibly NULL, with a deprecation warning.

Examples


if (FALSE) {
gui()
}



Initialize global Framework settings

Description

Creates the Framework config directory (via fw_config_dir()) and copies default settings files if they don't already exist. Also handles migration from previous R versions or legacy ⁠~/.config/framework⁠ location.

Usage

init_global_config(force = FALSE)

Arguments

force

If TRUE, overwrites existing settings (default: FALSE)

Value

Invisibly returns NULL


List the Project's Cloud Ledger

Description

List the Project's Cloud Ledger

Usage

ledger_list(name = NULL)

Arguments

name

Optional data catalog name to filter by.

Value

A data.frame of ledger entries, newest first.


Import the Local Ledger into the Cloud

Description

Reads the project's local framework.db (the SQLite ledger of record that data_save() always maintains) and appends any digests the cloud ledger does not yet have. This is the default way project history reaches Framework Cloud: an explicit, reviewable action rather than a network call on every save.

Usage

ledger_push()

Details

For per-save streaming instead – tamper-evident, since each entry lands before the file could be altered – set FW_LEDGER=live or options: cloud_ledger: live in the project's settings.yml.

Value

Invisibly, a list with pushed and up_to_date counts.

See Also

data_verify(), ledger_list()


List available framework templates

Description

List available framework templates

Usage

list_framework_templates()

List all metadata

Description

List all metadata

Usage

list_metadata()

Value

A data frame of metadata with keys, values, and timestamps


Read the Framework settings catalog

Description

The catalog defines metadata (labels, hints) and default values for settings sections. Users can override the packaged defaults by placing a settings-catalog.yml file in their Framework config directory (tools::R_user_dir("framework", "config")). When an override exists it is merged on top of the packaged catalog.

Usage

load_settings_catalog(include_user = TRUE, validate = TRUE)

Arguments

include_user

Logical indicating whether to merge user overrides. Defaults to TRUE.

validate

Logical indicating whether to perform basic validation on the catalog structure. Defaults to TRUE.

Value

A nested list representing the settings catalog.


Create a Notebook or Script from Stub Template

Description

Creates a new Quarto (.qmd), RMarkdown (.Rmd) notebook, or R script (.R) from stub templates. Searches for user-provided stubs first (in ⁠stubs/⁠ directory), then falls back to framework defaults.

Usage

make_notebook(
  name,
  type = NULL,
  dir = NULL,
  stub = "default",
  overwrite = FALSE,
  subdir = NULL
)

Arguments

name

Character. The file name. Extension determines type:

  • .qmd: Quarto notebook (default if no extension)

  • .Rmd: RMarkdown notebook

  • .R: R script Examples: 1-init, 1-init.qmd, analysis.Rmd, script.R

type

Character. File type: "quarto", "rmarkdown", "script", or "jupyter" (an .ipynb for the R kernel). Auto-detected from extension if provided. If NULL (default):

  1. Checks the project's scaffold.notebook_format (or legacy default_notebook_format and options$default_notebook_format), ignoring "quarto" when the project turned the Quarto tool off

  2. Falls back to "quarto", unless the project turned the Quarto tool off: then "jupyter" when the Jupyter tool is on, "rmarkdown" when rmarkdown is installed, and "script" otherwise

dir

Character. Directory to create the file in. Uses your project's configured directories$notebooks setting. Default: "notebooks/". A relative path starts at the project root, not the working directory.

stub

Character. Name of the stub template to use. Defaults to "default". User can create custom stubs in ⁠stubs/notebook-{stub}.qmd⁠, ⁠stubs/notebook-{stub}.Rmd⁠, or ⁠stubs/script-{stub}.R⁠.

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

subdir

Optional subdirectory under dir (e.g., "analyses/exploratory").

Details

Convenient aliases: Use make_qmd() or make_rmd() for explicit Quarto or RMarkdown notebook creation. Use make_revealjs() or make_presentation() for reveal.js presentations.

Default Output

Notebooks are created in the ⁠notebooks/⁠ directory by default:

notebooks/
  1-data-cleaning.qmd
  2-analysis.qmd
  3-visualization.qmd

Extension Normalization

Stub Template Resolution

The function searches for stub templates in this order:

  1. User stubs: ⁠stubs/notebook-{stub}.qmd⁠ or ⁠stubs/notebook-{stub}.Rmd⁠

  2. Framework stubs: ⁠inst/stubs/notebook-{stub}.qmd⁠ or ⁠inst/stubs/notebook-{stub}.Rmd⁠

Custom stub templates can use placeholders:

Value

Invisible path to created notebook

See Also

make_qmd(), make_rmd(), make_revealjs(), make_presentation()

Examples


if (FALSE) {
# Create notebooks/1-init.qmd (defaults to Quarto)
make_notebook("1-init")

# Create notebooks/analysis.Rmd (RMarkdown, extension-based)
make_notebook("analysis.Rmd")

# Explicit type parameter
make_notebook("report", type = "rmarkdown")

# Use custom stub template
make_notebook("report", stub = "minimal")

# Create in specific directory
make_notebook("explore", dir = "work")

# Convenient aliases (recommended for explicit types)
make_qmd("analysis")       # Creates .qmd
make_rmd("report")         # Creates .Rmd
# An extension in the name wins over the alias, as in the Python package:
# make_qmd("report.Rmd") creates an .Rmd
make_revealjs("slides")    # Creates reveal.js presentation
make_presentation("deck")  # Alias for make_revealjs()
}



Create a Presentation

Description

Alias for make_revealjs(). Creates a Quarto reveal.js presentation.

Usage

make_presentation(name, dir = NULL, overwrite = FALSE, subdir = NULL)

Arguments

name

Character. The presentation name (with or without .qmd extension)

dir

Character. Directory to create the file in. Uses your project's configured directories$notebooks setting. Default: "notebooks/". A relative path starts at the project root, not the working directory.

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

subdir

Optional subdirectory under dir (e.g., "slides/week-01").

Value

Invisible path to created presentation

See Also

make_notebook(), make_revealjs()

Examples


if (FALSE) {
# Create notebooks/deck.qmd with reveal.js format
make_presentation("deck")
}



Create a Quarto Notebook

Description

Convenient alias for make_notebook(type = "quarto"). Creates a .qmd file from stub templates.

Usage

make_qmd(name, dir = NULL, stub = "default", overwrite = FALSE, subdir = NULL)

Arguments

name

Character. The file name (with or without .qmd extension). Another extension wins: "x.Rmd" creates a .Rmd file.

dir

Character. Directory to create the file in. Uses your project's configured directories$notebooks setting. Default: "notebooks/". A relative path starts at the project root, not the working directory.

stub

Character. Name of the stub template to use. Default "default".

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

subdir

Optional subdirectory under dir (e.g., "slides/week-01").

Value

Invisible path to created notebook

See Also

make_notebook(), make_rmd()

Examples


if (FALSE) {
# Create notebooks/analysis.qmd
make_qmd("analysis")

# Use custom stub
make_qmd("report", stub = "minimal")

# Create in specific directory
make_qmd("explore", dir = "work")
}



Create a Reveal.js Presentation

Description

Convenient alias for creating reveal.js presentations. Always creates a Quarto notebook with the revealjs stub template.

Usage

make_revealjs(name, dir = NULL, overwrite = FALSE, subdir = NULL)

Arguments

name

Character. The presentation name (with or without .qmd extension)

dir

Character. Directory to create the file in. Uses your project's configured directories$notebooks setting. Default: "notebooks/". A relative path starts at the project root, not the working directory.

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

subdir

Optional subdirectory under dir (e.g., "slides/week-01").

Value

Invisible path to created presentation

See Also

make_notebook(), make_qmd(), make_presentation()

Examples


if (FALSE) {
# Create notebooks/slides.qmd with reveal.js format
make_revealjs("slides")

# Create in specific directory
make_revealjs("presentation", dir = "presentations")
}



Create an RMarkdown Notebook

Description

Convenient alias for make_notebook(type = "rmarkdown"). Creates a .Rmd file from stub templates.

Usage

make_rmd(name, dir = NULL, stub = "default", overwrite = FALSE, subdir = NULL)

Arguments

name

Character. The file name (with or without .Rmd extension). Another extension wins: "x.qmd" creates a .qmd file.

dir

Character. Directory to create the file in. Uses your project's configured directories$notebooks setting. Default: "notebooks/". A relative path starts at the project root, not the working directory.

stub

Character. Name of the stub template to use. Default "default".

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

subdir

Optional subdirectory under dir (e.g., "analyses/exploratory").

Value

Invisible path to created notebook

See Also

make_notebook(), make_qmd()

Examples


if (FALSE) {
# Create notebooks/analysis.Rmd
make_rmd("analysis")

# Use custom stub
make_rmd("report", stub = "minimal")

# Create in specific directory
make_rmd("explore", dir = "work")
}



Create an R Script from Stub Template

Description

Convenience wrapper for make_notebook() that creates R scripts (.R files). This is identical to calling make_notebook("name.R").

Usage

make_script(name, dir = NULL, stub = "default", overwrite = FALSE)

Arguments

name

Character. The script name (with or without .R extension). Examples: "process-data", "process-data.R"

dir

Character. Directory to create the script in. Uses your project's configured directories$scripts setting. Default: "scripts/". A relative path starts at the project root, not the working directory.

stub

Character. Name of the stub template to use. Defaults to "default", the only script stub Framework ships. Create custom stubs in ⁠stubs/script-{stub}.R⁠, or save your default with write_framework_template("script", ...).

overwrite

Logical. Whether to overwrite existing file. Default FALSE.

Details

This function is a convenience wrapper that:

  1. Ensures the name ends with .R extension

  2. Uses script_dir config option instead of notebook_dir

  3. Calls make_notebook() with type = "script"

Default Output

Scripts are created in the ⁠scripts/⁠ directory by default:

scripts/
  process-data.R
  build-features.R
  run-model.R

Value

Invisible path to created script

See Also

make_notebook() for creating Quarto/RMarkdown notebooks

Examples


if (FALSE) {
# Create script (extension optional)
make_script("process-data")
make_script("process-data.R")

# Use a custom stub: save it as stubs/script-etl.R first
make_script("etl-pipeline", stub = "etl")

# Create in specific directory
make_script("analysis", dir = "analysis/")
}



Create a New Project (Master Wrapper)

Description

Flexible project creation interface. Alias for new_project() that accepts type as a parameter.

Usage

new(
  name = NULL,
  location = NULL,
  type = NULL,
  browse = interactive(),
  key = NULL,
  url = NULL,
  ...
)

Arguments

name

Project name. If NULL (default), prompts interactively.

location

Directory path where project will be created. If NULL (default), prompts interactively.

type

Project type, as in new_project(). NULL (default): signed in to Framework Cloud, your default blueprint is used. Not signed in, an interactive session asks, with the Standard Project ("project") first, and a non-interactive one makes a "project". Pass type = "bare" for a bare project.

browse

Whether to open the project folder after creation (default: TRUE in interactive sessions)

key

A Framework Cloud project token. When given, the project's definition is fetched from the cloud (as with setup("fw_...")) and name and type come from it. The token is saved in the new project's .env for publish() and the ledger.

url

With key: the Framework Cloud server that issued the token. Defaults to FW_CLOUD_URL, then the server you last logged in to with cloud_login(), then https://framework.pub.

...

Ignored, with a warning.

Details

new_project() is the preferred name. new() remains available for existing scripts. Its name can mask methods::new() when attached.

Value

Invisibly returns the result from project_create()

See Also

new_project(), new_project_sensitive(), new_presentation(), new_course()

Examples


if (FALSE) {
# Create different project types
new("analysis", "~/projects/analysis")
new("study", "~/projects/study", type = "project_sensitive")
new("slides", "~/projects/slides", type = "presentation")
new("course-materials", "~/projects/course", type = "course")

# A project defined on Framework Cloud
new(key = "1|fw_abc123...", location = "~/projects/study")
}



Create a Course Project

Description

Shorthand for new_project(..., type = "course"). Creates a project structured for teaching materials with slides, assignments, and modules.

Usage

new_course(name = NULL, location = NULL, browse = interactive(), ...)

Arguments

name

Project name. If NULL (default), prompts interactively.

location

Directory path where project will be created. If NULL (default), prompts interactively.

browse

Whether to open the project folder after creation (default: TRUE in interactive sessions)

...

Ignored, with a warning.

Value

Invisibly returns the result from project_create()

See Also

new_project()

Examples


if (FALSE) {
new_course("stats-101", "~/projects/stats-101")
}



Create a Presentation Project

Description

Shorthand for new_project(..., type = "presentation"). Creates a project optimized for RevealJS presentations.

Usage

new_presentation(name = NULL, location = NULL, browse = interactive(), ...)

Arguments

name

Project name. If NULL (default), prompts interactively.

location

Directory path where project will be created. If NULL (default), prompts interactively.

browse

Whether to open the project folder after creation (default: TRUE in interactive sessions)

...

Ignored, with a warning.

Value

Invisibly returns the result from project_create()

See Also

new_project()

Examples


if (FALSE) {
new_presentation("quarterly-review", "~/projects/q4-review")
}



Create a New Framework Project

Description

Convenience wrapper for creating Framework projects from the command line. Uses your global settings (or your Framework Cloud defaults) as defaults, prompts for missing required values (name and location).

Usage

new_project(
  name = NULL,
  location = NULL,
  type = NULL,
  browse = interactive(),
  tools = NULL,
  package_sets = NULL,
  skill_sets = NULL,
  workflow = NULL,
  offline = FALSE,
  key = NULL,
  url = NULL,
  ...
)

Arguments

name

Project name. If NULL (default), prompts interactively.

location

Directory path where project will be created. If NULL (default), prompts interactively.

type

Project type: one of Framework's structures, "project", "project_sensitive", "course", "presentation", or "bare". NULL (default) uses your default blueprint on Framework Cloud when you are signed in, and "project" otherwise.

browse

Whether to open the project folder after creation (default: TRUE in interactive sessions)

tools

Tools to turn on, such as "quarto", "quarto_slides", "targets", "renv", or "jupyter": a character vector, or a named logical that can also turn a structure's tool off, as in c(quarto = FALSE, targets = TRUE). Tools a tool needs are added. NULL (default) keeps the structure's tools: Quarto for every structure except bare.

package_sets

Character vector of package sets to add, such as "tidyverse-analysis".

skill_sets

Character vector of AI skill sets to install, such as "framework" and "ggplot2". NULL (default) installs both. A sensitive project also gets the sensitive-data skill.

workflow

How notebooks are written: "quarto", "jupyter" (Quarto stays on for rendering), or "scripts" (plain R scripts, no notebook tools). NULL (default) keeps your default, or the structure's: Quarto for every structure except bare.

offline

When you are signed in to Framework Cloud, new_project() sends your choices to it and builds the project it resolves. If the cloud can't be reached, your saved cloud defaults are used when you made no choices beyond the name. Otherwise an interactive session asks before using Framework's built-in defaults, and a non-interactive one stops. Successful projects are registered with their choices on Cloud and linked through a project token in the ignored .env file. offline = TRUE skips the cloud: saved defaults when there are any, else the built-ins. Not signed in, the built-ins are used.

key

Optional Framework Cloud project token.

url

Optional Framework Cloud server URL for key.

...

Ignored, with a warning.

Details

This function is designed for the streamlined workflow:

remotes::install_github("table1/framework")
framework::new_project()  # Create projects using saved defaults

Global settings from tools::R_user_dir("framework", "config") are used for:

Value

Invisibly returns the result from project_create() (list with success, path, and project_id)

See Also

cloud_login() to use your Framework Cloud defaults, project_create() for full control

Examples


if (FALSE) {
# Interactive - prompts for name and location
new_project()

# With name and location specified
new_project("my-analysis", "~/projects/my-analysis")

# Create a sensitive data project
new_project("medical-study", "~/projects/medical", type = "project_sensitive")
}



Create a Sensitive Data Project

Description

Shorthand for new_project(..., type = "project_sensitive"). Creates a project with additional privacy protections for handling sensitive data.

Usage

new_project_sensitive(
  name = NULL,
  location = NULL,
  browse = interactive(),
  ...
)

Arguments

name

Project name. If NULL (default), prompts interactively.

location

Directory path where project will be created. If NULL (default), prompts interactively.

browse

Whether to open the project folder after creation (default: TRUE in interactive sessions)

...

Ignored, with a warning.

Value

Invisibly returns the result from project_create()

See Also

new_project()

Examples


if (FALSE) {
new_project_sensitive("medical-study", "~/projects/medical")
}



Get current datetime

Description

Get current datetime

Usage

now()

Value

Current datetime as an ISO 8601 formatted character string


Output Save Functions

Description

First-class functions for saving tables, figures, models, and reports. These functions implement lazy directory creation with console feedback.


Add a package to the project

Description

Records a package in the project's settings (in settings/packages.yml when the project uses split settings files, otherwise in settings.yml) and installs it if it isn't installed yet. Recording the package is what makes it reproducible: scaffold() and packages_install() install everything listed, and auto-attached packages are loaded by scaffold().

Usage

package_add(package, auto_attach = FALSE, install = TRUE)

Arguments

package

Package specification: "janitor", a pinned CRAN version ("dplyr@1.1.0"), a GitHub repository ("tidyverse/dplyr@main"), or a Bioconductor package ("bioc::DESeq2").

auto_attach

Logical. Whether scaffold() loads the package. Default FALSE.

install

Logical. Install the package now if it isn't installed (or the installed version doesn't match a pin). Default TRUE. If the install fails, the settings are left as they were and package_add() stops.

Details

Adding a package that is already listed replaces its entry, so this is also how to pin a version or turn auto-attach on or off.

Value

Invisibly, the package entry that was recorded.

See Also

packages_list(), packages_install()

Examples


if (FALSE) {
package_add("janitor")
package_add("forcats", auto_attach = TRUE)
package_add("tidyverse/dplyr@main")
package_add("dplyr@1.1.0")
}


Add a package set to the project

Description

Adds a package set's packages to an existing project. Packages the project already lists are left as they are. The rest are recorded as package_add() records them, with each package's source, repository, and auto-attach setting from the set. Sets also stack at creation with new_project(package_sets = ...).

Usage

package_set_add(set, install = TRUE)

Arguments

set

Package set id or Framework Cloud handle.

install

Logical. Install the added packages now. Default TRUE. A failed install leaves the package recorded and warns.

Details

A set is one of Framework's built-in sets for R, such as "tidyverse-analysis" or "bayes-r". See package_sets_list(). When you are signed in to Framework Cloud, a handle such as "@yourname/lab-tools" adds one of your account's sets.

Value

Invisibly, a list with added and present: the names of the packages added and those the project already listed.

See Also

package_sets_list(), package_add()

Examples


if (FALSE) {
package_set_add("bayes-r")
package_set_add("tidy-omop", install = FALSE)
}


List package sets

Description

Framework's built-in package sets for R projects. Add one to a project with package_set_add(), or at creation with new_project(package_sets = ...).

Usage

package_sets_list()

Value

A data frame with id, name, description, and packages (the package names, comma-separated).

See Also

package_set_add()

Examples

package_sets_list()

Install packages from configuration

Description

Installs all packages defined in the configuration that are not already installed. This is the same logic used in scaffold(), but exposed as a standalone function.

Usage

packages_install()

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
# Install all configured packages
packages_install()
}


List all packages from configuration

Description

Lists all packages defined in the configuration, showing the package name, version pin (if specified), and source (CRAN or GitHub).

Usage

packages_list()

Value

Invisibly returns NULL after printing package list

Examples


if (FALSE) {
# List all packages
packages_list()
}


Restore packages from renv.lock

Description

Wrapper around renv::restore() that requires Framework's renv integration to be enabled first.

Usage

packages_restore(prompt = FALSE)

Arguments

prompt

Logical. If TRUE, renv prompts before restoring.

Value

Invisibly returns TRUE on success.


Snapshot current package library (renv)

Description

Wrapper around renv::snapshot() that requires Framework's renv integration to be enabled first.

Usage

packages_snapshot(prompt = FALSE)

Arguments

prompt

Logical. If TRUE, renv prompts before writing the snapshot.

Value

Invisibly returns TRUE on success.


Show package status

Description

With Framework's renv integration on, a wrapper around renv::status(). With renv off, there is no lockfile to compare with, so it reports which packages in settings.yml are installed instead of stopping.

Usage

packages_status()

Value

With renv on, the status object returned by renv::status(). With renv off, invisibly a data frame with columns package, installed, and version, one row per package in settings.yml.


Update packages from configuration

Description

Updates packages defined in the configuration. If renv is enabled, uses renv::update(). Otherwise, reinstalls packages using standard installation methods.

Usage

packages_update(packages = NULL)

Arguments

packages

Character vector of specific packages to update, or NULL to update all

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
# Update all packages
packages_update()

# Update specific packages
packages_update(c("dplyr", "ggplot2"))
}


Add custom directories to an existing project

Description

Adds new directories to a project's configuration and creates them on the filesystem. This function is used by the GUI to allow users to add custom directories to their project structure without modifying existing directories.

Usage

project_add_directory(project_path, key, label, path)

Arguments

project_path

Character string. Absolute path to the project root directory.

key

Character string. Internal key for the directory (e.g., "analysis_archive"). An extra_directories entry with the same key is replaced.

label

Character string. Human-readable label for the directory (e.g., "Analysis Archive").

path

Character string. Relative path where the directory should be created (e.g., "analysis/archive"). Must be relative, not absolute. Parent directories will be created as needed.

Details

This function performs the following steps, as the Python package does:

  1. Validates all input arguments

  2. Finds the project's settings.yml (or config.yml)

  3. Creates the directory on the filesystem (with recursive creation)

  4. Records it under extra_directories in that file, as key, label, and path. An entry with the same key is replaced, so a second call with the same key updates it.

Core directories under directories are not checked or changed.

The function follows a non-destructive, additive-only approach. It will not:

Value

List with success status and directory information:

Safety

The function includes several safety checks:


Create a new Framework project (internal)

Description

Low-level function that creates a complete Framework project. This is called by user-facing functions like new() and new_project(). Users should typically use new() instead.

Usage

project_create(
  name,
  location,
  type = "project",
  author = list(name = "", email = "", affiliation = ""),
  packages = list(use_renv = FALSE, default_packages = list()),
  directories = list(),
  extra_directories = list(),
  ai = list(enabled = FALSE, assistants = c(), canonical_content = ""),
  git = list(use_git = TRUE, hooks = list(), gitignore_content = ""),
  scaffold = list(seed_on_scaffold = FALSE, seed = "", set_theme_on_scaffold = TRUE,
    ggplot_theme = "theme_minimal"),
  connections = NULL,
  env = NULL,
  quarto = NULL,
  render_dirs = NULL
)

Arguments

name

Project name (used for project title)

location

Full path to the project directory (will be created)

type

Project type: "project", "project_sensitive", "course", "presentation"

author

List with name, email, affiliation

packages

List with use_renv (logical) and default_packages (list of package configs)

directories

Named list of directory paths (notebooks, scripts, functions, etc.)

extra_directories

List of additional custom directories

ai

List with enabled, assistants, canonical_content

git

List with use_git, hooks, gitignore_content. With use_git, a project inside an existing git work tree is left to that repository: no git init and no initial commit.

scaffold

List with seed_on_scaffold, seed, set_theme_on_scaffold, ggplot_theme, ide, positron

quarto

List with html and revealjs format configurations for Quarto

render_dirs

Named list of render directory paths for Quarto outputs

Value

List with success status, project path, and project ID


Create a Project from a Layers File

Description

Reads a .framework/layers.json file (the format framework.pub sends), resolves it with spec_resolve(), and creates the project in path. This is the entry point the framework.pub GitHub Action runs, and it can also be used locally.

Usage

project_create_from_layers(layers_file, path = ".", interactive = FALSE)

Arguments

layers_file

Path to a layers file (see inst/schema/layers.v1.json).

path

Directory to create the project in (default: current directory).

interactive

If FALSE, run headless as described above.

Details

With interactive = FALSE it runs headless, for automation: it never prompts, does not initialize git or make a commit (the caller owns the repository), does not add the project to the local registry, and refuses to write under ⁠.github/workflows/⁠. In that mode path may be an existing git checkout that contains only ⁠.git/⁠, ⁠.github/⁠, ⁠.framework/⁠, README.md, and LICENSE. Anything else in it is an error, so a misconfigured run cannot overwrite real work.

Value

Invisibly, a list with success, path, and the resolved spec.

See Also

spec_resolve(), project_create()

Examples


if (FALSE) {
# In the framework.pub GitHub Action
project_create_from_layers(".framework/layers.json", path = ".", interactive = FALSE)
}



Display project structure information

Description

Shows configured directories and their status (created or pending lazy creation). Useful for understanding the project structure and discovering available paths.

Usage

project_info(verbose = FALSE)

Arguments

verbose

Has no effect. Every section is always shown, including the project name and type that verbose adds in the Python package.

Value

A data frame with directory information (invisibly)

Examples


if (FALSE) {
# Show project structure
project_info()

}



List all projects in global configuration

Description

Lists the projects in the registry. A project whose folder no longer exists (such as one made in a temporary folder) is marked exists = FALSE and a message names it; remove it with remove_project_from_config().

Usage

project_list()

Value

Data frame with columns id, path, created, and exists


Publishing Functions

Description

Functions for publishing notebooks, data, and files to S3 storage or Framework Cloud.

Publish files, directories, and R objects to named Cloud, GitHub, folder, or S3 destinations. publish_notebook() renders Quarto documents. publish_data() retains the low-level bucket export API.

Usage

publish(
  source,
  dest = NULL,
  connection = NULL,
  overwrite = TRUE,
  self_contained = TRUE,
  slug = NULL,
  include_private = FALSE,
  to = NULL,
  title = NULL,
  description = NULL,
  kind = NULL,
  password = NULL,
  visibility = NULL,
  collection = NULL,
  share_unlisted = FALSE
)

Arguments

source

A local file or rendered directory path, or an R object. publish() converts these objects to files:

  • Data frames, tibbles, data.tables, matrices, and table or xtabs contingency tables become a table with every row, a profile of each column, and variable labels from attr(x, "label"). Row names that aren't 1 to n become a first column named row.

  • anova() results and summary(aov) become an ANOVA table.

  • Hypothesis tests (htest objects from t.test(), chisq.test(), wilcox.test(), cor.test(), prop.test(), fisher.test(), shapiro.test(), and similar) become a test summary with the method, statistic, parameters, p-value, estimates, and confidence interval. The data name is left out.

  • lm, glm, aov, MASS::glm.nb, MASS::polr, nnet::multinom, lme4 (lmer, glmer), survival::coxph, survival::survreg, fixest, and mgcv::gam models become coefficients with standard errors and 95% Wald intervals, fit statistics, and a description of the model. Mixed models add random effects and gam models add smooth terms. Models never carry observations, residuals, fitted values, or the model object itself.

  • ggplot and patchwork plots, base graphics saved with recordPlot(), and lattice plots become an SVG figure (7 by 5 inches, white background) when svglite is installed, otherwise a 300 dpi PNG. An SVG larger than 5 MB is replaced by a PNG.

  • plotly and other htmlwidgets become a self-contained HTML file, which needs pandoc (Quarto's copy is used when pandoc isn't on the PATH).

  • gt, gtsummary, and flextable tables become HTML when their packages are installed.

Framework Cloud receives tables, tests, and models as structured JSON. Legacy storage uploads receive CSV tables, HTML summaries for lm and glm, and JSON for other models and tests. Named destinations receive typed bundles with offline readers and SHA-256 file manifests.

dest

Character or NULL. Destination path in S3 bucket. If NULL, derives from source filename. On Framework Cloud, use slug instead; dest still names the document there when slug isn't a string, for older scripts.

connection

Character or NULL. S3 connection name from config.yml. If NULL, uses the connection marked with default: true.

overwrite

Logical. Whether to overwrite existing files. Default TRUE.

self_contained

Logical. When publishing to Framework Cloud, whether to bundle an HTML file with its resources. Ignored for S3. Default TRUE.

slug

Framework Cloud only. A string names the document, for example slug = "main-results". It does not change visibility: a new artifact is unlisted and an existing one keeps its visibility. TRUE makes the artifact public under the name derived from dest or the file name, and FALSE makes it unlisted. NULL (the default) publishes under the derived name. Ignored, with a warning, for S3. With to = "github", a string names the folder under ⁠published/⁠.

include_private

Logical. Skip the private-path check. When the absolute path of any file to upload contains "private" in any case (apart from the ⁠/private/⁠ macOS adds to ⁠/tmp⁠ and ⁠/var⁠), Framework warns and, in an interactive session, asks before publishing (default No). In a non-interactive session it stops unless include_private = TRUE.

to

Named destination from publish.destinations, or a driver name. publish.default selects the default destination. "folder" needs a named destination with a path. "s3" and "bucket" retain legacy storage uploads. "cloud" selects Framework Cloud even when a bucket is configured. "bucket" selects storage. "github" publishes to the project's GitHub Pages site instead of a storage bucket or Framework Cloud: the document is bundled under ⁠published/<slug>/⁠. The artifact, version archives, and site index are committed and pushed. The site deploys from the default branch once "Publish with GitHub Pages" is on for the project in Framework Cloud, and it is public even when the repository is private, so an interactive session asks first. slug names the folder. Runs of characters outside lowercase letters and digits become -. The default is the file name lowercased, with other characters as - ("Final Report (v2).html" becomes final-report-v2). A folder needs an index.html at its top. dest, connection, and a TRUE/FALSE slug are errors here.

title

Artifact title. Default: a Quarto or R Markdown document's YAML title, else the file name.

description

Artifact description.

kind

Optional artifact kind override.

password

Password required to view the artifact on Framework Cloud.

visibility

Artifact visibility: "public", "unlisted", or "private". Set "public" for a readable URL. An explicit visibility wins over a TRUE or FALSE slug. Without one, a new artifact is unlisted. Unsupported access controls fail before delivery. Private folder and S3 destinations use visibility: private and destination access controls. private: true remains a compatibility alias. S3 requires API confirmation of a non-public bucket policy and Public Access Block settings.

collection

Existing project collection ID or slug. Follows the latest artifact version.

share_unlisted

Explicit consent to share an unlisted artifact with collection readers.

Details

With no connection and no storage bucket in settings.yml, a project set up from Framework Cloud publishes to its server instead (the FW_CLOUD_URL and FW_PROJECT_TOKEN in the project's .env). Each publish to Framework Cloud adds a new version of the document. Cloud provides owner-only access, public and unlisted links, and password protection. A new artifact is unlisted. Set visibility = "public" for a readable URL (⁠/@handle/project/slug⁠).

Value

Character. Published URLs, or the local path for a folder without a URL.

Examples


if (FALSE) {
# Upload a single file
publish("outputs/report.html")
# -> https://bucket.s3.region.amazonaws.com/prefix/report.html

# Upload with custom destination
publish("outputs/report.html", dest = "reports/q4-2024.html")

# Upload a directory
publish("outputs/charts/", dest = "reports/charts/")

# Use specific connection
publish("data.csv", connection = "s3_backup")

# Framework Cloud: a new version with a readable URL
publish("outputs/report.html", slug = "main-results", visibility = "public")

# GitHub Pages: commits published/main-results/ and pushes it
publish("outputs/report.html", to = "github", slug = "main-results")
}


Publish data to S3 or a named destination

Description

Uploads a data frame or existing data file. Like publish(), it follows to, then publish.default in settings.yml. S3 destinations, an explicit connection, and projects without publish.default get a plain upload to the storage bucket at dest. Folder, GitHub, and Cloud destinations publish the file with publish(). The slug is dest without its extension, with each / turned into -: "tables/demo.csv" publishes as tables-demo. The message says which slug was used.

Usage

publish_data(
  data,
  dest,
  format = "csv",
  connection = NULL,
  compress = FALSE,
  include_private = FALSE,
  to = NULL
)

Arguments

data

Data frame or character path to existing file.

dest

Character. Destination path in S3 (required for data frames). For other destinations, its file name names the file, and the path without its extension, with / turned into -, is the slug.

format

Character. Output format when data is a data frame: "csv", "rds", "parquet", or "json". Default "csv".

connection

Character or NULL. S3 connection name, or NULL for default.

compress

Logical. Whether to gzip compress. Default FALSE.

include_private

Logical. Skip the private-path check. When the absolute path of any file to upload contains "private" in any case (apart from the ⁠/private/⁠ macOS adds to ⁠/tmp⁠ and ⁠/var⁠), Framework warns and, in an interactive session, asks before publishing (default No). In a non-interactive session it stops unless include_private = TRUE.

to

Character or NULL. Named destination from publish.destinations, or a driver name, as in publish(). Default: publish.default.

Value

Character. Public URL of the published data (for a folder destination without a url, its location).

Examples


if (FALSE) {
# Publish a data frame
publish_data(my_df, "datasets/customers.csv")

# Publish as RDS
publish_data(my_df, "datasets/customers.rds", format = "rds")

# Publish existing file
publish_data("outputs/model.rds", "models/v2/model.rds")
}


Publish a directory to S3 or a named destination

Description

Recursively uploads all files in a directory to S3. Like publish(), it follows to, then publish.default in settings.yml. S3 destinations, an explicit connection, and projects without publish.default get a file-by-file upload under dest. Folder, GitHub, and Cloud destinations publish the directory (after pattern and recursive) with publish(), using the last part of dest (or the directory name) as the slug.

Usage

publish_dir(
  dir,
  dest = NULL,
  connection = NULL,
  pattern = NULL,
  recursive = TRUE,
  include_private = FALSE,
  to = NULL
)

Arguments

dir

Character. Local directory path.

dest

Character or NULL. Destination prefix in S3. If NULL, uses the directory name.

connection

Character or NULL. S3 connection name, or NULL for default.

pattern

Character or NULL. Optional regex pattern to filter files.

recursive

Logical. Whether to include subdirectories. Default TRUE.

include_private

Logical. Skip the private-path check. When the absolute path of any file to upload contains "private" in any case (apart from the ⁠/private/⁠ macOS adds to ⁠/tmp⁠ and ⁠/var⁠), Framework warns and, in an interactive session, asks before publishing (default No). In a non-interactive session it stops unless include_private = TRUE.

to

Character or NULL. Named destination from publish.destinations, or a driver name, as in publish(). Default: publish.default.

Value

Character vector. Public URLs of uploaded files (for other destinations, the published artifact's URL or location).

Examples


if (FALSE) {
# Upload entire directory
publish_dir("outputs/dashboard/")

# Upload to specific location
publish_dir("outputs/dashboard/", dest = "dashboards/v2/")

# Upload only HTML files
publish_dir("outputs/", pattern = "\\.html$")
}


List published files in S3 or a folder destination

Description

Lists files in an S3 bucket/prefix. Like publish(), it follows to, then publish.default in settings.yml. For a folder destination it lists the published artifacts, one row per slug. GitHub and Cloud destinations can't be listed here.

Usage

publish_list(prefix = NULL, connection = NULL, max = 1000L, to = NULL)

Arguments

prefix

Character or NULL. Prefix to filter by. If NULL, lists all files under the connection's configured prefix.

connection

Character or NULL. S3 connection name, or NULL for default.

max

Integer. Maximum number of files to list. Default 1000.

to

Character or NULL. Named destination from publish.destinations, or a driver name, as in publish(). Default: publish.default.

Value

Data frame with columns: key, size, last_modified, url.

Examples


if (FALSE) {
# List all published files
publish_list()

# List files under a prefix
publish_list("reports/")

# List from specific connection
publish_list(connection = "s3_backup")
}


Publish a Quarto notebook to S3 or Framework Cloud

Description

Renders a Quarto document and uploads it to S3. The notebook is rendered to a temporary directory, uploaded, then cleaned up.

Usage

publish_notebook(
  file,
  dest = NULL,
  connection = NULL,
  self_contained = TRUE,
  format = "html",
  slug = NULL,
  include_private = FALSE,
  to = NULL,
  collection = NULL,
  share_unlisted = FALSE,
  title = NULL,
  description = NULL,
  ...
)

Arguments

file

Character. Path to .qmd file.

dest

Character or NULL. Destination path in S3 (without extension). If NULL, derives from filename (e.g., "analysis.qmd" -> "analysis"). On Framework Cloud, use slug instead.

connection

Character or NULL. S3 connection name, or NULL for default.

self_contained

Logical. Whether to embed all resources. Default TRUE. Ignored if static_hosting: false (always renders self-contained).

format

Character. Output format. Default "html".

slug

Framework Cloud only: name the document. It does not make the document public. See publish(). With to = "github", names the folder under ⁠published/⁠.

include_private

Logical. Skip the private-path check. When the absolute path of any file to upload contains "private" in any case (apart from the ⁠/private/⁠ macOS adds to ⁠/tmp⁠ and ⁠/var⁠), Framework warns and, in an interactive session, asks before publishing (default No). In a non-interactive session it stops unless include_private = TRUE.

to

Character or NULL. "cloud" selects Framework Cloud and "bucket" selects storage. "github" publishes the rendered HTML to the project's GitHub Pages site. See publish().

collection

Existing project collection ID or slug. Follows the latest artifact version.

share_unlisted

Explicit consent to share an unlisted artifact with collection readers.

title

Character or NULL. The published title. Default: the document's YAML title, else its file name.

description

Character or NULL. A short description of the published document.

...

Additional arguments passed to quarto render.

Details

Publishing follows publish(): a named connection or a configured storage bucket comes first, then Framework Cloud when the project was set up from it. Framework Cloud takes HTML output only, adds a new version on each publish, and uses slug as publish() does.

The URL format depends on the S3 connection's static_hosting setting:

Value

Character. Public URL of the published notebook.

Examples


if (FALSE) {
# With static_hosting: true -> returns /analysis/
# With static_hosting: false -> returns /analysis.html
publish_notebook("notebooks/analysis.qmd")

# Publish to specific location
publish_notebook("notebooks/analysis.qmd", dest = "reports/2024/q4")

# Publish non-self-contained (only with static_hosting: true)
publish_notebook("notebooks/analysis.qmd", self_contained = FALSE)
}


Generate Quarto Configurations for Project

Description

Main entry point for a project's Quarto configuration. Writes one root ⁠_quarto.yml⁠ with the shared settings and an output folder that keeps each render folder's path (notebooks/ renders to outputs/notebooks/). A folder that needs its own format, such as a course's slides/, gets a ⁠_metadata.yml⁠, which inherits from the root. A render target outside the shared output folder keeps its own ⁠_quarto.yml⁠.

Usage

quarto_generate_all(
  project_path,
  project_type,
  render_dirs = NULL,
  quarto_settings = NULL,
  directories = NULL,
  root_output_dir = NULL
)

Arguments

project_path

Character. Path to project root

project_type

Character. One of "project", "project_sensitive", "course", "presentation"

render_dirs

Named list. Render directories with their paths

quarto_settings

List. Quarto settings (html and revealjs configs)

directories

Named list. Source directories keyed the same as render_dirs

root_output_dir

Ignored. Kept so older calls still work. The root output folder is the one most render_dirs share, as in the Python package. Setting it from quarto.render_dir would nest renders, such as outputs/notebooks/notebooks/x.html.

Value

List with success status and paths of generated files


Regenerate Quarto Configurations

Description

Regenerates all ⁠_quarto.yml⁠ files in a project. WARNING: This will overwrite any manual edits. Should only be called when user explicitly requests regeneration.

Usage

quarto_regenerate(project_path, backup = TRUE)

Arguments

project_path

Character. Path to project root

backup

Logical. If TRUE, backs up existing files before overwriting. Default TRUE.

Value

List with success status, backed up files, and regenerated files


Read the contents of a Framework template

Description

Templates are your versions of Framework's starter files, kept in the ⁠templates/⁠ folder of your Framework settings. Three are used: "notebook" by make_notebook() and make_qmd() with the default stub, "script" by make_script(), and "presentation" by make_revealjs(). A project's own ⁠stubs/⁠ folder still comes first. The gitignore and AI templates are kept for older settings and are not used by project creation.

Usage

read_framework_template(name)

Arguments

name

Template identifier (e.g., "notebook", "gitignore", "ai_claude")

Value

Character scalar containing template contents


Read global Framework configuration

Description

Read global Framework configuration

Usage

read_frameworkrc(use_defaults = TRUE)

Arguments

use_defaults

Whether to merge with default structure (default: TRUE)

Value

List containing global configuration


Remove project from global configuration

Description

Remove project from global configuration

Usage

remove_project_from_config(project_id)

Arguments

project_id

Project ID to remove

Value

Invisibly returns NULL


Disable renv for this project

Description

Deactivates renv integration while preserving renv.lock for future use. Removes the .framework_renv_enabled marker file.

Usage

renv_disable(keep_renv = TRUE)

Arguments

keep_renv

Logical; if TRUE (default), keep renv.lock and renv/ directory

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
renv_disable()
}


Enable renv for this project

Description

Initializes renv integration for the current Framework project. This:

Usage

renv_enable(sync = TRUE)

Arguments

sync

Logical; if TRUE (default), sync packages from settings.yml

Details

If a step fails, Framework undoes the steps before it: the marker file, the files renv created, and the .gitignore and .renvignore changes. The project is then as it was before the call. A package from settings.yml that fails to install gives a warning and is left out of renv.lock.

Value

Invisibly returns TRUE on success

Examples


if (FALSE) {
renv_enable()
}


Check if renv is enabled for this project

Description

Determines whether renv integration is active by checking for the .framework_renv_enabled marker file in the project root.

Usage

renv_enabled()

Value

Logical indicating whether renv is enabled

Examples

if (renv_enabled()) {
  message("Using renv for package management")
}

Restore packages from renv.lock

Description

Internal wrapper around renv::restore(). Use packages_restore() instead.

Usage

renv_restore(prompt = FALSE)

Arguments

prompt

Logical; if TRUE, prompt before restoring

Value

Invisibly returns TRUE on success


Snapshot current package versions to renv.lock

Description

Internal wrapper around renv::snapshot(). Use packages_snapshot() instead.

Usage

renv_snapshot(prompt = FALSE)

Arguments

prompt

Logical; if TRUE, prompt before creating snapshot

Value

Invisibly returns TRUE on success


Show package status

Description

Internal wrapper around renv::status(). Use packages_status() instead.

Usage

renv_status()

Value

Invisibly returns the status object from renv::status()


Sync packages with renv.lock

Description

Internal function that resolves inconsistencies between installed packages and renv.lock by restoring then snapshotting.

Usage

renv_sync(prompt = FALSE)

Arguments

prompt

Logical; if TRUE, prompt before making changes

Value

Invisibly returns TRUE on success


Update packages

Description

Internal wrapper around renv::update(). Use packages_update() instead.

Usage

renv_update(packages = NULL)

Arguments

packages

Character vector of package names to update, or NULL for all

Value

Invisibly returns TRUE on success


Reset a Framework template back to the packaged default

Description

Reset a Framework template back to the packaged default

Usage

reset_framework_template(name)

Arguments

name

Template identifier (e.g., "notebook", "gitignore", "ai_claude")

Value

Invisibly returns the file path of the reset template.


List saved results from the framework database

Description

Retrieves a list of all saved results (tables, figures, models, reports, notebooks) that have been tracked via the save_* functions.

Usage

result_list(type = NULL, public = NULL)

Arguments

type

Optional filter by type: "table", "figure", "model", "report", "notebook"

public

Optional filter: TRUE for public results only, FALSE for private only

Value

A data frame with columns: name, type, public, comment, hash, created_at, updated_at. Returns an empty data frame if no results found or database unavailable.

Examples


if (FALSE) {
# List all results
result_list()

# List only tables
result_list(type = "table")

# List only public figures
result_list(type = "figure", public = TRUE)
}



Save a figure to the outputs directory

Description

Saves a ggplot2 plot or base R graphics to the configured figures directory. The directory is created lazily on first use.

Usage

save_figure(
  plot = NULL,
  name,
  format = "png",
  width = 8,
  height = 6,
  dpi = 300,
  public = FALSE,
  overwrite = TRUE,
  ...
)

Arguments

plot

A ggplot2 object, a recorded plot from grDevices::recordPlot(), or NULL to save the current plot

name

The name for the output file (without extension)

format

Output format: "png" (default), "pdf", "svg", or "jpg"

width

Width in inches (default: 8)

height

Height in inches (default: 6)

dpi

Resolution in dots per inch (default: 300)

public

If TRUE, saves to public outputs directory (for project_sensitive type)

overwrite

If TRUE, overwrites existing files (default: TRUE)

...

Additional arguments passed to ggsave or the graphics device

Details

With plot = NULL, Framework saves the plot on the active graphics device, base graphics or ggplot2. Some devices keep no record of what they drew, such as the Rplots.pdf device in Rscript. There, a ggplot drawn last is saved with ggplot2::last_plot(), and a base plot drawn last is an error. Call dev.control("enable") before plotting, or pass recordPlot().

Value

The path to the saved file (invisibly)

Examples


if (FALSE) {
# Save a ggplot
p <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
save_figure(p, "mpg_vs_hp")

# Save as PDF for publication
save_figure(p, "mpg_vs_hp", format = "pdf", width = 10, height = 8)

# Save to public directory
save_figure(p, "summary_plot", public = TRUE)

# Save a base R plot
plot(mtcars$mpg, mtcars$hp)
save_figure(name = "mpg_vs_hp_base")
}



Save a model to the outputs directory

Description

Saves a fitted model object to the configured models directory. The directory is created lazily on first use.

Usage

save_model(model, name, public = FALSE, overwrite = TRUE, ...)

Arguments

model

A fitted model object (lm, glm, tidymodels workflow, etc.)

name

The name for the output file (without extension)

public

If TRUE, saves to public outputs directory (for project_sensitive type)

overwrite

If TRUE, overwrites existing files (default: TRUE)

...

Additional arguments passed to saveRDS()

Value

The path to the saved file (invisibly)

Examples


if (FALSE) {
# Fit and save a model
model <- lm(mpg ~ hp + wt, data = mtcars)
save_model(model, "mpg_regression")
}



Save a rendered notebook to the outputs directory

Description

Renders a Quarto, R Markdown, or Jupyter notebook and saves the output to the configured notebooks output directory. The directory is created lazily on first use.

Usage

save_notebook(
  file,
  name = NULL,
  format = "html",
  public = FALSE,
  overwrite = TRUE,
  embed_resources = TRUE,
  ...
)

Arguments

file

Path to the .qmd, .Rmd, or .ipynb file to render

name

Optional new name for the output file (without extension). If NULL, uses the original notebook name.

format

Output format: "html" (default), "pdf", or "docx"

public

If TRUE, saves to public outputs directory (for project_sensitive type)

overwrite

If TRUE, overwrites existing files (default: TRUE)

embed_resources

If TRUE, creates a self-contained file with embedded resources (default: TRUE for html format)

...

Additional arguments passed to quarto render

Details

Quarto renders a Jupyter notebook (.ipynb) from the outputs saved in it, without running its cells, so run the notebook before saving it.

Value

The path to the saved file (invisibly)

Examples


if (FALSE) {
# Render and save a notebook
save_notebook("notebooks/analysis.qmd")

# Save with a custom name
save_notebook("notebooks/analysis.qmd", name = "final_analysis")

# A Jupyter notebook, rendered from its saved outputs
save_notebook("notebooks/analysis.ipynb")

# Render to PDF
save_notebook("notebooks/analysis.qmd", format = "pdf")

# Save to public directory (for sensitive projects)
save_notebook("notebooks/analysis.qmd", public = TRUE)
}



Save a report to the outputs directory

Description

Copies or moves a rendered report (HTML, PDF, etc.) to the configured reports directory. The directory is created lazily on first use.

Usage

save_report(file, name = NULL, public = FALSE, overwrite = TRUE, move = FALSE)

Arguments

file

Path to the report file to save

name

Optional new name for the file (without extension). If NULL, uses original name.

public

If TRUE, saves to public outputs directory (for project_sensitive type)

overwrite

If TRUE, overwrites existing files (default: TRUE)

move

If TRUE, moves the file instead of copying (default: FALSE)

Value

The path to the saved file (invisibly)

Examples


if (FALSE) {
# Save a rendered HTML report
save_report("notebooks/analysis.html", "final_analysis")

# Save to public directory
save_report("notebooks/summary.pdf", "public_summary", public = TRUE)
}



Save a table to the outputs directory

Description

Saves a data frame or tibble to the configured tables directory. The directory is created lazily on first use.

Usage

save_table(data, name, format = "csv", public = FALSE, overwrite = TRUE, ...)

Arguments

data

A data frame, tibble, or other tabular data

name

The name for the output file (without extension)

format

Output format: "csv" (default), "rds", "xlsx", or "parquet"

public

If TRUE, saves to public outputs directory (for project_sensitive type)

overwrite

If TRUE, overwrites existing files (default: TRUE)

...

Additional arguments passed to the underlying write function

Value

The path to the saved file (invisibly)

Examples


if (FALSE) {
# Save a simple table
save_table(my_results, "regression_results")

# Save as Excel
save_table(my_results, "regression_results", format = "xlsx")

# Save to public directory (for sensitive projects)
save_table(summary_stats, "summary", public = TRUE)
}



Initialize and load the project environment

Description

The primary entry point for working with Framework projects. Call this at the start of every notebook or script to set up your environment with all configured packages, functions, and settings.

Usage

scaffold(config_file = NULL)

Arguments

config_file

Path to configuration file. If NULL (default), automatically discovers settings.yml or config.yml in the project.

Details

scaffold() performs the following steps in order:

  1. Standardizes working directory - Finds and sets the project root, even when called from notebooks in subdirectories

  2. Loads environment variables - Reads secrets from .env file

  3. Loads configuration - Parses settings.yml for project settings

  4. Sets random seed - For reproducibility (if seed is configured)

  5. Installs packages - Any missing packages from the packages list

  6. Loads packages - Attaches all configured packages

  7. Sources functions - Loads all .R files from ⁠functions/⁠ directory

  8. Sources scaffold.R - Runs the project's scaffold.R, if there is one

  9. Makes the first git commit - In a git repository with no commits yet, stages every file .gitignore allows and commits it as "Project initialized." This covers projects whose creation skipped that commit, for example when git had no user name or email. Repositories with commits are left alone.

After scaffold() completes, you have access to:

Value

Invisibly returns NULL. The main effects are side effects: loading packages and sourcing functions. No config object is created; read settings with settings() or settings_read().

Project Discovery

When called without arguments, scaffold() searches for a Framework project by:

This means you can call scaffold() from any subdirectory within your project.

Configuration

The settings.yml file controls what scaffold() loads. Key settings include:

See Also

Examples


if (FALSE) {
# At the top of every notebook or script:
library(framework)
scaffold()

# Now you can use your configured packages and functions
# Access settings via the settings() helper:
settings("directories.notebooks")
settings("seed")
}



Capture and Save Data to File

Description

Saves data to a file in various formats based on the object type and specified format. If no name is provided, uses the name of the object passed in. If no location is provided, uses the scratch directory from the configuration.

Usage

scratch_capture(x, name = NULL, to = NULL, location = NULL, n = Inf)

Arguments

x

The object to save

name

Optional character string specifying the name of the file (without extension). If not provided, will use the name of the object passed in.

to

Optional character string indicating the output format. One of: "text", "rds", "csv", "tsv". If not provided, will choose based on object type.

location

Optional character string specifying the directory where the file should be saved. If NULL, uses the scratch directory from the configuration.

n

Optional number of rows to capture for data frames (default: all rows)

Value

The input object x invisibly.

Examples


if (FALSE) {
# Save a character vector as text
scratch_capture(c("hello", "world"))

# Save a data frame as TSV
scratch_capture(mtcars)

# Save an R object as RDS
scratch_capture(list(a = 1, b = 2), to = "rds")
}



Clean up the scratch directory

Description

Deletes the files at the top of the scratch directory, dotfiles included. Subfolders and their contents stay.

Usage

scratch_clean()

Value

Invisibly returns NULL. Called for side effect of removing scratch files.


Get settings value by dot-notation key

Description

Framework's primary configuration helper that supports both flat and hierarchical key access using dot notation. Automatically checks common locations for directory settings. Pretty-prints nested structures in interactive sessions.

Usage

settings(key = NULL, default = NULL, settings_file = NULL)

Arguments

key

Character. Dot-notation key path (e.g., "notebooks" or "directories.notebooks" or "connections.db.host"). If NULL, returns entire settings.

default

Optional default value if key is not found (default: NULL)

settings_file

Settings file path (default: checks "settings.yml" then "settings.yml")

Details

For directory settings, the function checks multiple locations:

File Discovery:

Output Behavior:

Value

The settings value, or default if not found. In interactive sessions, nested structures are pretty-printed and returned invisibly.

Examples


if (FALSE) {
# Get notebook directory (checks both locations)
settings("notebooks")

# Get explicit nested setting
settings("directories.notebooks")
settings("connections.db.host")

# Get entire section
settings("directories")  # Returns all directory settings
settings("connections")  # Returns all connection settings

# View entire settings
settings()  # Returns full configuration

# With default value
settings("missing_key", default = "fallback")
}



Read project settings

Description

Reads the project settings from settings.yml or config.yml with environment-aware merging and split file resolution. Auto-discovers the settings file if not specified.

Usage

settings_read(settings_file = NULL, environment = NULL)

Arguments

settings_file

Path to settings file (default: auto-discover settings.yml or config.yml)

environment

Active environment name (default: R_CONFIG_ACTIVE or "default")

Value

The settings as a list


Write project settings

Description

Writes the project settings to settings.yml or config files

Usage

settings_write(settings, settings_file = NULL, section = NULL)

Arguments

settings

The settings list to write

settings_file

The settings file path (default: auto-detect settings.yml/config.yml)

section

Optional section to update (e.g. "data")

Value

Invisibly returns NULL.


Set up a Framework Cloud project, or Framework's global settings

Description

Usage

setup(token = NULL, browse = TRUE, location = NULL, url = NULL)

Arguments

token

A project token from Framework Cloud. NULL (default) sets up the global settings only.

browse

Open the new project's folder (default: TRUE)

location

Where to create the project (prompted interactively when NULL)

url

The Framework Cloud server that issued the token. Defaults to FW_CLOUD_URL, then the server you last logged in to with cloud_login(), then https://framework.pub.

Value

With a token, invisibly, the project_create() result. Without one, invisibly NULL.

See Also

new(), cloud_login()

Examples


if (FALSE) {
# Set up a cloud-defined project by its token
framework::setup("1|fw_abc123...")

# From a self-hosted server
framework::setup("1|fw_abc123...", url = "https://framework.example.edu")
}



Synchronize a Skill Directory

Description

Synchronize a versioned skill bundle with Framework Cloud. Divergent changes return a conflict without replacing files. Companion files and executable modes are included. Untracked skills become private account skills.

Usage

skills_sync(
  path,
  project_path = ".",
  direction = "auto",
  dry_run = FALSE,
  skill_id = NULL,
  variant = "r",
  resolve = NULL
)

Arguments

path

Project-relative skill directory.

project_path

Project root directory.

direction

One of auto, push, pull, or status.

dry_run

Report the action without writing files or Cloud versions.

skill_id

Explicit Cloud skill identity for adoption or an initial pull.

variant

Language variant: r, python, or stata.

resolve

Optional conflict choice: local or remote. Replaced files are backed up.

Value

A list with the action, skill identity, hashes, and version.


Check a Resolved Project Spec

Description

Checks a resolved spec for the problems project_create() cannot recover from: missing sections, unknown values, and paths that would write outside the project. The JSON Schema in inst/schema/spec.v1.json describes the same shape for other tools.

Usage

spec_check(spec)

Arguments

spec

A resolved spec, as returned by spec_resolve().

Value

A character vector of problems, empty when the spec is valid.

See Also

spec_resolve()


Resolve a Project Spec from Layers

Description

Merges spec layers into one complete project spec, the input to project_create(). This is the only implementation of the merge: the framework.pub cloud and the fw CLI send unmerged layers, and R resolves them.

Usage

spec_resolve(layers = list(), name, author = NULL, check = TRUE)

Arguments

layers

A list of layers, bottom to top. Each element is either a layer (a named list in spec shape) or a list with kind, key, version, and layer, as in .framework/layers.json.

name

Project name. Overrides any name in the layers.

author

Optional author list (name, email, affiliation, and optionally orcid, url, and affiliations). Non-empty fields override the layers' author; affiliations replaces the whole list.

check

If TRUE (default), stop when the resolved spec is invalid.

Details

The package defaults for the project type are always the bottom layer. The given layers are applied on top, in order. The project type is taken from the last layer that sets type (default "project").

Merge rules:

Value

The resolved spec as a named list. Attribute "conflicts" holds a data frame of keys set by more than one layer (path, layers).

See Also

project_create()

Examples

spec <- spec_resolve(
  list(list(security = list(sensitive = TRUE))),
  name = "My study"
)
spec$security$sensitive


Standardize Working Directory for Framework Projects

Description

This function helps standardize the working directory when working with framework projects, especially useful in Quarto/RMarkdown documents that may be rendered from subdirectories.

Usage

standardize_wd(project_root = NULL)

Arguments

project_root

Character string specifying the project root directory. If NULL (default), the function will attempt to find it automatically.

Details

The function looks for common framework project indicators:

It sets both the regular working directory and knitr's root.dir option if knitr is available.

Value

Invisibly returns the standardized project root path.

Examples


if (FALSE) {
library(framework)
standardize_wd()
scaffold()
}



Show Framework project status

Description

Displays comprehensive information about the current Framework project including:

Usage

status()

Value

No return value, called for side effect of printing project status.

Examples


if (FALSE) {
status()
}


Test storage connection

Description

Validates that S3/storage credentials and bucket access are working.

Usage

storage_test(connection = NULL)

Arguments

connection

Character or NULL. Connection name, or NULL for default.

Value

Logical. TRUE if connection is valid.

Examples


if (FALSE) {
# Test default storage connection
storage_test()

# Test specific connection
storage_test("my_s3_backup")
}


Save a Folder's Layout as a Structure on Framework Cloud

Description

Maps a folder's layout the same way as adopt() and saves it as a structure on Framework Cloud, private to you, so new projects can use it. Only the folder paths and the roles you confirm are sent; file names and contents never are. Changes nothing in the folder.

Usage

structure_import(path = ".", name = NULL, yes = FALSE)

Arguments

path

The folder whose layout to import (default: the working directory).

name

The structure's name. Default: the folder's name.

yes

If TRUE, accept the proposed mapping without asking.

Value

Invisibly, the cloud's response: key, name, and url.

Examples


if (FALSE) {
structure_import("~/projects/old-study", name = "Lab layout")
}



List Available Stubs

Description

Shows all available stub templates that can be used with make_notebook().

Usage

stubs_list(type = NULL)

Arguments

type

Character. Filter by type: "quarto", "rmarkdown", "script", or NULL (all).

Value

Data frame with columns: name, type, source (user for the project's ⁠stubs/⁠, personal for your templates, or framework), in the order make_notebook() searches. The first source hides later ones.

Examples


if (FALSE) {
# List all stubs
stubs_list()

# List only Quarto stubs
stubs_list("quarto")

# List only script stubs
stubs_list("script")
}



Get Path to Stub Templates Directory

Description

Returns the path to the user's stubs directory, or the framework stubs directory if no user stubs exist.

Usage

stubs_path(which = "auto")

Arguments

which

Character. Which directory to return:

  • "user" - User's project stubs directory (stubs/)

  • "framework" - Framework's built-in stubs directory

  • "auto" (default) - User directory if it exists, otherwise framework

Value

Character path to stubs directory

Examples


if (FALSE) {
# Get active stubs directory
stubs_path()

# Get framework stubs directory
stubs_path("framework")

# Get user stubs directory
stubs_path("user")
}



Publish Stub Templates for Customization

Description

Copies framework stub templates to your project's ⁠stubs/⁠ directory, allowing you to customize them. Similar to Laravel's ⁠artisan vendor:publish⁠ command.

Usage

stubs_publish(type = "all", overwrite = FALSE, stubs = NULL)

Arguments

type

Character vector. Which stub types to publish:

  • "notebooks" - Quarto/RMarkdown notebook stubs

  • "scripts" - R script stubs

  • "all" - All stubs (default)

overwrite

Logical. Whether to overwrite existing stubs. Default FALSE.

stubs

Character vector. Specific stub names to publish (e.g., "default", "minimal"). If NULL (default), publishes all stubs of the specified type.

Details

Stub Customization Workflow

  1. Publish stubs to your project: stubs_publish()

  2. Edit stubs in ⁠stubs/⁠ directory to match your preferences

  3. Use make_notebook() or make_script() - your custom stubs are used automatically

Stub Naming Convention

Stubs follow this naming pattern:

Framework searches user stubs first, then falls back to built-in stubs.

Available Placeholders

Stubs can use these placeholders:

Value

Invisible list of published file paths

See Also

make_notebook(), make_script(), stubs_list(), stubs_path()

Examples


if (FALSE) {
# Publish all stubs
stubs_publish()

# Publish only notebook stubs
stubs_publish("notebooks")

# Publish specific stub
stubs_publish(stubs = "default")

# Overwrite existing stubs
stubs_publish(overwrite = TRUE)
}



View data in an interactive browser viewer

Description

Opens an interactive, browser-based viewer for R objects. This is the primary function for viewing data frames, plots, lists, and other R objects with enhanced formatting.

Usage

view(x, title = NULL, max_rows = 5000)

Arguments

x

The data to view (data.frame, plot, list, function, or other R object)

title

Optional title for the view. If NULL, uses the object name.

max_rows

Maximum number of rows to display for data frames (default: 5000).

Value

Invisibly returns NULL. Opens a browser window.

Examples


if (FALSE) {
# View a data frame
view(mtcars)

# View with a title
view(iris, title = "Iris Dataset")

# View a ggplot
library(ggplot2)
p <- ggplot(mtcars, aes(mpg, hp)) + geom_point()
view(p)
}



Create an enhanced view of R objects in the browser

Description

Opens an interactive, browser-based viewer for R objects with syntax highlighting, tabbed interfaces, and enhanced data table support. Handles data frames, plots, lists, functions, and more with appropriate rendering for each type.

Usage

view_create(x, title = NULL, max_rows = 5000)

Arguments

x

The data to view (data.frame, plot, list, function, or other R object)

title

Optional title for the view. If NULL, uses the object name.

max_rows

Maximum number of rows to display for data frames (default: 5000). Large data frames are automatically truncated with a warning.

Value

Invisibly returns NULL. Function is called for its side effect of opening a browser window with the rendered view.


View data with enhanced browser-based interface

Description

Opens an interactive, browser-based viewer for R objects with search, filtering, sorting, pagination, and export capabilities (CSV/Excel). Provides a rich DataTables interface for data frames and enhanced views for plots, lists, and other R objects. This is the recommended function for exploring data in detail.

Usage

view_detail(x, title = NULL, max_rows = 5000)

Arguments

x

The data to view (data.frame, plot, list, function, or other R object)

title

Optional title for the view. If NULL, uses the object name.

max_rows

Maximum number of rows to display for data frames (default: 5000). Large data frames are automatically truncated with a warning.

Details

Unlike R's built-in View(), this function:

Value

Invisibly returns NULL. Function is called for its side effect of opening a browser window with the rendered view.

See Also

view


Overwrite a Framework template with new contents

Description

See read_framework_template() for which templates are used.

Usage

write_framework_template(name, contents)

Arguments

name

Template identifier (e.g., "notebook", "gitignore", "ai_claude")

contents

Character string to write to the template file.

Value

Invisibly returns the file path of the written template.


Write global Framework configuration

Description

Writes the global settings file. When config has a projects element, the project registry (projects.yml) is written too; otherwise it stays as it is.

Usage

write_frameworkrc(config)

Arguments

config

A named list, such as one from read_frameworkrc(). NULL or an empty list is an error, so a slip can't wipe the global settings.

Value

Invisibly returns NULL