nb-fabric 0.5.0

CLI for managing Microsoft Fabric notebooks; create, edit cells, execute interactively, schedule, and query OneLake data
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
// #region Imports
mod auth;
mod client;
mod commands;
mod notebook;
pub mod spinner;

use anyhow::Result;
use clap::{Parser, Subcommand};
// #endregion

// #region Classes

#[derive(Parser)]
#[command(name = "nb", version, about = "Fabric notebook CLI [experimental; commands may change]")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Authentication commands
    Auth {
        #[command(subcommand)]
        action: AuthAction,
    },

    /// List notebooks in a workspace
    #[command(after_long_help = "\
Examples:
  nb list \"My Workspace\"
  nb list 5feab05a-68a8-43af-a621-2571b5fcd3fd")]
    List {
        /// Workspace name or GUID
        workspace: String,
    },

    /// Create a new notebook
    #[command(after_long_help = "\
Examples:
  nb create \"My Workspace/ETL Pipeline\" --kernel python --lakehouse MainLH
  nb create \"My Workspace/Spark Job\" --kernel pyspark --lakehouse MainLH
  nb create \"My Workspace/Analytics\" --kernel python --warehouse MyWarehouse")]
    Create {
        /// Workspace/notebook-name reference
        reference: String,

        /// Kernel type
        #[arg(long, default_value = "python")]
        kernel: String,

        /// Default lakehouse name
        #[arg(long)]
        lakehouse: Option<String>,

        /// Default warehouse name
        #[arg(long)]
        warehouse: Option<String>,
    },

    /// Batch job management (run, list history)
    Job {
        #[command(subcommand)]
        action: JobAction,
    },

    /// Open notebook in browser
    Open {
        /// Workspace/notebook reference
        reference: String,
    },

    /// Export notebook to local .ipynb file
    #[command(after_long_help = "\
Examples:
  nb export \"My Workspace/ETL Pipeline\" -o ./notebooks/etl.ipynb")]
    Export {
        /// Workspace/notebook reference
        reference: String,

        /// Output file path
        #[arg(short, long)]
        output: String,
    },

    /// List all cells in a notebook
    #[command(after_long_help = "\
Examples:
  nb cells \"My Workspace/ETL Pipeline\"")]
    Cells {
        /// Workspace/notebook reference
        reference: String,
    },

    /// View, add, edit, or remove a cell
    Cell {
        #[command(subcommand)]
        action: CellAction,
    },

    /// Execute code interactively and return output
    #[command(after_long_help = "\
Subcommands:
  nb exec code  Run code directly against a lakehouse (no notebook needed)
  nb exec cell  Execute a notebook cell via its attached lakehouse

Examples:
  nb exec code \"MyWorkspace/MyLH.Lakehouse\" \"print('hello')\"
  nb exec code \"MyWorkspace/MyLH.Lakehouse\" \"spark.sql('SHOW TABLES').show()\"
  nb exec cell \"My Workspace/Notebook\" 0 --lakehouse MainLH")]
    Exec {
        #[command(subcommand)]
        action: ExecAction,
    },

    /// Show active notebook sessions
    Session {
        /// Workspace/notebook reference
        reference: String,
    },

    /// Manage notebook schedules
    Schedule {
        #[command(subcommand)]
        action: ScheduleAction,
    },

    /// Delete a notebook
    #[command(after_long_help = "\
Examples:
  nb delete \"My Workspace/Old Notebook\" --force")]
    Delete {
        /// Workspace/notebook reference
        reference: String,

        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },
}

#[derive(Subcommand)]
enum ExecAction {
    /// Run code directly against a lakehouse (no notebook needed)
    #[command(after_long_help = "\
Creates an ephemeral session, runs the code, prints output, and cleans up.
The spark (SparkSession) variable is available for querying lakehouse tables.
Pass - as code to read from stdin.

Examples:
  nb exec code \"MyWorkspace/MyLH.Lakehouse\" \"print('hello')\"
  nb exec code \"MyWorkspace/MyLH.Lakehouse\" \"spark.sql('SHOW TABLES').show()\"
  echo \"print(42)\" | nb exec code \"MyWorkspace/MyLH.Lakehouse\" -")]
    Code {
        /// Workspace/lakehouse reference (e.g. \"MyWS/MyLH.Lakehouse\")
        reference: String,

        /// Code to execute (use - for stdin)
        code: String,
    },

    /// Execute a notebook cell via its attached lakehouse
    #[command(after_long_help = "\
