-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathConvertMarkdownToNoteBook.ps1
109 lines (86 loc) · 2.94 KB
/
ConvertMarkdownToNoteBook.ps1
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
function Convert-MarkdownToNoteBook {
<#
.SYNOPSIS
Convert a markdown file to an interactive PowerShell Notebook
.Description
.Example
# converts .\demo.md to demo.ipynb
Convert-MarkdownToNoteBook .\demo.md
.Example
# converts .\demo.md to demo.ipynb and watches the file for changes and automatically converts it again
Convert-MarkdownToNoteBook .\demo.md -watch
#>
param(
$filename,
[Switch]$watch
)
function DoWatch {
param(
$targetFile,
[scriptblock]$sb
)
"Watching - Press Ctl-C to stop"
$targetFile = Resolve-Path $targetFile
$sb = {
foreach ($entry in $args[0].GetEnumerator()) {
if ($entry.Key -eq $targetFile -and $entry.Value -eq "Changed") {
& $sb
}
}
}.GetNewClosure()
&"$PSScriptRoot\Watch-Directory.ps1" -Path . -TestSeconds .5 -WaitSeconds 1 -Command $sb
}
"[{0}] Converting {1}" -f (Get-Date), $filename
$content = Get-Content $filename
$chapters = [ordered]@{ }
$chapterIndex = 1
switch ($content) {
"<!-- CHAPTER END -->" {
$inChapter = $false
$chapterIndex += 1
}
{ $inChapter } {
$currentChapter = "Chapter {0}" -f $chapterIndex
if (!$chapters.$currentChapter) {
$chapters.$currentChapter = @()
}
$chapters.$currentChapter += $_
}
"<!-- CHAPTER START -->" { $inChapter = $true }
}
$code = @()
$markDown = @()
New-PSNotebook -NoteBookName ($filename -replace '.md', '.ipynb') -IncludeCodeResults {
foreach ($chapter in $chapters.Keys) {
Add-NotebookMarkdown -markdown ("# $($chapter)")
$inCodeBlock = $false
switch ($chapters.$chapter) {
{ $_ -eq '```ps' -or $_ -eq '```powershell' } {
Add-NotebookMarkdown -markdown (-join $markDown)
$code = @()
$inCodeBlock = $true
}
'```' {
Add-NotebookCode -code (-join $code)
$markDown = @()
$inCodeBlock = $false
}
default {
if ($inCodeBlock) {
$code += $_ + "`r`n"
}
else {
$markDown += $_ + "`r`n"
}
}
}
if ($markDown) {
Add-NotebookMarkdown -markdown (-join $markDown)
$markDown = @()
}
}
}
"[{0}] Finished {1}" -f (Get-Date), $filename
# if ($Watch) { DoWatch $filename { .\ConvertMarkdownToNoteBook.ps1 -filename $filename } }
if ($Watch) { DoWatch $filename { Convert-MarkdownToNoteBook -filename $filename } }
}