Skip to content

Instantly share code, notes, and snippets.

@ognjenio
Last active May 12, 2021 01:19
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 ognjenio/764c6810c179fd21fa07e82d9dac3f4e to your computer and use it in GitHub Desktop.
Save ognjenio/764c6810c179fd21fa07e82d9dac3f4e to your computer and use it in GitHub Desktop.
Script for generating indexes for Dendron
require 'optparse'
require 'find'
def note(path, files)
return %Q|---
title: #{path} Index
desc: ''
updated: #{Time.now.to_i * 1000}
created: #{Time.now.to_i * 1000}
---
#{files if !files.to_s.empty?}
|
end
BASE = "<NOTES PATH>"
def clean(x)
x.gsub("[", "").gsub("]", "").gsub("((ref: ", "").gsub("))", "")
end
def make_index(path, deep)
puts "Creating #{path}..."
begin
existing = File.read(BASE + "#{path}index.md").split("\n")
front_matter_delimiter = 0
existing.each_with_index do |line, index|
if line == '---'
front_matter_delimiter = index
if index > 0
break
end
end
end
existing = existing[(front_matter_delimiter+1)..-1]
#.select{|x| x[0..1] == '[['}.map{|x| x.gsub("[", "").gsub("]", "")}
rescue
existing = []
end
if deep
files = Find.find(BASE + "#{path}").to_a.map{|x| x.gsub("#{BASE}#{path}", "")}.select{|x| !x.include? "index.md"}.sort
else
files = Dir[BASE + "#{path}*.md"].map{|x| x.gsub("#{BASE}#{path}", "")}.select{|x| !x.include? "index.md"}.sort
end
existing = existing.select{|x| !x.include? '[[' or files.include?(clean(x))}
new_files = files - existing.map{|x| clean(x)}
puts files
puts "---"
puts existing
puts "---"
puts new_files
files = (existing + (new_files).map{|x| "[[#{x.gsub("#{path}", "")}]]"}.sort).join("\n")
File.open("#{BASE}#{path}index.md", 'w') do |f|
f.write note(path, files)
end
end
def update_all(deep)
files = Dir[BASE + "*/index.md"].map{|x| x.gsub(BASE, "").gsub("index.md", "")}.each do |index|
make_index(index, deep)
end
end
deep = false
path = nil
OptionParser.new do |opts|
opts.banner = "Usage: d.rb [options]"
opts.on("-pPATH", "--path=PATH", "Path") do |v|
path = v
end
opts.on("-d", "--deep", "Deep") do |v|
deep = true
end
opts.on("-h", "--help", "Prints this help") do
puts opts
exit
end
end.parse!
if !path.empty?
if path == 'update'
update_all(deep)
else
path = path + "/" if path[-1] != '/'
make_index(path, deep)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment