Skip to content

Commit

Permalink
Use a random number generator
Browse files Browse the repository at this point in the history
  • Loading branch information
zanieb committed Jan 3, 2024
1 parent 182bbbb commit 487959e
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/ruff_notebook/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ serde_json = { workspace = true }
serde_with = { workspace = true, default-features = false, features = ["macros"] }
thiserror = { workspace = true }
uuid = { workspace = true }
rand = { workspace = true }

[dev-dependencies]
insta = { workspace = true }
Expand Down
11 changes: 5 additions & 6 deletions crates/ruff_notebook/src/notebook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::{io, iter};

use itertools::Itertools;
use once_cell::sync::OnceCell;
use rand::Rng;
use serde::Serialize;
use serde_json::error::Category;
use thiserror::Error;
Expand Down Expand Up @@ -145,8 +146,10 @@ impl Notebook {
// Add cell ids to 4.5+ notebooks if they are missing
// https://github.com/astral-sh/ruff/issues/6834
// https://github.com/jupyter/enhancement-proposals/blob/master/62-cell-id/cell-id.md#required-field
// https://github.com/jupyter/enhancement-proposals/blob/master/62-cell-id/cell-id.md#questions
if raw_notebook.nbformat == 4 && raw_notebook.nbformat_minor >= 5 {
let mut id_index: u128 = 0;
// We use a mock random number generator to generate deterministic uuids
let mut rng = rand::rngs::mock::StepRng::new(0, 1);
let mut existing_ids = HashSet::new();

for cell in &raw_notebook.cells {
Expand All @@ -168,15 +171,11 @@ impl Notebook {
};
if id.is_none() {
loop {
// https://github.com/jupyter/enhancement-proposals/blob/master/62-cell-id/cell-id.md#questions
let new_id = uuid::Builder::from_u128(id_index)
let new_id = uuid::Builder::from_random_bytes(rng.gen())
.into_uuid()
.as_hyphenated()
.to_string();

// Increment the index
id_index += 1;

if !existing_ids.contains(&new_id) {
existing_ids.insert(new_id.clone());
*id = Some(new_id);
Expand Down

0 comments on commit 487959e

Please sign in to comment.