Auto-detects kernel and lakehouse from notebook metadata.

Examples:
  nb exec cell \"My Workspace/Notebook\" 0
  nb exec cell \"My Workspace/Notebook\" 0 --lakehouse MainLH")]
    Cell {
        /// Workspace/notebook reference
        reference: String,

        /// Cell index to execute
        index: usize,

        /// Lakehouse name (auto-detected from notebook metadata if not specified)
        #[arg(long)]
        lakehouse: Option<String>,
    },
}

#[derive(Subcommand)]
enum AuthAction {
    /// Check authentication status
    Status,
}

#[derive(Subcommand)]
enum JobAction {
    /// Run a notebook as a batch job
    #[command(after_long_help = "\
Examples:
  nb job run \"My Workspace/ETL Pipeline\"
  nb job run \"My Workspace/ETL Pipeline\" --wait
  nb job run \"My Workspace/ETL Pipeline\" --wait --timeout 600")]
    Run {
        /// Workspace/notebook reference
        reference: String,

        /// Wait for completion
        #[arg(long)]
        wait: bool,

        /// Timeout in seconds (with --wait)
        #[arg(long, default_value = "3600")]
        timeout: u64,
    },

    /// List recent job runs
    #[command(after_long_help = "\
Examples:
  nb job list \"My Workspace/ETL Pipeline\"")]
    List {
        /// Workspace/notebook reference
        reference: String,
    },
}

#[derive(Subcommand)]
enum CellAction {
    /// View a single cell
    View {
        /// Workspace/notebook reference
        reference: String,
        /// Cell index
        index: usize,
    },

    /// Add a new cell
    Add {
        /// Workspace/notebook reference
        reference: String,

        /// Code or markdown content
        #[arg(long)]
        code: String,

        /// Create a markdown cell instead of code
        #[arg(long)]
        markdown: bool,

        /// Insert at position (default: append)
        #[arg(long)]
        at: Option<usize>,
    },

    /// Edit a cell's source
    Edit {
        /// Workspace/notebook reference
        reference: String,

        /// Cell index
        index: usize,

        /// New source code
        #[arg(long)]
        code: String,
    },

    /// Remove a cell
    Rm {
        /// Workspace/notebook reference
        reference: String,

        /// Cell index
        index: usize,
    },
}

#[derive(Subcommand)]
enum ScheduleAction {
    /// List schedules for a notebook
    List {
        /// Workspace/notebook reference
        reference: String,
    },

    /// Create a schedule
    Create {
        /// Workspace/notebook reference
        reference: String,

        /// Schedule type: Cron, Daily, Weekly
        #[arg(long, default_value = "Cron")]
        r#type: String,

        /// Interval (minutes for Cron, times per day for Daily)
        #[arg(long)]
        interval: u64,

        /// Start datetime (ISO 8601)
        #[arg(long)]
        start: String,

        /// End datetime (ISO 8601)
        #[arg(long)]
        end: Option<String>,

        /// Timezone
        #[arg(long, default_value = "UTC")]
        timezone: String,

        /// Enable immediately
        #[arg(long)]
        enable: bool,
    },

    /// Update an existing schedule
    Update {
        /// Workspace/notebook reference
        reference: String,

        /// Schedule ID to update
        id: String,

        /// Enable or disable
        #[arg(long)]
        enable: Option<bool>,

        /// New interval
        #[arg(long)]
        interval: Option<u64>,

        /// New schedule type
        #[arg(long)]
        r#type: Option<String>,
    },

    /// Delete a schedule
    Delete {
        /// Workspace/notebook reference
        reference: String,

        /// Schedule ID to delete
        id: String,
    },
}

// #endregion

// #region Functions

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();
    let http = client::build_client()?;

    match cli.command {
        Commands::Auth { action } => match action {
            AuthAction::Status => commands::auth::run_auth_status()?,
        },

        Commands::List { workspace } => {
            commands::list::run_list(&http, &workspace).await?;
        }

        Commands::Create {
            reference,
            kernel,
            lakehouse,
            warehouse,
        } => {
            commands::create::run_create(
                &http,
                &reference,
                &kernel,
                lakehouse.as_deref(),
                warehouse.as_deref(),
            )
            .await?;
        }

        Commands::Job { action } => match action {
            JobAction::Run {
                reference,
                wait,
                timeout,
            } => {
                commands::run::run_run(&http, &reference, wait, timeout).await?;
            }
            JobAction::List { reference } => {
                commands::run::run_runs(&http, &reference).await?;
            }
        },

        Commands::Open { reference } => {
            commands::open::run_open(&http, &reference).await?;
        }

        Commands::Export { reference, output } => {
            commands::export::run_export(&http, &reference, &output).await?;
        }

        Commands::Cells { reference } => {
            commands::cells::run_cells_list(&http, &reference).await?;
        }

        Commands::Cell { action } => match action {
            CellAction::View { reference, index } => {
                commands::cells::run_cell_view(&http, &reference, index).await?;
            }
            CellAction::Add {
                reference,
                code,
                markdown,
                at,
            } => {
                commands::cells::run_cell_add(&http, &reference, &code, markdown, at).await?;
            }
            CellAction::Edit {
                reference,
                index,
                code,
            } => {
                commands::cells::run_cell_edit(&http, &reference, index, &code).await?;
            }
            CellAction::Rm { reference, index } => {
                commands::cells::run_cell_rm(&http, &reference, index).await?;
            }
        },

        Commands::Exec { action } => match action {
            ExecAction::Code {
                reference,
                code,
            } => {
                commands::exec::run_exec_quick(&http, &reference, &code).await?;
            }
            ExecAction::Cell {
                reference,
                index,
                lakehouse,
            } => {
                commands::exec::run_exec(&http, &reference, None, Some(index), lakehouse.as_deref()).await?;
            }
        },

        Commands::Session { reference } => {
            commands::session::run_session(&http, &reference).await?;
        }

        Commands::Schedule { action } => match action {
            ScheduleAction::List { reference } => {
                commands::schedule::run_schedule_list(&http, &reference).await?;
            }
            ScheduleAction::Create {
                reference,
                r#type,
                interval,
                start,
                end,
                timezone,
                enable,
            } => {
                commands::schedule::run_schedule_create(
                    &http,
                    &reference,
                    &r#type,
                    interval,
                    &start,
                    end.as_deref(),
                    &timezone,
                    enable,
                )
                .await?;
            }
            ScheduleAction::Update {
                reference,
                id,
                enable,
                interval,
                r#type,
            } => {
                commands::schedule::run_schedule_update(
                    &http,
                    &reference,
                    &id,
                    enable,
                    interval,
                    r#type.as_deref(),
                )
                .await?;
            }
            ScheduleAction::Delete { reference, id } => {
                commands::schedule::run_schedule_delete(&http, &reference, &id).await?;
            }
        },

        Commands::Delete { reference, force } => {
            let (ws_name, nb_name) = client::parse_ref(&reference)?;
            let ws_id = client::resolve_workspace(&http, ws_name).await?;
            let nb = client::resolve_item(&http, &ws_id, nb_name, "Notebook").await?;

            if !force {
                anyhow::bail!("Delete '{}' requires --force to confirm", nb.display_name);
            } else {
                let token = auth::get_fabric_token()?;
                let resp = http
                    .delete(format!(
                        "https://api.fabric.microsoft.com/v1/workspaces/{}/items/{}",
                        ws_id, nb.id
                    ))
                    .bearer_auth(&token)
                    .send()
                    .await?;

                if resp.status().is_success() {
                    println!("  Deleted '{}'", nb.display_name);
                } else {
                    let body = resp.text().await.unwrap_or_default();
                    anyhow::bail!("Delete failed: {}", body);
                }
            }
        }
    }

    Ok(())
}

// #endregion