Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/api/data_types/code_mappings.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//! Data types for the bulk code mappings API.

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkCodeMappingsRequest {
pub project: String,
pub repository: String,
pub default_branch: String,
pub mappings: Vec<BulkCodeMapping>,
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

m: Because of how we use this in #3210, I think this struct should probably use borrowed, instead of owned, types. This would avoid cloning in #3210

pub struct BulkCodeMappingsRequest<'a> {
    pub project: &'a str,
    pub repository: &'a str,
    pub default_branch: &'a str,
    pub mappings: &'a [BulkCodeMapping],
}


#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkCodeMapping {
pub stack_root: String,
pub source_root: String,
}

#[derive(Debug, Deserialize)]
pub struct BulkCodeMappingsResponse {
pub created: u64,
pub updated: u64,
pub errors: u64,
pub mappings: Vec<BulkCodeMappingResult>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BulkCodeMappingResult {
pub stack_root: String,
pub source_root: String,
pub status: String,
#[serde(default)]
pub detail: Option<String>,
}
2 changes: 2 additions & 0 deletions src/api/data_types/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
//! Data types used in the api module

mod chunking;
mod code_mappings;
mod deploy;
mod snapshots;

pub use self::chunking::*;
pub use self::code_mappings::*;
pub use self::deploy::*;
pub use self::snapshots::*;
11 changes: 11 additions & 0 deletions src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,17 @@ impl AuthenticatedApi<'_> {
Ok(rv)
}

/// Bulk uploads code mappings for an organization.
pub fn bulk_upload_code_mappings(
&self,
org: &str,
body: &BulkCodeMappingsRequest,
) -> ApiResult<BulkCodeMappingsResponse> {
let path = format!("/organizations/{}/code-mappings/bulk/", PathArg(org));
self.post(&path, body)?
.convert_rnf(ApiErrorKind::OrganizationNotFound)
}

/// Creates a preprod snapshot artifact for the given project.
pub fn create_preprod_snapshot<S: Serialize>(
&self,
Expand Down
45 changes: 45 additions & 0 deletions src/commands/code_mappings/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use anyhow::Result;
use clap::{ArgMatches, Command};

use crate::utils::args::ArgExt as _;

pub mod upload;

macro_rules! each_subcommand {
($mac:ident) => {
$mac!(upload);
};
}

pub fn make_command(mut command: Command) -> Command {
macro_rules! add_subcommand {
($name:ident) => {{
command = command.subcommand(crate::commands::code_mappings::$name::make_command(
Command::new(stringify!($name).replace('_', "-")),
));
}};
}

command = command
.about("Manage code mappings for Sentry. Code mappings link stack trace paths to source code paths in your repository, enabling source context and code linking in Sentry.")
.subcommand_required(true)
.arg_required_else_help(true)
.org_arg()
.project_arg(false);
each_subcommand!(add_subcommand);
command
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
macro_rules! execute_subcommand {
($name:ident) => {{
if let Some(sub_matches) =
matches.subcommand_matches(&stringify!($name).replace('_', "-"))
{
return crate::commands::code_mappings::$name::execute(&sub_matches);
}
}};
}
each_subcommand!(execute_subcommand);
unreachable!();
}
199 changes: 199 additions & 0 deletions src/commands/code_mappings/upload.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
use std::fs;

use anyhow::{bail, Context as _, Result};
use clap::{Arg, ArgMatches, Command};
use log::debug;

use crate::api::{Api, BulkCodeMapping, BulkCodeMappingResult, BulkCodeMappingsRequest};
use crate::config::Config;
use crate::utils::formatting::Table;
use crate::utils::vcs;

pub fn make_command(command: Command) -> Command {
command
.about("Upload code mappings for a project from a JSON file. Each mapping pairs a stack trace root (e.g. com/example/module) with the corresponding source path in your repository (e.g. modules/module/src/main/java/com/example/module).")
.arg(
Arg::new("path")
.value_name("PATH")
.required(true)
.help("Path to a JSON file containing code mappings."),
)
.arg(
Arg::new("repo")
.long("repo")
.value_name("REPO")
.help("The repository name (e.g. owner/repo). Defaults to the git remote."),
)
.arg(
Arg::new("default_branch")
.long("default-branch")
.value_name("BRANCH")
.help("The default branch name. Defaults to the git remote HEAD or 'main'."),
)
}

pub fn execute(matches: &ArgMatches) -> Result<()> {
let config = Config::current();
let org = config.get_org(matches)?;
let project = config.get_project(matches)?;

let path = matches
.get_one::<String>("path")
.expect("path is a required argument");
let data = fs::read(path).with_context(|| format!("Failed to read mappings file '{path}'"))?;

let mappings: Vec<BulkCodeMapping> =
serde_json::from_slice(&data).context("Failed to parse mappings JSON")?;

if mappings.is_empty() {
bail!("Mappings file contains an empty array. Nothing to upload.");
}

for (i, mapping) in mappings.iter().enumerate() {
if mapping.stack_root.is_empty() {
bail!("Mapping at index {i} has an empty stackRoot.");
}
if mapping.source_root.is_empty() {
bail!("Mapping at index {i} has an empty sourceRoot.");
}
}

// Resolve repo name and default branch
let explicit_repo = matches.get_one::<String>("repo");
let explicit_branch = matches.get_one::<String>("default_branch");

let (repo_name, default_branch) = match (explicit_repo, explicit_branch) {
(Some(r), Some(b)) => (r.to_owned(), b.to_owned()),
_ => {
let git_repo = git2::Repository::open_from_env();

// Resolve the best remote name when we have a git repo.
// Prefer explicit config (SENTRY_VCS_REMOTE / ini), then inspect
// the repo for the best remote (upstream > origin > first).
let remote_name = git_repo.as_ref().ok().and_then(|repo| {
let configured_remote = config.get_cached_vcs_remote();
if vcs::git_repo_remote_url(repo, &configured_remote).is_ok() {
debug!("Using configured VCS remote: {configured_remote}");
Some(configured_remote)
} else {
match vcs::find_best_remote(repo) {
Ok(Some(best)) => {
debug!(
"Configured remote '{configured_remote}' not found, using: {best}"
);
Some(best)
}
_ => None,
}
}
});

let repo_name = match explicit_repo {
Some(r) => r.to_owned(),
None => {
let git_repo = git_repo.as_ref().map_err(|e| {
anyhow::anyhow!(
"Could not open git repository: {e}. \
Use --repo to specify manually."
)
})?;
let remote_name = remote_name.as_deref().ok_or_else(|| {
anyhow::anyhow!(
"No remotes found in the git repository. \
Use --repo to specify manually."
)
})?;
let remote_url = vcs::git_repo_remote_url(git_repo, remote_name)?;
debug!("Found remote '{remote_name}': {remote_url}");
let inferred = vcs::get_repo_from_remote_preserve_case(&remote_url);
if inferred.is_empty() {
bail!("Could not parse repository name from remote URL: {remote_url}");
}
println!("Inferred repository: {inferred}");
inferred
}
};

let default_branch = match explicit_branch {
Some(b) => b.to_owned(),
None => {
let inferred = git_repo
.as_ref()
.ok()
.and_then(|repo| {
remote_name.as_deref().and_then(|name| {
vcs::git_repo_base_ref(repo, name)
.map(Some)
.unwrap_or_else(|e| {
debug!("Could not infer default branch from remote: {e}");
None
})
})
})
.unwrap_or_else(|| {
debug!("No git repo or remote available, falling back to 'main'");
"main".to_owned()
});
println!("Inferred default branch: {inferred}");
inferred
}
};

(repo_name, default_branch)
}
};

let mapping_count = mappings.len();
let request = BulkCodeMappingsRequest {
project,
repository: repo_name,
default_branch,
mappings,
};

println!("Uploading {mapping_count} code mapping(s)...");

let api = Api::current();
let response = api
.authenticated()?
.bulk_upload_code_mappings(&org, &request)?;

print_results_table(response.mappings);
println!(
"Created: {}, Updated: {}, Errors: {}",
response.created, response.updated, response.errors
);

if response.errors > 0 {
bail!(
"{} mapping(s) failed to upload. See errors above.",
response.errors
);
}

Ok(())
}

fn print_results_table(mappings: Vec<BulkCodeMappingResult>) {
let mut table = Table::new();
table
.title_row()
.add("Stack Root")
.add("Source Root")
.add("Status");

for result in mappings {
let status = match result.detail {
Some(detail) if result.status == "error" => format!("error: {detail}"),
_ => result.status,
};
table
.add_row()
.add(&result.stack_root)
.add(&result.source_root)
.add(&status);
}

table.print();
println!();
}
2 changes: 2 additions & 0 deletions src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use crate::utils::value_parsers::auth_token_parser;

mod bash_hook;
mod build;
mod code_mappings;
mod dart_symbol_map;
mod debug_files;
mod deploys;
Expand Down Expand Up @@ -52,6 +53,7 @@ macro_rules! each_subcommand {
($mac:ident) => {
$mac!(bash_hook);
$mac!(build);
$mac!(code_mappings);
$mac!(debug_files);
$mac!(deploys);
$mac!(events);
Expand Down
26 changes: 19 additions & 7 deletions src/utils/vcs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,27 +301,39 @@ pub fn git_repo_base_ref(repo: &git2::Repository, remote_name: &str) -> Result<S
})
}

/// Like git_repo_base_repo_name but preserves the original case of the repository name.
/// This is used specifically for build upload where case preservation is important.
pub fn git_repo_base_repo_name_preserve_case(repo: &git2::Repository) -> Result<Option<String>> {
/// Finds the best remote in a git repository.
/// Prefers "upstream" if it exists, then "origin", otherwise uses the first remote.
pub fn find_best_remote(repo: &git2::Repository) -> Result<Option<String>> {
let remotes = repo.remotes()?;
let remote_names: Vec<&str> = remotes.iter().flatten().collect();

if remote_names.is_empty() {
warn!("No remotes found in repository");
return Ok(None);
}

// Prefer "upstream" if it exists, then "origin", otherwise use the first one
let chosen_remote = if remote_names.contains(&"upstream") {
let chosen = if remote_names.contains(&"upstream") {
"upstream"
} else if remote_names.contains(&"origin") {
"origin"
} else {
remote_names[0]
};

match git_repo_remote_url(repo, chosen_remote) {
Ok(Some(chosen.to_owned()))
}

/// Like git_repo_base_repo_name but preserves the original case of the repository name.
/// This is used specifically for build upload where case preservation is important.
pub fn git_repo_base_repo_name_preserve_case(repo: &git2::Repository) -> Result<Option<String>> {
let chosen_remote = match find_best_remote(repo)? {
Some(remote) => remote,
None => {
warn!("No remotes found in repository");
return Ok(None);
}
};

match git_repo_remote_url(repo, &chosen_remote) {
Ok(remote_url) => {
debug!("Found remote '{chosen_remote}': {remote_url}");
let repo_name = get_repo_from_remote_preserve_case(&remote_url);
Expand Down
Loading
Loading