Skip to content

Instantly share code, notes, and snippets.

@matejdro
Last active March 11, 2019 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matejdro/047e179738ca85fa108d9b07e81f6315 to your computer and use it in GitHub Desktop.
Save matejdro/047e179738ca85fa108d9b07e81f6315 to your computer and use it in GitHub Desktop.
$thisDirectory = (Get-Location).Path
$notes = Get-ChildItem -Path . -Filter *.md -Recurse -ErrorAction SilentlyContinue -Force
foreach ($note in $notes) {
$relativeFolder = $note.DirectoryName.Replace($thisDirectory, "").Trim().TrimStart("\")
$contents = Get-Content -Path $note.FullName
if ($relativeFolder.Length -eq 0) {
$relativeFolder = "."
}
$tagsMatch = [regex]::Match($contents, "tags: \[(.*?)\]")
if ($contents.Contains("deleted: true")) {
$tags = @("zzz_Trash")
} elseif ($tagsMatch.Groups.Count -lt 2) {
$tags = @()
} else {
$tags = ((,($tagsMatch.Groups[1].Value -split ", ") | Where-Object {$_.StartsWith("Notebooks")}) -replace "Notebooks/","")
}
if ($tags.Count -eq 0) {
$targetDirectory = "."
} ElseIf ($tags.Count -eq 1) {
$targetDirectory = ($tags[0] -replace "[^\w\-. /]", "_")
} else {
$splitTags = @()
foreach ($tag in $tags) {
$splitTags += ,($tag -split "/")
}
$minTagLength = 99999
foreach ($tags in $splitTags) {
$minTagLength = [math]::min($minTagLength, $tags.Count)
}
$equalPath = "";
:outer for ($i = 0; $i -lt $minTagLength; $i++){
$tagName = $splitTags[0][$i];
for ($j = 0; $j -lt $splitTags.Count; $j++){
if ($splitTags[$j][$i] -ne $tagName) {
break outer;
}
}
$equalPath += ,($tagName -replace "[^\w\-. ]", "_");
$equalPath += "/"
}
if ($equalPath.Length -eq 0) {
$targetDirectory = "."
} else {
$targetDirectory = $equalPath.TrimEnd("/")
}
}
$targetDirectory = $targetDirectory.Replace('/', '\')
if ($targetDirectory -ne $relativeFolder) {
echo "Moving $($note.Name) from $relativeFolder to $targetDirectory"
New-Item $targetDirectory -ItemType Directory -ErrorAction SilentlyContinue
move $note.FullName $targetDirectory
} else {
# echo "$($note.Name) Is already in proper folder"
}
}
echo "Complete"
pause
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment