From 801e58ca2787157c17f1d23826530757b5d2cad2 Mon Sep 17 00:00:00 2001 From: Glenn Date: Fri, 24 Mar 2023 16:53:27 +0100 Subject: [PATCH 01/25] feat: prepare for future commands --- src/{launcher.cr => builder/builder.cr} | 16 ++++++++++++- src/cli.cr | 32 +++++++++++++++---------- src/planner/planner.cr | 11 +++++++++ src/scaffolder/scaffolder.cr | 12 ++++++++++ 4 files changed, 57 insertions(+), 14 deletions(-) rename src/{launcher.cr => builder/builder.cr} (91%) create mode 100644 src/planner/planner.cr create mode 100644 src/scaffolder/scaffolder.cr diff --git a/src/launcher.cr b/src/builder/builder.cr similarity index 91% rename from src/launcher.cr rename to src/builder/builder.cr index 9e06b66..e7c5d74 100644 --- a/src/launcher.cr +++ b/src/builder/builder.cr @@ -1,6 +1,6 @@ module DocMachine - class Launcher + class Builder def initialize(config) @basedir = config[:data_dir]? ? config[:data_dir] : Dir.current @basehash = Digest::SHA256.hexdigest(@basedir)[0..6] @@ -120,5 +120,19 @@ module DocMachine def docker_opts() end + + def self.add_options(opts) + opts.on("build", "Build content and produce deliverables") do + opts.banner = [ + "Usage: #{PROGRAM_NAME} build [options]", + "", + "Main options:" + ].join("\n") + + opts.separator "" + opts.separator "Builder Options:" + opts.on("-t", "--test", "Test") { puts "Test" } + end + end end end diff --git a/src/cli.cr b/src/cli.cr index 038addf..cacc236 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -2,7 +2,9 @@ require "option_parser" require "digest/sha256" require "colorize" -require "./launcher" +require "./builder/builder.cr" +require "./scaffolder/scaffolder.cr" +require "./planner/planner.cr" module DocMachine class Cli @@ -13,7 +15,11 @@ module DocMachine options = {} of Symbol => String parser = OptionParser.new do |opts| - opts.banner = "Usage: script.cr [options]" + opts.banner = [ + "Usage: #{PROGRAM_NAME} [options]", + "", + "Main options:" + ].join("\n") opts.on("-d", "--data-dir DIR", "Content directory") do |dir| options[:data_dir] = dir @@ -35,6 +41,12 @@ module DocMachine puts opts exit end + + opts.separator "" + opts.separator "Commands:" + DocMachine::Builder.add_options(opts) + DocMachine::Scaffolder.add_options(opts) + DocMachine::Planner.add_options(opts) end parser.parse(ARGV) @@ -47,20 +59,14 @@ module DocMachine docker_image = "glenux/docmachine:latest" if options[:help]? - puts "Usage: script.cr [options]" - puts "" - puts "-d, --data-dir DIR Content directory" - puts "-a, --action ACTION Action (watch, build, shell, etc.)" - puts "-t, --tty Enable TTY mode (needed for shell)" - puts "-v, --verbose Enable verbosity" - puts "-h, --help Show this help" + puts parser.to_s exit end - launcher = DocMachine::Launcher.new(options) - launcher.prepare - launcher.start - launcher.wait + builder = DocMachine::Builder.new(options) + builder.prepare + builder.start + builder.wait end end end diff --git a/src/planner/planner.cr b/src/planner/planner.cr new file mode 100644 index 0000000..ffce06e --- /dev/null +++ b/src/planner/planner.cr @@ -0,0 +1,11 @@ + +module DocMachine + class Planner + def self.add_options(opts) + opts.on("content", "Generate content and structure") do + opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" + opts.on("-t", "--test", "Test") { puts "Test" } + end + end + end +end diff --git a/src/scaffolder/scaffolder.cr b/src/scaffolder/scaffolder.cr new file mode 100644 index 0000000..72df864 --- /dev/null +++ b/src/scaffolder/scaffolder.cr @@ -0,0 +1,12 @@ + +module DocMachine + class Scaffolder + def self.add_options(opts) + opts.on("scaffold", "Scaffold directory") do + opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options]" + + opts.on("-t", "--test", "Test") { puts "Test" } + end + end + end +end From 9a87615129fc4315d6db0f0f79b11a4d6c7f32e6 Mon Sep 17 00:00:00 2001 From: Glenn Date: Sat, 25 Mar 2023 20:40:52 +0100 Subject: [PATCH 02/25] feat: Prepare for multi-command --- src/builder/builder.cr | 138 ----------------------------------- src/builder/cli.cr | 33 +++++++++ src/builder/config.cr | 13 ++++ src/builder/run.cr | 128 ++++++++++++++++++++++++++++++++ src/cli.cr | 45 +++--------- src/config.cr | 10 +++ src/planner/cli.cr | 17 +++++ src/planner/config.cr | 9 +++ src/planner/planner.cr | 11 --- src/scaffolder/cli.cr | 15 ++++ src/scaffolder/config.cr | 10 +++ src/scaffolder/scaffolder.cr | 12 --- 12 files changed, 247 insertions(+), 194 deletions(-) delete mode 100644 src/builder/builder.cr create mode 100644 src/builder/cli.cr create mode 100644 src/builder/config.cr create mode 100644 src/builder/run.cr create mode 100644 src/config.cr create mode 100644 src/planner/cli.cr create mode 100644 src/planner/config.cr delete mode 100644 src/planner/planner.cr create mode 100644 src/scaffolder/cli.cr create mode 100644 src/scaffolder/config.cr delete mode 100644 src/scaffolder/scaffolder.cr diff --git a/src/builder/builder.cr b/src/builder/builder.cr deleted file mode 100644 index e7c5d74..0000000 --- a/src/builder/builder.cr +++ /dev/null @@ -1,138 +0,0 @@ - -module DocMachine - class Builder - def initialize(config) - @basedir = config[:data_dir]? ? config[:data_dir] : Dir.current - @basehash = Digest::SHA256.hexdigest(@basedir)[0..6] - @action = config[:action]? ? config[:action] : "watch" - # @verbosity = config[:verbose]? ? config[:verbose] : 0 - @docker_name = "docmachine-#{@basehash}" - @docker_image = "glenux/docmachine:latest" - @docker_opts = [] of String - @enable_tty = !!config[:tty]? - @process = nil - end - - - # cleanup environment - # create directories - # setup permissions - def prepare() - puts "basedir = #{@basedir}" - puts "docker_image = #{@docker_image}" - puts "action = #{@action}" - - docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip - - puts "docker_name: #{@docker_name}" - puts "docker_cid: #{docker_cid}" - - if !docker_cid.empty? - Process.run("docker", ["kill", @docker_name]) - end - end - - def start() - uid = %x{id -u}.strip - gid = %x{id -g}.strip - puts "uid: #{uid}" - puts "cid: #{gid}" - - docker_opts = [] of String - docker_opts << "run" - docker_opts << "-i" - # add tty support - docker_opts << "-t" if @enable_tty - # add container name - docker_opts.concat ["--name", @docker_name] - docker_opts << "--rm" - docker_opts << "--shm-size=1gb" - docker_opts.concat ["-e", "EXT_UID=#{uid}"] - docker_opts.concat ["-e", "EXT_GID=#{gid}"] - docker_opts.concat ["-v", "#{@basedir}/docs:/app/docs"] - docker_opts.concat ["-v", "#{@basedir}/slides:/app/slides"] - docker_opts.concat ["-v", "#{@basedir}/images:/app/images"] - docker_opts.concat ["-v", "#{@basedir}/_build:/app/_build"] - - ## Detect Marp SCSS - if File.exists?("#{@basedir}/.marp/theme.scss") - docker_opt_marp_theme = ["-v", "#{@basedir}/.marp:/app/.marp"] - docker_opts.concat docker_opt_marp_theme - puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" - else - puts "Theme: no theme detected. Using default files" - end - - ## Detect Mkdocs configuration - old format (full) - if File.exists?("#{@basedir}/mkdocs.yml") - puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" - exit 1 - end - - ## Detect Mkdocs configuration - new format (patch) - if File.exists?("#{@basedir}/mkdocs-patch.yml") - docker_opt_mkdocs_config = ["-v", "#{@basedir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] - docker_opts.concat docker_opt_mkdocs_config - puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" - else - puts "Mkdocs: no mkdocs-patch.yml detected. Using default files" - end - - ## Detect slides - if Dir.exists?("#{@basedir}/slides") - docker_opt_marp_port = ["-p", "5200:5200"] - docker_opts.concat docker_opt_marp_port - puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" - else - puts "Slides: no slides directory detected." - end - - ## Detect docs - if Dir.exists?("#{@basedir}/docs") - docker_opt_marp_port = ["-p", "5100:5100"] - docker_opts.concat docker_opt_marp_port - puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" - else - puts "Slides: no slides docs detected." - end - - docker_opts << @docker_image - docker_opts << @action - - puts docker_opts.inspect.colorize(:yellow) - @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) - end - - def wait() - process = @process - return if process.nil? - - Signal::INT.trap do - STDERR.puts "Received CTRL-C" - process.signal(Signal::KILL) - Process.run("docker", ["kill", @docker_name]) - end - process.wait - end - - def stop() - end - - def docker_opts() - end - - def self.add_options(opts) - opts.on("build", "Build content and produce deliverables") do - opts.banner = [ - "Usage: #{PROGRAM_NAME} build [options]", - "", - "Main options:" - ].join("\n") - - opts.separator "" - opts.separator "Builder Options:" - opts.on("-t", "--test", "Test") { puts "Test" } - end - end - end -end diff --git a/src/builder/cli.cr b/src/builder/cli.cr new file mode 100644 index 0000000..715bf45 --- /dev/null +++ b/src/builder/cli.cr @@ -0,0 +1,33 @@ + +require "./config" + +module DocMachine::Builder + class Cli + def self.add_options(opts, parent_config) + config = Config.new(parent_config) + + opts.on("build", "Build content and produce deliverables") do + opts.banner = [ + "Usage: #{PROGRAM_NAME} build [options]", + "", + "Main options:" + ].join("\n") + + opts.separator "" + opts.separator "Builder Options:" + + opts.on("-d", "--data-dir DIR", "Content directory") do |dir| + config.data_dir = dir + end + + opts.on("-a", "--action ACTION", "Action (watch, build, shell, etc.)") do |action| + config.action = action + end + + opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do + config.enable_tty = true + end + end + end + end +end diff --git a/src/builder/config.cr b/src/builder/config.cr new file mode 100644 index 0000000..67787c9 --- /dev/null +++ b/src/builder/config.cr @@ -0,0 +1,13 @@ + +module DocMachine + module Builder + class Config + property data_dir : String = Dir.current + property action : String = "watch" + property enable_tty : Bool = false + + def initialize(@parent : DocMachine::Config) + end + end + end +end diff --git a/src/builder/run.cr b/src/builder/run.cr new file mode 100644 index 0000000..5c6a211 --- /dev/null +++ b/src/builder/run.cr @@ -0,0 +1,128 @@ + +require "./config" + +module DocMachine + module Builder + + class Run + def initialize(@config : DocMachine::Builder::Config) + @basedir = config[:data_dir]? ? config[:data_dir] : Dir.current + @basehash = Digest::SHA256.hexdigest(@basedir)[0..6] + @action = config[:action]? ? config[:action] : "watch" + # @verbosity = config[:verbose]? ? config[:verbose] : 0 + @docker_name = "docmachine-#{@basehash}" + @docker_image = "glenux/docmachine:latest" + @docker_opts = [] of String + @process = nil + end + + + # cleanup environment + # create directories + # setup permissions + def prepare() + puts "basedir = #{@basedir}" + puts "docker_image = #{@docker_image}" + puts "action = #{@action}" + + docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip + + puts "docker_name: #{@docker_name}" + puts "docker_cid: #{docker_cid}" + + if !docker_cid.empty? + Process.run("docker", ["kill", @docker_name]) + end + end + + def start() + uid = %x{id -u}.strip + gid = %x{id -g}.strip + puts "uid: #{uid}" + puts "cid: #{gid}" + + docker_opts = [] of String + docker_opts << "run" + docker_opts << "-i" + # add tty support + docker_opts << "-t" if @enable_tty + # add container name + docker_opts.concat ["--name", @docker_name] + docker_opts << "--rm" + docker_opts << "--shm-size=1gb" + docker_opts.concat ["-e", "EXT_UID=#{uid}"] + docker_opts.concat ["-e", "EXT_GID=#{gid}"] + docker_opts.concat ["-v", "#{@basedir}/docs:/app/docs"] + docker_opts.concat ["-v", "#{@basedir}/slides:/app/slides"] + docker_opts.concat ["-v", "#{@basedir}/images:/app/images"] + docker_opts.concat ["-v", "#{@basedir}/_build:/app/_build"] + + ## Detect Marp SCSS + if File.exists?("#{@basedir}/.marp/theme.scss") + docker_opt_marp_theme = ["-v", "#{@basedir}/.marp:/app/.marp"] + docker_opts.concat docker_opt_marp_theme + puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" + else + puts "Theme: no theme detected. Using default files" + end + + ## Detect Mkdocs configuration - old format (full) + if File.exists?("#{@basedir}/mkdocs.yml") + puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" + exit 1 + end + + ## Detect Mkdocs configuration - new format (patch) + if File.exists?("#{@basedir}/mkdocs-patch.yml") + docker_opt_mkdocs_config = ["-v", "#{@basedir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] + docker_opts.concat docker_opt_mkdocs_config + puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" + else + puts "Mkdocs: no mkdocs-patch.yml detected. Using default files" + end + + ## Detect slides + if Dir.exists?("#{@basedir}/slides") + docker_opt_marp_port = ["-p", "5200:5200"] + docker_opts.concat docker_opt_marp_port + puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" + else + puts "Slides: no slides directory detected." + end + + ## Detect docs + if Dir.exists?("#{@basedir}/docs") + docker_opt_marp_port = ["-p", "5100:5100"] + docker_opts.concat docker_opt_marp_port + puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" + else + puts "Slides: no slides docs detected." + end + + docker_opts << @docker_image + docker_opts << @action + + puts docker_opts.inspect.colorize(:yellow) + @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) + end + + def wait() + process = @process + return if process.nil? + + Signal::INT.trap do + STDERR.puts "Received CTRL-C" + process.signal(Signal::KILL) + Process.run("docker", ["kill", @docker_name]) + end + process.wait + end + + def stop() + end + + def docker_opts() + end + end + end +end diff --git a/src/cli.cr b/src/cli.cr index cacc236..93e940c 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -2,9 +2,11 @@ require "option_parser" require "digest/sha256" require "colorize" -require "./builder/builder.cr" -require "./scaffolder/scaffolder.cr" -require "./planner/planner.cr" +require "./config" +require "./builder/cli" +require "./builder/run" +require "./scaffolder/cli" +require "./planner/cli" module DocMachine class Cli @@ -12,7 +14,7 @@ module DocMachine end def start(argv) - options = {} of Symbol => String + config = Config.new parser = OptionParser.new do |opts| opts.banner = [ @@ -21,20 +23,8 @@ module DocMachine "Main options:" ].join("\n") - opts.on("-d", "--data-dir DIR", "Content directory") do |dir| - options[:data_dir] = dir - end - - opts.on("-a", "--action ACTION", "Action (watch, build, shell, etc.)") do |action| - options[:action] = action - end - - opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do |tty| - options[:tty] = tty - end - opts.on("-v", "--verbose", "Enable verbosity") do |verbose| - options[:verbose] = true.to_s + config.verbose = true end opts.on("-h", "--help", "Show this help") do @@ -44,26 +34,15 @@ module DocMachine opts.separator "" opts.separator "Commands:" - DocMachine::Builder.add_options(opts) - DocMachine::Scaffolder.add_options(opts) - DocMachine::Planner.add_options(opts) + + DocMachine::Builder::Cli.add_options(opts, config) + DocMachine::Scaffolder::Cli.add_options(opts, config) + DocMachine::Planner::Cli.add_options(opts, config) end parser.parse(ARGV) - - basedir = options[:data_dir]? ? options[:data_dir] : Dir.current - basehash = Digest::SHA256.hexdigest(basedir)[0..6] - action = options[:action]? ? options[:action] : "watch" - verbosity = options[:verbose]? ? options[:verbose] : 0 - docker_image = "glenux/docmachine:latest" - - if options[:help]? - puts parser.to_s - exit - end - - builder = DocMachine::Builder.new(options) + builder = DocMachine::Builder::Run.new(config) builder.prepare builder.start builder.wait diff --git a/src/config.cr b/src/config.cr new file mode 100644 index 0000000..3de0e98 --- /dev/null +++ b/src/config.cr @@ -0,0 +1,10 @@ + +module DocMachine + class Config + + property verbose : Bool = false + + def initialize + end + end +end diff --git a/src/planner/cli.cr b/src/planner/cli.cr new file mode 100644 index 0000000..5edaa1a --- /dev/null +++ b/src/planner/cli.cr @@ -0,0 +1,17 @@ + +require "./config" + +module DocMachine + module Planner + class Cli + def self.add_options(opts, parent_config) + config = Config.new(parent_config) + + opts.on("content", "Generate content and structure") do + opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" + opts.on("-t", "--test", "Test") { puts "Test" } + end + end + end + end +end diff --git a/src/planner/config.cr b/src/planner/config.cr new file mode 100644 index 0000000..6444962 --- /dev/null +++ b/src/planner/config.cr @@ -0,0 +1,9 @@ + +module DocMachine + module Planner + class Config + def initialize(@parent : DocMachine::Config) + end + end + end +end diff --git a/src/planner/planner.cr b/src/planner/planner.cr deleted file mode 100644 index ffce06e..0000000 --- a/src/planner/planner.cr +++ /dev/null @@ -1,11 +0,0 @@ - -module DocMachine - class Planner - def self.add_options(opts) - opts.on("content", "Generate content and structure") do - opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" - opts.on("-t", "--test", "Test") { puts "Test" } - end - end - end -end diff --git a/src/scaffolder/cli.cr b/src/scaffolder/cli.cr new file mode 100644 index 0000000..f3113e7 --- /dev/null +++ b/src/scaffolder/cli.cr @@ -0,0 +1,15 @@ +require "./config" + +module DocMachine + module Scaffolder + class Cli + def self.add_options(opts, parent_config) + config = Config.new(parent_config) + + opts.on("scaffold", "Scaffold directory") do + opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options]" + end + end + end + end +end diff --git a/src/scaffolder/config.cr b/src/scaffolder/config.cr new file mode 100644 index 0000000..e242c5e --- /dev/null +++ b/src/scaffolder/config.cr @@ -0,0 +1,10 @@ + + +module DocMachine + module Scaffolder + class Config + def initialize(@parent : DocMachine::Config) + end + end + end +end diff --git a/src/scaffolder/scaffolder.cr b/src/scaffolder/scaffolder.cr deleted file mode 100644 index 72df864..0000000 --- a/src/scaffolder/scaffolder.cr +++ /dev/null @@ -1,12 +0,0 @@ - -module DocMachine - class Scaffolder - def self.add_options(opts) - opts.on("scaffold", "Scaffold directory") do - opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options]" - - opts.on("-t", "--test", "Test") { puts "Test" } - end - end - end -end From 5f83e7821ecb9ed586cb09a330ea5ff009d1989f Mon Sep 17 00:00:00 2001 From: Glenn Date: Sat, 25 Mar 2023 20:41:12 +0100 Subject: [PATCH 03/25] feat: show error trace --- Makefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 371d330..a54ec15 100644 --- a/Makefile +++ b/Makefile @@ -3,4 +3,5 @@ all: build build: - shards build + shards build --error-trace + read A From 6d34bec0e69d652a011d57f4c7cce799a97daabc Mon Sep 17 00:00:00 2001 From: Glenn Date: Sun, 26 Mar 2023 11:41:40 +0200 Subject: [PATCH 04/25] feat: Organize for subcommands --- src/builder/cli.cr | 10 +++++++++- src/builder/run.cr | 35 ++++++++++++++++------------------- src/cli.cr | 19 ++++++++++--------- src/planner/cli.cr | 2 +- src/scaffolder/cli.cr | 9 ++++++++- src/scaffolder/run.cr | 0 6 files changed, 44 insertions(+), 31 deletions(-) create mode 100644 src/scaffolder/run.cr diff --git a/src/builder/cli.cr b/src/builder/cli.cr index 715bf45..23a3d77 100644 --- a/src/builder/cli.cr +++ b/src/builder/cli.cr @@ -3,7 +3,7 @@ require "./config" module DocMachine::Builder class Cli - def self.add_options(opts, parent_config) + def self.add_options(opts, args, parent_config, command) config = Config.new(parent_config) opts.on("build", "Build content and produce deliverables") do @@ -27,7 +27,15 @@ module DocMachine::Builder opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do config.enable_tty = true end + + command << ->() : Nil do + app = DocMachine::Builder::Run.new(config) + app.prepare + app.start + app.wait + end end + end end end diff --git a/src/builder/run.cr b/src/builder/run.cr index 5c6a211..1700062 100644 --- a/src/builder/run.cr +++ b/src/builder/run.cr @@ -6,10 +6,7 @@ module DocMachine class Run def initialize(@config : DocMachine::Builder::Config) - @basedir = config[:data_dir]? ? config[:data_dir] : Dir.current - @basehash = Digest::SHA256.hexdigest(@basedir)[0..6] - @action = config[:action]? ? config[:action] : "watch" - # @verbosity = config[:verbose]? ? config[:verbose] : 0 + @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] @docker_name = "docmachine-#{@basehash}" @docker_image = "glenux/docmachine:latest" @docker_opts = [] of String @@ -21,9 +18,9 @@ module DocMachine # create directories # setup permissions def prepare() - puts "basedir = #{@basedir}" + puts "basedir = #{@config.data_dir}" puts "docker_image = #{@docker_image}" - puts "action = #{@action}" + puts "action = #{@config.action}" docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip @@ -45,21 +42,21 @@ module DocMachine docker_opts << "run" docker_opts << "-i" # add tty support - docker_opts << "-t" if @enable_tty + docker_opts << "-t" if @config.enable_tty # add container name docker_opts.concat ["--name", @docker_name] docker_opts << "--rm" docker_opts << "--shm-size=1gb" docker_opts.concat ["-e", "EXT_UID=#{uid}"] docker_opts.concat ["-e", "EXT_GID=#{gid}"] - docker_opts.concat ["-v", "#{@basedir}/docs:/app/docs"] - docker_opts.concat ["-v", "#{@basedir}/slides:/app/slides"] - docker_opts.concat ["-v", "#{@basedir}/images:/app/images"] - docker_opts.concat ["-v", "#{@basedir}/_build:/app/_build"] + docker_opts.concat ["-v", "#{@config.data_dir}/docs:/app/docs"] + docker_opts.concat ["-v", "#{@config.data_dir}/slides:/app/slides"] + docker_opts.concat ["-v", "#{@config.data_dir}/images:/app/images"] + docker_opts.concat ["-v", "#{@config.data_dir}/_build:/app/_build"] ## Detect Marp SCSS - if File.exists?("#{@basedir}/.marp/theme.scss") - docker_opt_marp_theme = ["-v", "#{@basedir}/.marp:/app/.marp"] + if File.exists?("#{@config.data_dir}/.marp/theme.scss") + docker_opt_marp_theme = ["-v", "#{@config.data_dir}/.marp:/app/.marp"] docker_opts.concat docker_opt_marp_theme puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" else @@ -67,14 +64,14 @@ module DocMachine end ## Detect Mkdocs configuration - old format (full) - if File.exists?("#{@basedir}/mkdocs.yml") + if File.exists?("#{@config.data_dir}/mkdocs.yml") puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" exit 1 end ## Detect Mkdocs configuration - new format (patch) - if File.exists?("#{@basedir}/mkdocs-patch.yml") - docker_opt_mkdocs_config = ["-v", "#{@basedir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] + if File.exists?("#{@config.data_dir}/mkdocs-patch.yml") + docker_opt_mkdocs_config = ["-v", "#{@config.data_dir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] docker_opts.concat docker_opt_mkdocs_config puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" else @@ -82,7 +79,7 @@ module DocMachine end ## Detect slides - if Dir.exists?("#{@basedir}/slides") + if Dir.exists?("#{@config.data_dir}/slides") docker_opt_marp_port = ["-p", "5200:5200"] docker_opts.concat docker_opt_marp_port puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" @@ -91,7 +88,7 @@ module DocMachine end ## Detect docs - if Dir.exists?("#{@basedir}/docs") + if Dir.exists?("#{@config.data_dir}/docs") docker_opt_marp_port = ["-p", "5100:5100"] docker_opts.concat docker_opt_marp_port puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" @@ -100,7 +97,7 @@ module DocMachine end docker_opts << @docker_image - docker_opts << @action + docker_opts << @config.action puts docker_opts.inspect.colorize(:yellow) @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) diff --git a/src/cli.cr b/src/cli.cr index 93e940c..052cc65 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -13,8 +13,9 @@ module DocMachine def initialize end - def start(argv) + def start(args) config = Config.new + commands = [] of Proc(Nil) parser = OptionParser.new do |opts| opts.banner = [ @@ -35,17 +36,17 @@ module DocMachine opts.separator "" opts.separator "Commands:" - DocMachine::Builder::Cli.add_options(opts, config) - DocMachine::Scaffolder::Cli.add_options(opts, config) - DocMachine::Planner::Cli.add_options(opts, config) + DocMachine::Builder::Cli.add_options(opts, args, config, commands) + DocMachine::Scaffolder::Cli.add_options(opts, args, config, commands) + DocMachine::Planner::Cli.add_options(opts, args, config, commands) end - parser.parse(ARGV) + parser.parse(args) - builder = DocMachine::Builder::Run.new(config) - builder.prepare - builder.start - builder.wait + commands.each do |command| + puts "running #{command}" + command.call() + end end end end diff --git a/src/planner/cli.cr b/src/planner/cli.cr index 5edaa1a..c82b47b 100644 --- a/src/planner/cli.cr +++ b/src/planner/cli.cr @@ -4,7 +4,7 @@ require "./config" module DocMachine module Planner class Cli - def self.add_options(opts, parent_config) + def self.add_options(opts, args, parent_config, command) config = Config.new(parent_config) opts.on("content", "Generate content and structure") do diff --git a/src/scaffolder/cli.cr b/src/scaffolder/cli.cr index f3113e7..a049bf0 100644 --- a/src/scaffolder/cli.cr +++ b/src/scaffolder/cli.cr @@ -3,12 +3,19 @@ require "./config" module DocMachine module Scaffolder class Cli - def self.add_options(opts, parent_config) + def self.add_options(opts, args, parent_config, command) config = Config.new(parent_config) opts.on("scaffold", "Scaffold directory") do opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options]" end + + command << ->() : Nil do + # app = DocMachine::Scaffolder::Run.new(config) + # app.prepare + # app.start + # app.wait + end end end end diff --git a/src/scaffolder/run.cr b/src/scaffolder/run.cr new file mode 100644 index 0000000..e69de29 From b8c887682b5a8a536bb42f88310ef4605b01deb0 Mon Sep 17 00:00:00 2001 From: Glenn Date: Mon, 27 Mar 2023 16:01:20 +0200 Subject: [PATCH 05/25] feat: Add support for scaffold --- .gitignore | 1 + shard.lock | 30 ++++++++++++++++++++ shard.yml | 13 ++++++--- src/builder/cli.cr | 4 +-- src/cli.cr | 13 +++++++-- src/scaffolder/cli.cr | 33 ++++++++++++++-------- src/scaffolder/config.cr | 11 ++++---- src/scaffolder/run.cr | 61 ++++++++++++++++++++++++++++++++++++++++ 8 files changed, 140 insertions(+), 26 deletions(-) create mode 100644 shard.lock diff --git a/.gitignore b/.gitignore index 4052fca..ea479e5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /bin +/lib diff --git a/shard.lock b/shard.lock new file mode 100644 index 0000000..6e040c8 --- /dev/null +++ b/shard.lock @@ -0,0 +1,30 @@ +version: 2.0 +shards: + completion: + git: https://github.com/f/completion.git + version: 0.1.0+git.commit.d8799381b2de14430496199260eca64eb329625f + + cor: + git: https://github.com/watzon/cor.git + version: 0.1.0+git.commit.9c9e51ac6168f3bd4fdc51d679b65de09ef76cac + + ioctl: + git: https://github.com/crystal-posix/ioctl.cr.git + version: 1.0.0 + + term-cursor: + git: https://github.com/crystal-term/cursor.git + version: 0.1.0+git.commit.8805d5f686d153db92cf2ce3333433f8ed3708d0 + + term-prompt: + git: https://github.com/crystal-term/prompt.git + version: 0.1.0+git.commit.bf2b17f885a6c660aea0dda62b0b9da4343ab295 + + term-reader: + git: https://github.com/crystal-term/reader.git + version: 0.1.0+git.commit.cd022d4d4628e5d9de47e669a770ccb7df412863 + + term-screen: + git: https://github.com/crystal-term/screen.git + version: 0.1.0+git.commit.ea51ee8d1f6c286573c41a7e784d31c80af7b9bb + diff --git a/shard.yml b/shard.yml index 4eb42db..fdfff8b 100644 --- a/shard.yml +++ b/shard.yml @@ -12,10 +12,15 @@ targets: docmachine: main: src/main.cr -# dependencies: -# pg: -# github: will/crystal-pg -# version: "~> 0.5" +dependencies: + term-prompt: + github: crystal-term/prompt + +# completion: +# github: f/completion +# pg: +# github: will/crystal-pg +# version: "~> 0.5" # development_dependencies: # webmock: diff --git a/src/builder/cli.cr b/src/builder/cli.cr index 23a3d77..fcd6d86 100644 --- a/src/builder/cli.cr +++ b/src/builder/cli.cr @@ -3,7 +3,7 @@ require "./config" module DocMachine::Builder class Cli - def self.add_options(opts, args, parent_config, command) + def self.add_options(opts, args, parent_config, commands) config = Config.new(parent_config) opts.on("build", "Build content and produce deliverables") do @@ -28,7 +28,7 @@ module DocMachine::Builder config.enable_tty = true end - command << ->() : Nil do + commands << ->() : Nil do app = DocMachine::Builder::Run.new(config) app.prepare app.start diff --git a/src/cli.cr b/src/cli.cr index 052cc65..d6627de 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -42,10 +42,17 @@ module DocMachine end parser.parse(args) + puts commands - commands.each do |command| - puts "running #{command}" - command.call() + if commands.size > 0 + commands.each do |command| + # puts "== Running #{command}" + command.call() + end + else + puts parser.to_s + STDOUT.puts "" + STDERR.puts "ERROR: no command defined" end end end diff --git a/src/scaffolder/cli.cr b/src/scaffolder/cli.cr index a049bf0..b803f6b 100644 --- a/src/scaffolder/cli.cr +++ b/src/scaffolder/cli.cr @@ -1,20 +1,29 @@ require "./config" +require "./run" -module DocMachine - module Scaffolder - class Cli - def self.add_options(opts, args, parent_config, command) - config = Config.new(parent_config) +module DocMachine::Scaffolder + class Cli + def self.add_options(opts, args, parent_config, commands) + config = Config.new(parent_config) - opts.on("scaffold", "Scaffold directory") do - opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options]" + opts.on("scaffold", "Scaffold target directory") do + opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options] TARGET" + + opts.on("-f", "--force", "Don't ask for confirmation") do + config.force = true end - command << ->() : Nil do - # app = DocMachine::Scaffolder::Run.new(config) - # app.prepare - # app.start - # app.wait + commands << ->() : Nil do + if args.size < 1 + STDERR.puts "ERROR: No target given!" + exit 1 + end + config.target_directory = args[0] + + app = DocMachine::Scaffolder::Run.new(config) + app.prepare + app.start + app.wait end end end diff --git a/src/scaffolder/config.cr b/src/scaffolder/config.cr index e242c5e..4b4bb63 100644 --- a/src/scaffolder/config.cr +++ b/src/scaffolder/config.cr @@ -1,10 +1,11 @@ -module DocMachine - module Scaffolder - class Config - def initialize(@parent : DocMachine::Config) - end +module DocMachine::Scaffolder + class Config + property target_directory : String = "." + property force : Bool = false + + def initialize(@parent : DocMachine::Config) end end end diff --git a/src/scaffolder/run.cr b/src/scaffolder/run.cr index e69de29..c3dafa7 100644 --- a/src/scaffolder/run.cr +++ b/src/scaffolder/run.cr @@ -0,0 +1,61 @@ + +# Core +require "file_utils" + +# Internal +require "./config" + +# Shards +require "term-prompt" + +module DocMachine::Scaffolder + class Run + private property config : DocMachine::Scaffolder::Config + + def initialize(@config) + end + + # Verify parameters + def prepare() + if ! File.directory? @config.target_directory + STDERR.puts "ERROR: target must be a directory" + exit 1 + end + + puts "Target directory: #{@config.target_directory}" + + if !@config.force + prompt = Term::Prompt.new + confirm = prompt.no?("Are you sure you want to proceed?") + exit 1 if !confirm + end + end + + def start() + puts "== Scaffolding #{@config.target_directory}" + p = Path.new(@config.target_directory) + cwd = Dir.current + ["docs", "slides", "images"].each do |dir| + p_sub = p.join(dir) + puts "-- creating #{p_sub}" + FileUtils.mkdir_p(p_sub) + end + ["docs", "slides"].each do |dir| + p_sub = p.join(dir) + FileUtils.cd(p_sub) + puts "-- creating link to images in #{p_sub}" + if File.symlink? "images" + FileUtils.rm "images" + end + FileUtils.ln_sf(Path.new("..","images"), Path.new("images")) + FileUtils.cd(cwd) + end + puts "-- creating README.md" + FileUtils.touch("README.md") + end + + # Verify parameters + def wait() + end + end +end From da329ab19e6f7998744f3809c52947a7eeb81c01 Mon Sep 17 00:00:00 2001 From: Glenn Date: Mon, 27 Mar 2023 16:31:18 +0200 Subject: [PATCH 06/25] feat: Add doc for future GPT content generation --- src/planner/runner.cr | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/planner/runner.cr diff --git a/src/planner/runner.cr b/src/planner/runner.cr new file mode 100644 index 0000000..de395a5 --- /dev/null +++ b/src/planner/runner.cr @@ -0,0 +1,48 @@ + +# Ref. https://platform.openai.com/docs/api-reference/chat + +## -x --expertise XXX +## -a --audience +## -o --objectives + +# System + +# System (common) +# +# Characters +# TEACHER is ... +# AUDITOR is ... +# +# Content Type +# ... +# +# Audience +# ... +# +# Topic +# ... + +# Message (1) : please define main TOC +# +# Request +# Write TOC for a ... +# +# Constraints +# ... +# +# => JSON + +# Message (1) : please define chapter TOC +# +# TOC +# ... +# Request +# Write content structure for chapter ... +# ... +# => JSON + +# Message (2) : please write + + +# [auto] Request +# [auto] From 920c58b1576251eb2d48f50b32886ca9ed86f094 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Sun, 16 Apr 2023 12:02:43 +0200 Subject: [PATCH 07/25] feat: Add multiple binary outputs --- shard.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/shard.yml b/shard.yml index fdfff8b..2619451 100644 --- a/shard.yml +++ b/shard.yml @@ -9,6 +9,15 @@ description: | Command line utils for docmachine targets: + # Validate input(s) & detect errors + docmachine-lint: + main: src/lint/main.cr + docmachine-plan: + main: src/planr/main.cr + # write content based on plan + docmachine-write: + main: src/write/main.cr + # builder docmachine: main: src/main.cr From ae563d781af3faadcb908b04613b860427edcdf1 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Mon, 17 Apr 2023 19:14:08 +0200 Subject: [PATCH 08/25] doc: Add samples formats & prompts & config --- docs/config.md | 38 ++++++++++++++ docs/prompts.md | 91 +++++++++++++++++++++++++++++++++ docs/samples/base.json | 9 ++++ docs/samples/chapter.01.json | 9 ++++ docs/samples/section.01.01.json | 10 ++++ 5 files changed, 157 insertions(+) create mode 100644 docs/config.md create mode 100644 docs/prompts.md create mode 100644 docs/samples/base.json create mode 100644 docs/samples/chapter.01.json create mode 100644 docs/samples/section.01.01.json diff --git a/docs/config.md b/docs/config.md new file mode 100644 index 0000000..41a589e --- /dev/null +++ b/docs/config.md @@ -0,0 +1,38 @@ + +## Usage + +Préparer un fichier `docmachine.yaml`: + + personae: + - TECHY + - GEOPOLY + + context: | + some text here + + audience: | + some text here + + prerequisites: | + some text here + + goals: | + some text here + + pattern: "{{chapter.index}}.{{section.index}}.{{chapter.slug}}.json" + + +Run docmachine to build the main toc + + docmachine plan -c docmachine.yaml --level 0 --output . + + +Run docmachine to build the toc for all chapters + + docmachine plan -c docmachine.yaml --level 1 --output . + + +Run docmachine to build the toc (if missing) + + docmachine plan -c docmachine.yaml --level 0 --output . + diff --git a/docs/prompts.md b/docs/prompts.md new file mode 100644 index 0000000..3de3bc6 --- /dev/null +++ b/docs/prompts.md @@ -0,0 +1,91 @@ + +[TECHY is a technology expert with more than 20 years of experience. TECHY are specialized in systems, networks and infrastructures. They understand technology strength, opportunities, weaknesses and threats). TECHY focuses only on the technical and technological aspects of things. TECHY is methodical and analytical in his answers. TECHY admits his incompetence on other topics. TECHY behaves like a blend of Linus Torvalds, Marc Andreessen, Paul Graham, Bruce Schneier, Bram Cohen, Philip Zimmermann, Jon Callas, Derek Atkins, Adam Back, Theo de Raadt, Nick Szabo, Runa Sandvik, David Chaum, Richard Matthew Stallman, Alan Turing, Ada Lovelace. In all messages, you will start your reply by "TECHY:" and then you will answer to the questions or to the prompt like if TECHY was answering himself.] + +## Contexte + +Une formation d'excellente qualité, faite une université ou une ecole prestigieuse comme l'ENS Ulm, l'école Centrale, l'Ecole polytechnique, le MIT, l'université de Berkeley. + +## Public concerné + +* Administrateurs de bases de données +* Administrateurs de systèmes +* Professionnels des opérations et DevOps +* et toute personne souhaitant maitriser parfaitement MongoDB + +## Prérequis + +* Avoir une connaissance générale des systèmes d'informations, systèmes et réseaux IP. +* Avoir de bonnes connaissance Linux +* Familiarité avec les concepts basiques et intermédiaires de MongoDB +* Plusieurs années d'expérience sur l'outil MongoDB + +## Objectifs + +* Connaître la manipulation et l'interrogation des données à un niveau avancé +* Connaître les bonnes pratiques d'optimisation des performances +* Comprendre l'indexation avancée et les collections spéciales +* Travailler sur la performance et la haute disponibilité avec le sharding et la réplication +* Savoir détecter les causes de sous-performance et y remédier +* Faire face à une montée en charge avec une répartition de charge. +* Créer une stratégie de sauvegarde + +## Programme de la formation + +### Manipulation avancée de données + +* Ajustement du Shell Mongo +* Manipulation efficace des opérations CRUD (insertions, requêtes, mises à jour, suppressions) +* Commandes d'administration utiles + +### Optimisation des performances + +* Outils de supervision intégrés : mongotop, mongostat +* Analyser la mémoire et les performances des E/S +* MongoDB Cloud Manager et Munin +* Identifier les requêtes sous-optimales. Utiliser le profileur de requêtes. +* Moteurs de stockage : MMAPv1 et WiredTiger +* Les Explainable objects + +### Indexation et collections spéciales + +* Gestion et fonctionnement des index +* Index des champs uniques et composés +* Index des tableaux et des sous-documents +* Index géo-spatiaux +* Collections plafonnées, indexs TTL et curseurs + +### Agrégation + +* Agrégation à finalité unique +* Pipelines d'agrégation +* Map-reduce + +### Réplication + +* Réplication asynchrone dans MongoDB +* Mise en place et entretien d'un replica set +* Utilisation de "write concern" et "read preference" +* Gérer les échecs de réplication + +### Sharding + +* Sharding automatique +* Mise en place d'un cluster de shards MongoDB +* Choisir judicieusement une shard key +* Administration avancée d'un cluster de shards +* Gérer un cluster de shards déséquilibré +* Gérer les chunks (scission, fusion, migration) + +### Sécurité + +* Authentification et autorisation dans les replica sets et les clusters de shards +* Gestion des privilèges et des rôles personnalisés +* Recommandations pour un déploiement sûr + +### Plans de sauvegarde et de restauration + +* Stratégies basées sur le système de fichiers +* Utilisation mongodump et mongorestore +* Récupération de type point-in-time + + diff --git a/docs/samples/base.json b/docs/samples/base.json new file mode 100644 index 0000000..8de85c8 --- /dev/null +++ b/docs/samples/base.json @@ -0,0 +1,9 @@ +{ + "type": "main-element", + "title": "" + "chapters": [ + "EXAMPLE CHAPTER TITLE...", + "EXAMPLE CHAPTER TITLE...", + "EXAMPLE CHAPTER TITLE..." + ] +} diff --git a/docs/samples/chapter.01.json b/docs/samples/chapter.01.json new file mode 100644 index 0000000..66b03d6 --- /dev/null +++ b/docs/samples/chapter.01.json @@ -0,0 +1,9 @@ +{ + "type": "chapter", + "title": "" + "sections": [ + "EXAMPLE SECTION TITLE...", + "EXAMPLE SECTION TITLE...", + "EXAMPLE SECTION TITLE..." + ] +} diff --git a/docs/samples/section.01.01.json b/docs/samples/section.01.01.json new file mode 100644 index 0000000..461e419 --- /dev/null +++ b/docs/samples/section.01.01.json @@ -0,0 +1,10 @@ +{ + "type": "section", + "title": "" + "subsections": [ + "EXAMPLE SUBSECTION TITLE...", + "EXAMPLE SUBSECTION TITLE...", + "EXAMPLE SUBSECTION TITLE..." + ] +} + From 3ee2bdf5d46b4cd7b2238852bf666d081e8f2ad5 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Mon, 17 Apr 2023 20:25:24 +0200 Subject: [PATCH 09/25] data: Add prompts for GPT --- data/prompts/chats-sessions.md | 5 ++ data/prompts/prompt-00-main.md | 89 +++++++++++++++++++++++ data/prompts/prompt-01-chapter-loop.md | 18 +++++ data/prompts/prompt-02-section-loop.md | 27 +++++++ data/prompts/prompt-03-subsection-loop.md | 18 +++++ data/prompts/prompt-04-fix-content.md | 7 ++ data/prompts/syllabus.md | 67 +++++++++++++++++ 7 files changed, 231 insertions(+) create mode 100644 data/prompts/chats-sessions.md create mode 100644 data/prompts/prompt-00-main.md create mode 100644 data/prompts/prompt-01-chapter-loop.md create mode 100644 data/prompts/prompt-02-section-loop.md create mode 100644 data/prompts/prompt-03-subsection-loop.md create mode 100644 data/prompts/prompt-04-fix-content.md create mode 100644 data/prompts/syllabus.md diff --git a/data/prompts/chats-sessions.md b/data/prompts/chats-sessions.md new file mode 100644 index 0000000..a15a996 --- /dev/null +++ b/data/prompts/chats-sessions.md @@ -0,0 +1,5 @@ + +# Chat sessions + +* Formation MongoDB + diff --git a/data/prompts/prompt-00-main.md b/data/prompts/prompt-00-main.md new file mode 100644 index 0000000..35a0d55 --- /dev/null +++ b/data/prompts/prompt-00-main.md @@ -0,0 +1,89 @@ +[TECHY is a technology expert with more than 20 years of experience. TECHY are specialized in systems, networks and infrastructures. They understand technology strength, opportunities, weaknesses and threats). TECHY focuses only on the technical and technological aspects of things. TECHY is methodical and analytical in his answers. TECHY admits his incompetence on other topics. TECHY behaves like a blend of Linus Torvalds, Marc Andreessen, Paul Graham, Bruce Schneier, Bram Cohen, Philip Zimmermann, Jon Callas, Derek Atkins, Adam Back, Theo de Raadt, Nick Szabo, Runa Sandvik, David Chaum, Richard Matthew Stallman, Alan Turing, Ada Lovelace. In all messages, you will start your reply by "TECHY:" and then you will answer to the questions or to the prompt like if TECHY was answering himself.] + +## Contexte + +Une formation d'excellente qualité, faite une université ou une ecole prestigieuse comme l'ENS Ulm, l'école Centrale, l'Ecole polytechnique, le MIT, l'université de Berkeley. + +## Public concerné + +* Administrateurs de bases de données +* Administrateurs de systèmes +* Professionnels des opérations et DevOps +* et toute personne souhaitant maitriser parfaitement MongoDB + +## Prérequis + +* Avoir une connaissance générale des systèmes d'informations, systèmes et réseaux IP. +* Avoir de bonnes connaissance Linux +* Familiarité avec les concepts basiques et intermédiaires de MongoDB +* Plusieurs années d'expérience sur l'outil MongoDB + +## Objectifs + +* Connaître la manipulation et l'interrogation des données à un niveau avancé +* Connaître les bonnes pratiques d'optimisation des performances +* Comprendre l'indexation avancée et les collections spéciales +* Travailler sur la performance et la haute disponibilité avec le sharding et la réplication +* Savoir détecter les causes de sous-performance et y remédier +* Faire face à une montée en charge avec une répartition de charge. +* Créer une stratégie de sauvegarde + +## Programme de la formation + +### Manipulation avancée de données + +* Ajustement du Shell Mongo +* Manipulation efficace des opérations CRUD (insertions, requêtes, mises à jour, suppressions) +* Commandes d'administration utiles + +### Optimisation des performances + +* Outils de supervision intégrés : mongotop, mongostat +* Analyser la mémoire et les performances des E/S +* MongoDB Cloud Manager et Munin +* Identifier les requêtes sous-optimales. Utiliser le profileur de requêtes. +* Moteurs de stockage : MMAPv1 et WiredTiger +* Les Explainable objects + +### Indexation et collections spéciales + +* Gestion et fonctionnement des index +* Index des champs uniques et composés +* Index des tableaux et des sous-documents +* Index géo-spatiaux +* Collections plafonnées, indexs TTL et curseurs + +### Agrégation + +* Agrégation à finalité unique +* Pipelines d'agrégation +* Map-reduce + +### Réplication + +* Réplication asynchrone dans MongoDB +* Mise en place et entretien d'un replica set +* Utilisation de "write concern" et "read preference" +* Gérer les échecs de réplication + +### Sharding + +* Sharding automatique +* Mise en place d'un cluster de shards MongoDB +* Choisir judicieusement une shard key +* Administration avancée d'un cluster de shards +* Gérer un cluster de shards déséquilibré +* Gérer les chunks (scission, fusion, migration) + +### Sécurité + +* Authentification et autorisation dans les replica sets et les clusters de shards +* Gestion des privilèges et des rôles personnalisés +* Recommandations pour un déploiement sûr + +### Plans de sauvegarde et de restauration + +* Stratégies basées sur le système de fichiers +* Utilisation mongodump et mongorestore +* Récupération de type point-in-time + diff --git a/data/prompts/prompt-01-chapter-loop.md b/data/prompts/prompt-01-chapter-loop.md new file mode 100644 index 0000000..8699f1f --- /dev/null +++ b/data/prompts/prompt-01-chapter-loop.md @@ -0,0 +1,18 @@ +GOAL: Build sections object containing subsections + +PROMPT: + + Merci. + + Suit la structure du PROGRAMME DE FORMATION. + + Concentre toi sur le chapitre « {{this.title}} ». + + Focalise toi plus spécifiquement sur les sections suivantes « + {% for child in this.children %} + * {{ child }} + {% endfor %} + » de ce chapitre sur lequel on se concentre. + + Rédige la table des matière détaillée de ces différentes sections. + Ajoute également à la fin les différents travaux pratiques possibles pour chaque section. diff --git a/data/prompts/prompt-02-section-loop.md b/data/prompts/prompt-02-section-loop.md new file mode 100644 index 0000000..41304ef --- /dev/null +++ b/data/prompts/prompt-02-section-loop.md @@ -0,0 +1,27 @@ +GOAL: Build subsections object containing markdown + +PROMPT: + + Super. + + Suit la structure du PROGRAMME DE FORMATION. + + Concentre toi sur le chapitre « {{this.chapter.title}} » + + Dans ce chapitre, concentre toi sur la section « {{this.section.title}} ». + + Focalise toi plus spécifiquement sur la sous-sections suivantes « {{this.subsection.title}} » + qui contient les éléments suivants : + « + {% for child in this.children %} + * {{ child }} + {% endfor %} + » sur lequel on se concentre. + + Rédige le contenu détaillée de ces différents sous-sujets, sous forme phrases courtes et de listes à puces (bullet-points) pour remplir le contenu d'une présentation PowerPoint. + + Donne des informations plus précises et plus techniques. + + Précise les mots "gérer" ou "permet" quand tu les utilises. + + Indique où trouver les informations dans MongoDB, dans la CLI ou dans d'autres outils. Donne les commandes à utiliser et des exemples de code si nécessaire. diff --git a/data/prompts/prompt-03-subsection-loop.md b/data/prompts/prompt-03-subsection-loop.md new file mode 100644 index 0000000..23042f2 --- /dev/null +++ b/data/prompts/prompt-03-subsection-loop.md @@ -0,0 +1,18 @@ +GOAL: provide examples and code for given subsection + +PROMPT: + + Super. + Suit la structure du PROGRAMME DE FORMATION. + + Concentre toi sur le chapitre « {{this.chapter.title}} ». Focalise toi plus spécifiquement sur la section suivante « {{this.section}} » et la sous-section « {{this.subsection.title}} » + + Explique les sujets suivants: + « + {% for child in this.children %} + * {{child}} + {% endfor %} + » + + Donne également des exemples: commandes shell, extraits de code, ou extraits de configuration pour illustrer tes explications. + diff --git a/data/prompts/prompt-04-fix-content.md b/data/prompts/prompt-04-fix-content.md new file mode 100644 index 0000000..a48876e --- /dev/null +++ b/data/prompts/prompt-04-fix-content.md @@ -0,0 +1,7 @@ +@@ TEXTE A CORRIGER + +[[FIXME: text]] + +@@ REQUETE + +Dans le TEXTE A CORRIGER, indique où sont les erreurs et les approximations, et propose des corrections pour améliorer le contenu (pour une formation sur OpenStack). diff --git a/data/prompts/syllabus.md b/data/prompts/syllabus.md new file mode 100644 index 0000000..4c6472f --- /dev/null +++ b/data/prompts/syllabus.md @@ -0,0 +1,67 @@ + +## Programme de la formation + +Please use the following syllabus for the 'beging to advanced Openstack administrator course' + +Week 1: Introduction to Openstack + +* Overview of the Openstack platform and its components +* Setting up an Openstack development environment +* Basic Openstack commands and usage + +Week 2: Openstack Compute (Nova) + +* Understanding Nova architecture and components +* Managing virtual machines and instances +* Configuring and managing flavors and images + +Week 3: Openstack Networking (Neutron) + +* Understanding Neutron architecture and components +* Managing virtual networks and subnets +* Configuring security groups and firewall rules + +Week 4: Openstack Storage (Cinder and Swift) + +* Understanding Cinder and Swift architecture and components +* Managing block and object storage +* Creating and managing volumes and snapshots + +Week 5: Openstack Identity (Keystone) + +* Understanding Keystone architecture and components +* Managing users and projects +* Configuring authentication and authorization + +Week 6: Openstack Dashboard (Horizon) + +* Understanding Horizon architecture and components +* Navigating and using the Openstack dashboard +* Customizing and extending the dashboard + +Week 7: Advanced Openstack topics + +* Deploying and managing a production Openstack environment +* Managing and scaling an Openstack cloud +* Troubleshooting and monitoring Openstack +* Openstack in a multi-node environment + +Week 8: Project and Exam + +* Students will be given a project to deploy a multi-node OpenStack cloud, and they will need to complete it +* Written Exam will be held to evaluate the student's understanding of the course content and their ability to apply the knowledge to real-world scenarios + + +## ME + +Please follow the syllabus structure and write the detailed content for "week 1 : introduction to openstack" + +## ME + +Follow the syllabus and the content structure above, and write the detailed course content for "Basic Openstack commands and usage" + +## ME + +Please provide all explanations and commands for the "Configuring and managing flavors and images" part, as the content of multiple slides in markdown, separated by "----": + + From e11d2bc588ddbef09a1e39a69d2eb29343e7f88a Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Tue, 18 Apr 2023 10:49:43 +0200 Subject: [PATCH 10/25] data: Prepare better samples --- data/samples/content.01.01.01.md | 3 +++ data/samples/content.01.01.json | 9 +++++++++ data/samples/content.01.json | 10 ++++++++++ data/samples/content.json | 9 +++++++++ docs/samples/base.json | 9 --------- docs/samples/chapter.01.json | 9 --------- docs/samples/section.01.01.json | 10 ---------- 7 files changed, 31 insertions(+), 28 deletions(-) create mode 100644 data/samples/content.01.01.01.md create mode 100644 data/samples/content.01.01.json create mode 100644 data/samples/content.01.json create mode 100644 data/samples/content.json delete mode 100644 docs/samples/base.json delete mode 100644 docs/samples/chapter.01.json delete mode 100644 docs/samples/section.01.01.json diff --git a/data/samples/content.01.01.01.md b/data/samples/content.01.01.01.md new file mode 100644 index 0000000..6a2348e --- /dev/null +++ b/data/samples/content.01.01.01.md @@ -0,0 +1,3 @@ +## SUBSECTION TITLE + +FIXME diff --git a/data/samples/content.01.01.json b/data/samples/content.01.01.json new file mode 100644 index 0000000..dd78035 --- /dev/null +++ b/data/samples/content.01.01.json @@ -0,0 +1,9 @@ +{ + "type": "section", + "title": "" + "subsections": [ + { "type": "subsection", "title": "...", "keywords": ["...", "..."] }, + { "type": "subsection", "title": "...", "keywords": ["...", "..."] }, + { "type": "subsection", "title": "...", "keywords": ["...", "..."] } + ] +} diff --git a/data/samples/content.01.json b/data/samples/content.01.json new file mode 100644 index 0000000..39fca9c --- /dev/null +++ b/data/samples/content.01.json @@ -0,0 +1,10 @@ +{ + "type": "chapter", + "title": "" + "keywords": ["...", "...", "..."], + "sections": [ + { "type": "section", "title": "...", "keywords": ["...", "..."] }, + { "type": "section", "title": "...", "keywords": ["...", "..."] }, + { "type": "section", "title": "...", "keywords": ["...", "..."] } + ] +} diff --git a/data/samples/content.json b/data/samples/content.json new file mode 100644 index 0000000..ea9c7ab --- /dev/null +++ b/data/samples/content.json @@ -0,0 +1,9 @@ +{ + "type": "root-element", + "title": "" + "chapters": [ + { "type": "chapter", "title": "...", "keywords": ["...", "..."] }, + { "type": "chapter", "title": "...", "keywords": ["...", "..."] }, + { "type": "chapter", "title": "...", "keywords": ["...", "..."] }, + ] +} diff --git a/docs/samples/base.json b/docs/samples/base.json deleted file mode 100644 index 8de85c8..0000000 --- a/docs/samples/base.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "type": "main-element", - "title": "" - "chapters": [ - "EXAMPLE CHAPTER TITLE...", - "EXAMPLE CHAPTER TITLE...", - "EXAMPLE CHAPTER TITLE..." - ] -} diff --git a/docs/samples/chapter.01.json b/docs/samples/chapter.01.json deleted file mode 100644 index 66b03d6..0000000 --- a/docs/samples/chapter.01.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "type": "chapter", - "title": "" - "sections": [ - "EXAMPLE SECTION TITLE...", - "EXAMPLE SECTION TITLE...", - "EXAMPLE SECTION TITLE..." - ] -} diff --git a/docs/samples/section.01.01.json b/docs/samples/section.01.01.json deleted file mode 100644 index 461e419..0000000 --- a/docs/samples/section.01.01.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "type": "section", - "title": "" - "subsections": [ - "EXAMPLE SUBSECTION TITLE...", - "EXAMPLE SUBSECTION TITLE...", - "EXAMPLE SUBSECTION TITLE..." - ] -} - From 594b5f853a4adc644ef8ae5ffa4f680f9c1769a5 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Sun, 23 Apr 2023 15:59:29 +0200 Subject: [PATCH 11/25] refactor: shorten names & use same structure --- src/{builder => build}/cli.cr | 6 +- src/build/config.cr | 11 +++ src/build/run.cr | 122 ++++++++++++++++++++++++ src/builder/config.cr | 13 --- src/builder/run.cr | 125 ------------------------- src/cli.cr | 19 ++-- src/plan/cli.cr | 15 +++ src/{planner => plan}/config.cr | 2 +- src/{planner/runner.cr => plan/run.cr} | 0 src/planner/cli.cr | 17 ---- src/scaffold/cli.cr | 31 ++++++ src/{scaffolder => scaffold}/config.cr | 2 +- src/{scaffolder => scaffold}/run.cr | 4 +- src/{scaffolder => write}/cli.cr | 7 +- src/write/config.cr | 11 +++ src/write/run.cr | 61 ++++++++++++ 16 files changed, 274 insertions(+), 172 deletions(-) rename src/{builder => build}/cli.cr (84%) create mode 100644 src/build/config.cr create mode 100644 src/build/run.cr delete mode 100644 src/builder/config.cr delete mode 100644 src/builder/run.cr create mode 100644 src/plan/cli.cr rename src/{planner => plan}/config.cr (87%) rename src/{planner/runner.cr => plan/run.cr} (100%) delete mode 100644 src/planner/cli.cr create mode 100644 src/scaffold/cli.cr rename src/{scaffolder => scaffold}/config.cr (84%) rename src/{scaffolder => scaffold}/run.cr (93%) rename src/{scaffolder => write}/cli.cr (81%) create mode 100644 src/write/config.cr create mode 100644 src/write/run.cr diff --git a/src/builder/cli.cr b/src/build/cli.cr similarity index 84% rename from src/builder/cli.cr rename to src/build/cli.cr index fcd6d86..8cdb4dc 100644 --- a/src/builder/cli.cr +++ b/src/build/cli.cr @@ -1,12 +1,12 @@ require "./config" -module DocMachine::Builder +module DocMachine::Build class Cli def self.add_options(opts, args, parent_config, commands) config = Config.new(parent_config) - opts.on("build", "Build content and produce deliverables") do + opts.on("build", "Build content and produce HTML & PDF deliverables") do opts.banner = [ "Usage: #{PROGRAM_NAME} build [options]", "", @@ -29,7 +29,7 @@ module DocMachine::Builder end commands << ->() : Nil do - app = DocMachine::Builder::Run.new(config) + app = DocMachine::Build::Run.new(config) app.prepare app.start app.wait diff --git a/src/build/config.cr b/src/build/config.cr new file mode 100644 index 0000000..3c1b2e5 --- /dev/null +++ b/src/build/config.cr @@ -0,0 +1,11 @@ + +module DocMachine::Build + class Config + property data_dir : String = Dir.current + property action : String = "watch" + property enable_tty : Bool = false + + def initialize(@parent : DocMachine::Config) + end + end +end diff --git a/src/build/run.cr b/src/build/run.cr new file mode 100644 index 0000000..a7591a0 --- /dev/null +++ b/src/build/run.cr @@ -0,0 +1,122 @@ + +require "./config" + +module DocMachine::Build + class Run + def initialize(@config : DocMachine::Build::Config) + @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] + @docker_name = "docmachine-#{@basehash}" + @docker_image = "glenux/docmachine:latest" + @docker_opts = [] of String + @process = nil + end + + + # cleanup environment + # create directories + # setup permissions + def prepare() + puts "basedir = #{@config.data_dir}" + puts "docker_image = #{@docker_image}" + puts "action = #{@config.action}" + + docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip + + puts "docker_name: #{@docker_name}" + puts "docker_cid: #{docker_cid}" + + if !docker_cid.empty? + Process.run("docker", ["kill", @docker_name]) + end + end + + def start() + uid = %x{id -u}.strip + gid = %x{id -g}.strip + puts "uid: #{uid}" + puts "cid: #{gid}" + + docker_opts = [] of String + docker_opts << "run" + docker_opts << "-i" + # add tty support + docker_opts << "-t" if @config.enable_tty + # add container name + docker_opts.concat ["--name", @docker_name] + docker_opts << "--rm" + docker_opts << "--shm-size=1gb" + docker_opts.concat ["-e", "EXT_UID=#{uid}"] + docker_opts.concat ["-e", "EXT_GID=#{gid}"] + docker_opts.concat ["-v", "#{@config.data_dir}/docs:/app/docs"] + docker_opts.concat ["-v", "#{@config.data_dir}/slides:/app/slides"] + docker_opts.concat ["-v", "#{@config.data_dir}/images:/app/images"] + docker_opts.concat ["-v", "#{@config.data_dir}/_build:/app/_build"] + + ## Detect Marp SCSS + if File.exists?("#{@config.data_dir}/.marp/theme.scss") + docker_opt_marp_theme = ["-v", "#{@config.data_dir}/.marp:/app/.marp"] + docker_opts.concat docker_opt_marp_theme + puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" + else + puts "Theme: no theme detected. Using default files" + end + + ## Detect Mkdocs configuration - old format (full) + if File.exists?("#{@config.data_dir}/mkdocs.yml") + puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" + exit 1 + end + + ## Detect Mkdocs configuration - new format (patch) + if File.exists?("#{@config.data_dir}/mkdocs-patch.yml") + docker_opt_mkdocs_config = ["-v", "#{@config.data_dir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] + docker_opts.concat docker_opt_mkdocs_config + puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" + else + puts "Mkdocs: no mkdocs-patch.yml detected. Using default files" + end + + ## Detect slides + if Dir.exists?("#{@config.data_dir}/slides") + docker_opt_marp_port = ["-p", "5200:5200"] + docker_opts.concat docker_opt_marp_port + puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" + else + puts "Slides: no slides directory detected." + end + + ## Detect docs + if Dir.exists?("#{@config.data_dir}/docs") + docker_opt_marp_port = ["-p", "5100:5100"] + docker_opts.concat docker_opt_marp_port + puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" + else + puts "Slides: no slides docs detected." + end + + docker_opts << @docker_image + docker_opts << @config.action + + puts docker_opts.inspect.colorize(:yellow) + @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) + end + + def wait() + process = @process + return if process.nil? + + Signal::INT.trap do + STDERR.puts "Received CTRL-C" + process.signal(Signal::KILL) + Process.run("docker", ["kill", @docker_name]) + end + process.wait + end + + def stop() + end + + def docker_opts() + end + end +end diff --git a/src/builder/config.cr b/src/builder/config.cr deleted file mode 100644 index 67787c9..0000000 --- a/src/builder/config.cr +++ /dev/null @@ -1,13 +0,0 @@ - -module DocMachine - module Builder - class Config - property data_dir : String = Dir.current - property action : String = "watch" - property enable_tty : Bool = false - - def initialize(@parent : DocMachine::Config) - end - end - end -end diff --git a/src/builder/run.cr b/src/builder/run.cr deleted file mode 100644 index 1700062..0000000 --- a/src/builder/run.cr +++ /dev/null @@ -1,125 +0,0 @@ - -require "./config" - -module DocMachine - module Builder - - class Run - def initialize(@config : DocMachine::Builder::Config) - @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] - @docker_name = "docmachine-#{@basehash}" - @docker_image = "glenux/docmachine:latest" - @docker_opts = [] of String - @process = nil - end - - - # cleanup environment - # create directories - # setup permissions - def prepare() - puts "basedir = #{@config.data_dir}" - puts "docker_image = #{@docker_image}" - puts "action = #{@config.action}" - - docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip - - puts "docker_name: #{@docker_name}" - puts "docker_cid: #{docker_cid}" - - if !docker_cid.empty? - Process.run("docker", ["kill", @docker_name]) - end - end - - def start() - uid = %x{id -u}.strip - gid = %x{id -g}.strip - puts "uid: #{uid}" - puts "cid: #{gid}" - - docker_opts = [] of String - docker_opts << "run" - docker_opts << "-i" - # add tty support - docker_opts << "-t" if @config.enable_tty - # add container name - docker_opts.concat ["--name", @docker_name] - docker_opts << "--rm" - docker_opts << "--shm-size=1gb" - docker_opts.concat ["-e", "EXT_UID=#{uid}"] - docker_opts.concat ["-e", "EXT_GID=#{gid}"] - docker_opts.concat ["-v", "#{@config.data_dir}/docs:/app/docs"] - docker_opts.concat ["-v", "#{@config.data_dir}/slides:/app/slides"] - docker_opts.concat ["-v", "#{@config.data_dir}/images:/app/images"] - docker_opts.concat ["-v", "#{@config.data_dir}/_build:/app/_build"] - - ## Detect Marp SCSS - if File.exists?("#{@config.data_dir}/.marp/theme.scss") - docker_opt_marp_theme = ["-v", "#{@config.data_dir}/.marp:/app/.marp"] - docker_opts.concat docker_opt_marp_theme - puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" - else - puts "Theme: no theme detected. Using default files" - end - - ## Detect Mkdocs configuration - old format (full) - if File.exists?("#{@config.data_dir}/mkdocs.yml") - puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" - exit 1 - end - - ## Detect Mkdocs configuration - new format (patch) - if File.exists?("#{@config.data_dir}/mkdocs-patch.yml") - docker_opt_mkdocs_config = ["-v", "#{@config.data_dir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] - docker_opts.concat docker_opt_mkdocs_config - puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" - else - puts "Mkdocs: no mkdocs-patch.yml detected. Using default files" - end - - ## Detect slides - if Dir.exists?("#{@config.data_dir}/slides") - docker_opt_marp_port = ["-p", "5200:5200"] - docker_opts.concat docker_opt_marp_port - puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" - else - puts "Slides: no slides directory detected." - end - - ## Detect docs - if Dir.exists?("#{@config.data_dir}/docs") - docker_opt_marp_port = ["-p", "5100:5100"] - docker_opts.concat docker_opt_marp_port - puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" - else - puts "Slides: no slides docs detected." - end - - docker_opts << @docker_image - docker_opts << @config.action - - puts docker_opts.inspect.colorize(:yellow) - @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) - end - - def wait() - process = @process - return if process.nil? - - Signal::INT.trap do - STDERR.puts "Received CTRL-C" - process.signal(Signal::KILL) - Process.run("docker", ["kill", @docker_name]) - end - process.wait - end - - def stop() - end - - def docker_opts() - end - end - end -end diff --git a/src/cli.cr b/src/cli.cr index d6627de..36bfed7 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -3,10 +3,14 @@ require "digest/sha256" require "colorize" require "./config" -require "./builder/cli" -require "./builder/run" -require "./scaffolder/cli" -require "./planner/cli" +require "./build/cli" +require "./build/run" +require "./scaffold/cli" +require "./scaffold/run" +require "./plan/cli" +require "./plan/run" +require "./write/cli" +require "./write/run" module DocMachine class Cli @@ -36,9 +40,10 @@ module DocMachine opts.separator "" opts.separator "Commands:" - DocMachine::Builder::Cli.add_options(opts, args, config, commands) - DocMachine::Scaffolder::Cli.add_options(opts, args, config, commands) - DocMachine::Planner::Cli.add_options(opts, args, config, commands) + DocMachine::Scaffold::Cli.add_options(opts, args, config, commands) + DocMachine::Plan::Cli.add_options(opts, args, config, commands) + DocMachine::Write::Cli.add_options(opts, args, config, commands) + DocMachine::Build::Cli.add_options(opts, args, config, commands) end parser.parse(args) diff --git a/src/plan/cli.cr b/src/plan/cli.cr new file mode 100644 index 0000000..5becba0 --- /dev/null +++ b/src/plan/cli.cr @@ -0,0 +1,15 @@ + +require "./config" + +module DocMachine::Plan + class Cli + def self.add_options(opts, args, parent_config, command) + config = Config.new(parent_config) + + opts.on("plan", "Generate content structure (beta)") do + opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" + opts.on("-t", "--test", "Test") { puts "Test" } + end + end + end +end diff --git a/src/planner/config.cr b/src/plan/config.cr similarity index 87% rename from src/planner/config.cr rename to src/plan/config.cr index 6444962..181d274 100644 --- a/src/planner/config.cr +++ b/src/plan/config.cr @@ -1,6 +1,6 @@ module DocMachine - module Planner + module Plan class Config def initialize(@parent : DocMachine::Config) end diff --git a/src/planner/runner.cr b/src/plan/run.cr similarity index 100% rename from src/planner/runner.cr rename to src/plan/run.cr diff --git a/src/planner/cli.cr b/src/planner/cli.cr deleted file mode 100644 index c82b47b..0000000 --- a/src/planner/cli.cr +++ /dev/null @@ -1,17 +0,0 @@ - -require "./config" - -module DocMachine - module Planner - class Cli - def self.add_options(opts, args, parent_config, command) - config = Config.new(parent_config) - - opts.on("content", "Generate content and structure") do - opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" - opts.on("-t", "--test", "Test") { puts "Test" } - end - end - end - end -end diff --git a/src/scaffold/cli.cr b/src/scaffold/cli.cr new file mode 100644 index 0000000..4e67740 --- /dev/null +++ b/src/scaffold/cli.cr @@ -0,0 +1,31 @@ +require "./config" +require "./run" + +module DocMachine::Scaffold + class Cli + def self.add_options(opts, args, parent_config, commands) + config = Config.new(parent_config) + + opts.on("scaffold", "Scaffold target directory (beta)") do + opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options] TARGET" + + opts.on("-f", "--force", "Don't ask for confirmation") do + config.force = true + end + + commands << ->() : Nil do + if args.size < 1 + STDERR.puts "ERROR: No target given!" + exit 1 + end + config.target_directory = args[0] + + app = DocMachine::Scaffold::Run.new(config) + app.prepare + app.start + app.wait + end + end + end + end +end diff --git a/src/scaffolder/config.cr b/src/scaffold/config.cr similarity index 84% rename from src/scaffolder/config.cr rename to src/scaffold/config.cr index 4b4bb63..4d5db07 100644 --- a/src/scaffolder/config.cr +++ b/src/scaffold/config.cr @@ -1,6 +1,6 @@ -module DocMachine::Scaffolder +module DocMachine::Scaffold class Config property target_directory : String = "." property force : Bool = false diff --git a/src/scaffolder/run.cr b/src/scaffold/run.cr similarity index 93% rename from src/scaffolder/run.cr rename to src/scaffold/run.cr index c3dafa7..8de36e0 100644 --- a/src/scaffolder/run.cr +++ b/src/scaffold/run.cr @@ -8,9 +8,9 @@ require "./config" # Shards require "term-prompt" -module DocMachine::Scaffolder +module DocMachine::Scaffold class Run - private property config : DocMachine::Scaffolder::Config + private property config : DocMachine::Scaffold::Config def initialize(@config) end diff --git a/src/scaffolder/cli.cr b/src/write/cli.cr similarity index 81% rename from src/scaffolder/cli.cr rename to src/write/cli.cr index b803f6b..49cd3b2 100644 --- a/src/scaffolder/cli.cr +++ b/src/write/cli.cr @@ -1,12 +1,12 @@ require "./config" require "./run" -module DocMachine::Scaffolder +module DocMachine::Write class Cli def self.add_options(opts, args, parent_config, commands) config = Config.new(parent_config) - opts.on("scaffold", "Scaffold target directory") do + opts.on("write", "Write content target for plan (beta)") do opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options] TARGET" opts.on("-f", "--force", "Don't ask for confirmation") do @@ -20,7 +20,7 @@ module DocMachine::Scaffolder end config.target_directory = args[0] - app = DocMachine::Scaffolder::Run.new(config) + app = DocMachine::Write::Run.new(config) app.prepare app.start app.wait @@ -29,3 +29,4 @@ module DocMachine::Scaffolder end end end + diff --git a/src/write/config.cr b/src/write/config.cr new file mode 100644 index 0000000..132f6ef --- /dev/null +++ b/src/write/config.cr @@ -0,0 +1,11 @@ + + +module DocMachine::Write + class Config + property target_directory : String = "." + property force : Bool = false + + def initialize(@parent : DocMachine::Config) + end + end +end diff --git a/src/write/run.cr b/src/write/run.cr new file mode 100644 index 0000000..f84e3d4 --- /dev/null +++ b/src/write/run.cr @@ -0,0 +1,61 @@ + +# Core +require "file_utils" + +# Internal +require "./config" + +# Shards +require "term-prompt" + +module DocMachine::Write + class Run + private property config : DocMachine::Write::Config + + def initialize(@config) + end + + # Verify parameters + def prepare() + if ! File.directory? @config.target_directory + STDERR.puts "ERROR: target must be a directory" + exit 1 + end + + puts "Target directory: #{@config.target_directory}" + + if !@config.force + prompt = Term::Prompt.new + confirm = prompt.no?("Are you sure you want to proceed?") + exit 1 if !confirm + end + end + + def start() + puts "== Writeing #{@config.target_directory}" + p = Path.new(@config.target_directory) + cwd = Dir.current + ["docs", "slides", "images"].each do |dir| + p_sub = p.join(dir) + puts "-- creating #{p_sub}" + FileUtils.mkdir_p(p_sub) + end + ["docs", "slides"].each do |dir| + p_sub = p.join(dir) + FileUtils.cd(p_sub) + puts "-- creating link to images in #{p_sub}" + if File.symlink? "images" + FileUtils.rm "images" + end + FileUtils.ln_sf(Path.new("..","images"), Path.new("images")) + FileUtils.cd(cwd) + end + puts "-- creating README.md" + FileUtils.touch("README.md") + end + + # Verify parameters + def wait() + end + end +end From adc96653e5d2253e21557d8ab5f181fa62b7a4d7 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Mon, 24 Apr 2023 10:31:54 +0200 Subject: [PATCH 12/25] feat: Add dependency for crinja --- shard.lock | 8 ++++---- shard.yml | 21 +++------------------ 2 files changed, 7 insertions(+), 22 deletions(-) diff --git a/shard.lock b/shard.lock index 6e040c8..4de6f9f 100644 --- a/shard.lock +++ b/shard.lock @@ -1,13 +1,13 @@ version: 2.0 shards: - completion: - git: https://github.com/f/completion.git - version: 0.1.0+git.commit.d8799381b2de14430496199260eca64eb329625f - cor: git: https://github.com/watzon/cor.git version: 0.1.0+git.commit.9c9e51ac6168f3bd4fdc51d679b65de09ef76cac + crinja: + git: https://github.com/straight-shoota/crinja.git + version: 0.8.1 + ioctl: git: https://github.com/crystal-posix/ioctl.cr.git version: 1.0.0 diff --git a/shard.yml b/shard.yml index 2619451..e5550d1 100644 --- a/shard.yml +++ b/shard.yml @@ -9,30 +9,15 @@ description: | Command line utils for docmachine targets: - # Validate input(s) & detect errors - docmachine-lint: - main: src/lint/main.cr - docmachine-plan: - main: src/planr/main.cr - # write content based on plan - docmachine-write: - main: src/write/main.cr - # builder docmachine: main: src/main.cr dependencies: term-prompt: github: crystal-term/prompt + crinja: + github: straight-shoota/crinja -# completion: -# github: f/completion -# pg: -# github: will/crystal-pg -# version: "~> 0.5" - -# development_dependencies: -# webmock: -# github: manastech/webmock.cr +# FIXME: for prompts rendering license: MIT From a921acc3f9d55ba649bd4de7d1128558b575184d Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Mon, 24 Apr 2023 18:43:04 +0200 Subject: [PATCH 13/25] ci: add missing libreadline-dev --- .drone.yml | 2 +- src/build/run.cr | 33 +++++++++++++++++++++++++++++++++ src/cli.cr | 17 ++++++++--------- src/common/docker.cr | 14 ++++++++++++++ src/config.cr | 3 +++ src/main.cr | 1 + src/write/cli.cr | 6 +++++- src/write/config.cr | 2 ++ 8 files changed, 67 insertions(+), 11 deletions(-) create mode 100644 src/common/docker.cr diff --git a/.drone.yml b/.drone.yml index 087a097..db1e400 100644 --- a/.drone.yml +++ b/.drone.yml @@ -11,7 +11,7 @@ steps: path: /_cache commands: - pwd - - apt-get update && apt-get install -y cmake g++ + - apt-get update && apt-get install -y cmake g++ libreadline-dev - shards install - shards build --production --static - strip bin/docmachine diff --git a/src/build/run.cr b/src/build/run.cr index a7591a0..a2951c2 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -1,8 +1,13 @@ +require "path" +require "file_utils" + require "./config" module DocMachine::Build class Run + Log = DB::Log.for("docmachine.build") # Log for db.pool source + def initialize(@config : DocMachine::Build::Config) @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] @docker_name = "docmachine-#{@basehash}" @@ -20,6 +25,11 @@ module DocMachine::Build puts "docker_image = #{@docker_image}" puts "action = #{@config.action}" + self._avoid_duplicates() + self._pull_image() + end + + private def _avoid_duplicates docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip puts "docker_name: #{@docker_name}" @@ -30,6 +40,29 @@ module DocMachine::Build end end + def _pull_image + data_cache_dir = ( + if ENV["XDG_CACHE_HOME"]? + Path[ENV["XDG_CACHE_HOME"], "docmachine"] + else + Path[ENV["HOME"], ".cache", "docmachine"] + end + ) + + data_cache_file = data_cache_dir / "image.tar" + puts "Checking cache #{data_cache_file}..." + if ! File.exists? data_cache_file.to_s + puts "Downloading #{@docker_image} image..." + Process.run("docker", ["pull", @docker_image], output: STDOUT) + puts "Building cache for image (#{data_cache_dir})" + FileUtils.mkdir_p(data_cache_dir) + Process.run("docker", ["save", @docker_image, "-o", data_cache_file.to_s], output: STDOUT) + puts "done" + else + puts "Cache already exist. Skipping." + end + end + def start() uid = %x{id -u}.strip gid = %x{id -g}.strip diff --git a/src/cli.cr b/src/cli.cr index 36bfed7..584a64c 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -47,17 +47,16 @@ module DocMachine end parser.parse(args) - puts commands + Log.info { "commands = #{commands}" } - if commands.size > 0 - commands.each do |command| - # puts "== Running #{command}" - command.call() - end - else + if commands.size < 1 puts parser.to_s - STDOUT.puts "" - STDERR.puts "ERROR: no command defined" + Log.error { "ERROR: no command defined" } + end + + commands.each do |command| + # puts "== Running #{command}" + command.call() end end end diff --git a/src/common/docker.cr b/src/common/docker.cr new file mode 100644 index 0000000..f49d699 --- /dev/null +++ b/src/common/docker.cr @@ -0,0 +1,14 @@ + +class Docker + property image : String + + def initialize(@image) + end + + + def store_image + end + + def image_load + end +end diff --git a/src/config.cr b/src/config.cr index 3de0e98..084ef21 100644 --- a/src/config.cr +++ b/src/config.cr @@ -1,5 +1,8 @@ + module DocMachine + Log = ::Log.for("doc_machine") + class Config property verbose : Bool = false diff --git a/src/main.cr b/src/main.cr index c426b18..9bc515b 100644 --- a/src/main.cr +++ b/src/main.cr @@ -1,6 +1,7 @@ require "./cli" +Log.setup(:debug) app = DocMachine::Cli.new app.start(ARGV) diff --git a/src/write/cli.cr b/src/write/cli.cr index 49cd3b2..d6bc1d7 100644 --- a/src/write/cli.cr +++ b/src/write/cli.cr @@ -2,7 +2,11 @@ require "./config" require "./run" module DocMachine::Write + Log = DocMachine::Log.for("write") + class Cli + Log = DocMachine::Write::Log.for("cli") + def self.add_options(opts, args, parent_config, commands) config = Config.new(parent_config) @@ -15,7 +19,7 @@ module DocMachine::Write commands << ->() : Nil do if args.size < 1 - STDERR.puts "ERROR: No target given!" + Log.error { "ERROR: No target given!" } exit 1 end config.target_directory = args[0] diff --git a/src/write/config.cr b/src/write/config.cr index 132f6ef..9adc918 100644 --- a/src/write/config.cr +++ b/src/write/config.cr @@ -2,6 +2,8 @@ module DocMachine::Write class Config + Log = DocMachine::Write.for("config") + property target_directory : String = "." property force : Bool = false From 3f985f27514f7c046d0461d082e7d2411a726687 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Tue, 25 Apr 2023 12:28:16 +0200 Subject: [PATCH 14/25] feat: use Log library instead of puts --- Makefile | 1 - src/build/module.cr | 7 ++++ src/build/run.cr | 75 ++++++++++++++++++++++++------------------ src/cli.cr | 8 ++--- src/config.cr | 4 +-- src/main.cr | 5 ++- src/module.cr | 6 ++++ src/plan/cli.cr | 4 ++- src/scaffold/cli.cr | 2 +- src/scaffold/module.cr | 0 src/scaffold/run.cr | 12 +++---- src/write/run.cr | 12 +++---- 12 files changed, 82 insertions(+), 54 deletions(-) create mode 100644 src/build/module.cr create mode 100644 src/module.cr create mode 100644 src/scaffold/module.cr diff --git a/Makefile b/Makefile index a54ec15..3ea87f8 100644 --- a/Makefile +++ b/Makefile @@ -4,4 +4,3 @@ all: build build: shards build --error-trace - read A diff --git a/src/build/module.cr b/src/build/module.cr new file mode 100644 index 0000000..98b0d6e --- /dev/null +++ b/src/build/module.cr @@ -0,0 +1,7 @@ + +require "../module" +require "log" + +module DocMachine::Build + Log = DocMachine::Log.for("docmachine") +end diff --git a/src/build/run.cr b/src/build/run.cr index a2951c2..cc83f95 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -2,11 +2,12 @@ require "path" require "file_utils" +require "./module" require "./config" module DocMachine::Build class Run - Log = DB::Log.for("docmachine.build") # Log for db.pool source + Log = DocMachine::Build::Log.for("run") def initialize(@config : DocMachine::Build::Config) @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] @@ -21,9 +22,9 @@ module DocMachine::Build # create directories # setup permissions def prepare() - puts "basedir = #{@config.data_dir}" - puts "docker_image = #{@docker_image}" - puts "action = #{@config.action}" + Log.info { "basedir = #{@config.data_dir}" } + Log.info { "docker_image = #{@docker_image}" } + Log.info { "action = #{@config.action}" } self._avoid_duplicates() self._pull_image() @@ -32,8 +33,8 @@ module DocMachine::Build private def _avoid_duplicates docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip - puts "docker_name: #{@docker_name}" - puts "docker_cid: #{docker_cid}" + Log.info { "docker_name: #{@docker_name}" } + Log.info { "docker_cid: #{docker_cid}" } if !docker_cid.empty? Process.run("docker", ["kill", @docker_name]) @@ -41,33 +42,43 @@ module DocMachine::Build end def _pull_image - data_cache_dir = ( - if ENV["XDG_CACHE_HOME"]? - Path[ENV["XDG_CACHE_HOME"], "docmachine"] - else - Path[ENV["HOME"], ".cache", "docmachine"] - end - ) + # FIXME: add option to force update + data_cache_dir = if ENV["XDG_CACHE_HOME"]? + Path[ENV["XDG_CACHE_HOME"], "docmachine"] + else Path[ENV["HOME"], ".cache", "docmachine"] + end data_cache_file = data_cache_dir / "image.tar" - puts "Checking cache #{data_cache_file}..." + Log.info { "Checking cache #{data_cache_file}..." } if ! File.exists? data_cache_file.to_s - puts "Downloading #{@docker_image} image..." + Log.info { "Downloading #{@docker_image} image..." } Process.run("docker", ["pull", @docker_image], output: STDOUT) - puts "Building cache for image (#{data_cache_dir})" + Log.info { "Building cache for image (#{data_cache_dir})" } FileUtils.mkdir_p(data_cache_dir) - Process.run("docker", ["save", @docker_image, "-o", data_cache_file.to_s], output: STDOUT) - puts "done" + Process.run( + "docker", + ["image", "save", @docker_image, "-o", data_cache_file.to_s], + output: STDOUT + ) + Log.info { "done" } else - puts "Cache already exist. Skipping." + Log.info { "Cache already exist. Skipping." } end + + Log.info { "Loading #{@docker_image} image from cache..." } + docker_image_loaded = false + Process.run( + "docker", + ["image", "load", @docker_image, "-i", data_cache_file.to_s], + output: STDOUT + ) end def start() uid = %x{id -u}.strip gid = %x{id -g}.strip - puts "uid: #{uid}" - puts "cid: #{gid}" + Log.info { "uid: #{uid}" } + Log.info { "cid: #{gid}" } docker_opts = [] of String docker_opts << "run" @@ -89,14 +100,14 @@ module DocMachine::Build if File.exists?("#{@config.data_dir}/.marp/theme.scss") docker_opt_marp_theme = ["-v", "#{@config.data_dir}/.marp:/app/.marp"] docker_opts.concat docker_opt_marp_theme - puts "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" + Log.info { "Theme: detected Marp files. Adding option to command line (#{docker_opt_marp_theme})" } else - puts "Theme: no theme detected. Using default files" + Log.info { "Theme: no theme detected. Using default files" } end ## Detect Mkdocs configuration - old format (full) if File.exists?("#{@config.data_dir}/mkdocs.yml") - puts "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" + Log.info { "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" } exit 1 end @@ -104,33 +115,33 @@ module DocMachine::Build if File.exists?("#{@config.data_dir}/mkdocs-patch.yml") docker_opt_mkdocs_config = ["-v", "#{@config.data_dir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] docker_opts.concat docker_opt_mkdocs_config - puts "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" + Log.info { "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" } else - puts "Mkdocs: no mkdocs-patch.yml detected. Using default files" + Log.info { "Mkdocs: no mkdocs-patch.yml detected. Using default files" } end ## Detect slides if Dir.exists?("#{@config.data_dir}/slides") docker_opt_marp_port = ["-p", "5200:5200"] docker_opts.concat docker_opt_marp_port - puts "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" + Log.info { "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" } else - puts "Slides: no slides directory detected." + Log.info { "Slides: no slides directory detected." } end ## Detect docs if Dir.exists?("#{@config.data_dir}/docs") docker_opt_marp_port = ["-p", "5100:5100"] docker_opts.concat docker_opt_marp_port - puts "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" + Log.info { "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" } else - puts "Slides: no slides docs detected." + Log.info { "Slides: no slides docs detected." } end docker_opts << @docker_image docker_opts << @config.action - puts docker_opts.inspect.colorize(:yellow) + Log.info { docker_opts.inspect.colorize(:yellow) } @process = Process.new("docker", docker_opts, output: STDOUT, error: STDERR) end @@ -139,7 +150,7 @@ module DocMachine::Build return if process.nil? Signal::INT.trap do - STDERR.puts "Received CTRL-C" + Log.warn { "Received CTRL-C" } process.signal(Signal::KILL) Process.run("docker", ["kill", @docker_name]) end diff --git a/src/cli.cr b/src/cli.cr index 584a64c..2d9557d 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -33,7 +33,7 @@ module DocMachine end opts.on("-h", "--help", "Show this help") do - puts opts + Log.info { opts } exit end @@ -47,15 +47,15 @@ module DocMachine end parser.parse(args) - Log.info { "commands = #{commands}" } + Log.debug { "commands = #{commands}" } if commands.size < 1 - puts parser.to_s + Log.error { parser.to_s } Log.error { "ERROR: no command defined" } end commands.each do |command| - # puts "== Running #{command}" + # Log.info { "== Running #{command}" } command.call() end end diff --git a/src/config.cr b/src/config.cr index 084ef21..a2f90f4 100644 --- a/src/config.cr +++ b/src/config.cr @@ -1,8 +1,8 @@ +require "./module" + module DocMachine - Log = ::Log.for("doc_machine") - class Config property verbose : Bool = false diff --git a/src/main.cr b/src/main.cr index 9bc515b..715054a 100644 --- a/src/main.cr +++ b/src/main.cr @@ -1,7 +1,10 @@ require "./cli" -Log.setup(:debug) +Log.define_formatter BaseFormat, "#{message}" + + +::Log.setup(:notice, Log::IOBackend.new(formatter: BaseFormat)) app = DocMachine::Cli.new app.start(ARGV) diff --git a/src/module.cr b/src/module.cr new file mode 100644 index 0000000..bdcbc06 --- /dev/null +++ b/src/module.cr @@ -0,0 +1,6 @@ + +require "log" + +module DocMachine + Log = ::Log.for("docmachine") +end diff --git a/src/plan/cli.cr b/src/plan/cli.cr index 5becba0..aa72ee9 100644 --- a/src/plan/cli.cr +++ b/src/plan/cli.cr @@ -8,7 +8,9 @@ module DocMachine::Plan opts.on("plan", "Generate content structure (beta)") do opts.banner = "Usage: #{PROGRAM_NAME} plan [options]" - opts.on("-t", "--test", "Test") { puts "Test" } + opts.on("-t", "--test", "Test") do + Log.info { "Test" } + end end end end diff --git a/src/scaffold/cli.cr b/src/scaffold/cli.cr index 4e67740..c20822a 100644 --- a/src/scaffold/cli.cr +++ b/src/scaffold/cli.cr @@ -15,7 +15,7 @@ module DocMachine::Scaffold commands << ->() : Nil do if args.size < 1 - STDERR.puts "ERROR: No target given!" + Log.error { "ERROR: No target given!" } exit 1 end config.target_directory = args[0] diff --git a/src/scaffold/module.cr b/src/scaffold/module.cr new file mode 100644 index 0000000..e69de29 diff --git a/src/scaffold/run.cr b/src/scaffold/run.cr index 8de36e0..480294a 100644 --- a/src/scaffold/run.cr +++ b/src/scaffold/run.cr @@ -18,11 +18,11 @@ module DocMachine::Scaffold # Verify parameters def prepare() if ! File.directory? @config.target_directory - STDERR.puts "ERROR: target must be a directory" + Log.error { "ERROR: target must be a directory" } exit 1 end - puts "Target directory: #{@config.target_directory}" + Log.info { "Target directory: #{@config.target_directory}" } if !@config.force prompt = Term::Prompt.new @@ -32,25 +32,25 @@ module DocMachine::Scaffold end def start() - puts "== Scaffolding #{@config.target_directory}" + Log.info { "== Scaffolding #{@config.target_directory}" } p = Path.new(@config.target_directory) cwd = Dir.current ["docs", "slides", "images"].each do |dir| p_sub = p.join(dir) - puts "-- creating #{p_sub}" + Log.info { "-- creating #{p_sub}" } FileUtils.mkdir_p(p_sub) end ["docs", "slides"].each do |dir| p_sub = p.join(dir) FileUtils.cd(p_sub) - puts "-- creating link to images in #{p_sub}" + Log.info { "-- creating link to images in #{p_sub}" } if File.symlink? "images" FileUtils.rm "images" end FileUtils.ln_sf(Path.new("..","images"), Path.new("images")) FileUtils.cd(cwd) end - puts "-- creating README.md" + Log.info { "-- creating README.md" } FileUtils.touch("README.md") end diff --git a/src/write/run.cr b/src/write/run.cr index f84e3d4..571e337 100644 --- a/src/write/run.cr +++ b/src/write/run.cr @@ -18,11 +18,11 @@ module DocMachine::Write # Verify parameters def prepare() if ! File.directory? @config.target_directory - STDERR.puts "ERROR: target must be a directory" + Log.error { "ERROR: target must be a directory" } exit 1 end - puts "Target directory: #{@config.target_directory}" + Log.info { "Target directory: #{@config.target_directory}" } if !@config.force prompt = Term::Prompt.new @@ -32,25 +32,25 @@ module DocMachine::Write end def start() - puts "== Writeing #{@config.target_directory}" + Log.info { "== Writeing #{@config.target_directory}" } p = Path.new(@config.target_directory) cwd = Dir.current ["docs", "slides", "images"].each do |dir| p_sub = p.join(dir) - puts "-- creating #{p_sub}" + Log.info { "-- creating #{p_sub}" } FileUtils.mkdir_p(p_sub) end ["docs", "slides"].each do |dir| p_sub = p.join(dir) FileUtils.cd(p_sub) - puts "-- creating link to images in #{p_sub}" + Log.info { "-- creating link to images in #{p_sub}" } if File.symlink? "images" FileUtils.rm "images" end FileUtils.ln_sf(Path.new("..","images"), Path.new("images")) FileUtils.cd(cwd) end - puts "-- creating README.md" + Log.info { "-- creating README.md" } FileUtils.touch("README.md") end From 8ae9599d0fa5fc36592018098811d0c3c6748818 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 27 Apr 2023 09:50:11 +0200 Subject: [PATCH 15/25] fix(build): make image load work --- src/build/run.cr | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/build/run.cr b/src/build/run.cr index cc83f95..0d1c5d0 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -55,23 +55,35 @@ module DocMachine::Build Process.run("docker", ["pull", @docker_image], output: STDOUT) Log.info { "Building cache for image (#{data_cache_dir})" } FileUtils.mkdir_p(data_cache_dir) - Process.run( + status = Process.run( "docker", ["image", "save", @docker_image, "-o", data_cache_file.to_s], output: STDOUT ) - Log.info { "done" } + if status.success? + Log.info { "done" } + else + Log.error { "Unable to save cache image" } + exit 1 + end + else Log.info { "Cache already exist. Skipping." } end Log.info { "Loading #{@docker_image} image from cache..." } docker_image_loaded = false - Process.run( + status = Process.run( "docker", - ["image", "load", @docker_image, "-i", data_cache_file.to_s], + ["image", "load", "-i", data_cache_file.to_s], output: STDOUT ) + if status.success? + Log.info { "done" } + else + Log.error { "Unable to load cache image" } + exit 1 + end end def start() From 0832e4c8777a65050e51cde8d5d29d7fd182e1ed Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 27 Apr 2023 09:42:15 +0200 Subject: [PATCH 16/25] refactor: Clean up the logging system --- src/cli.cr | 21 ++++++++++++++++----- src/config.cr | 2 +- src/log.cr | 38 ++++++++++++++++++++++++++++++++++++++ src/main.cr | 5 ++--- src/write/cli.cr | 11 ++++++++--- src/write/module.cr | 6 ++++++ src/write/nodes/module.cr | 6 ++++++ src/write/run.cr | 2 +- 8 files changed, 78 insertions(+), 13 deletions(-) create mode 100644 src/log.cr create mode 100644 src/write/module.cr create mode 100644 src/write/nodes/module.cr diff --git a/src/cli.cr b/src/cli.cr index 2d9557d..d8219ba 100644 --- a/src/cli.cr +++ b/src/cli.cr @@ -2,6 +2,7 @@ require "option_parser" require "digest/sha256" require "colorize" +require "./log" require "./config" require "./build/cli" require "./build/run" @@ -14,6 +15,8 @@ require "./write/run" module DocMachine class Cli + Log = DocMachine::Log.for("cli") + def initialize end @@ -28,12 +31,18 @@ module DocMachine "Main options:" ].join("\n") - opts.on("-v", "--verbose", "Enable verbosity") do |verbose| - config.verbose = true + opts.on("-v", "--verbosity LEVEL", "Change verbosity level to LEVEL (0..3)") do |verbose| + verbose_i = verbose.to_i + verbose_i = 0 if verbose.to_i < 0 + verbose_i = 3 if verbose.to_i > 3 + config.verbosity = ::Log::Severity.from_value(3 - verbose_i) + rescue ex: ArgumentError + Log.error { "Wrong value for parameter --verbosity" } + exit 1 end opts.on("-h", "--help", "Show this help") do - Log.info { opts } + Log.notice { opts } exit end @@ -47,15 +56,17 @@ module DocMachine end parser.parse(args) + ::Log.setup(config.verbosity, ::Log::IOBackend.new(formatter: BaseFormat)) + Log.notice { "verbosity level = #{config.verbosity}" } Log.debug { "commands = #{commands}" } if commands.size < 1 Log.error { parser.to_s } - Log.error { "ERROR: no command defined" } + Log.error { "No command defined" } end commands.each do |command| - # Log.info { "== Running #{command}" } + Log.debug { "== Running #{command}" } command.call() end end diff --git a/src/config.cr b/src/config.cr index a2f90f4..01485f1 100644 --- a/src/config.cr +++ b/src/config.cr @@ -5,7 +5,7 @@ require "./module" module DocMachine class Config - property verbose : Bool = false + property verbosity = ::Log::Severity::Notice def initialize end diff --git a/src/log.cr b/src/log.cr new file mode 100644 index 0000000..0b8bc1b --- /dev/null +++ b/src/log.cr @@ -0,0 +1,38 @@ + +require "log" +require "colorize" + +struct DebugFormat < Log::StaticFormatter + def run + string @entry.severity.label[0].downcase + string ": " + source + string ": " + message + end + end + +struct BaseFormat < Log::StaticFormatter + def run + io = ::IO::Memory.new + + color = case @entry.severity + when ::Log::Severity::Error + Colorize.colorize.red.bold + when ::Log::Severity::Warn + Colorize.colorize.red.yellow + when ::Log::Severity::Notice + Colorize.colorize.bold + else + Colorize.colorize + end + + color.surround(io) do + io << @entry.message + end + + string io.to_s + end + end + +# Log.define_formatter BaseFormat, "#{severity.to_s.lstrip}(#{source}): #{message}" diff --git a/src/main.cr b/src/main.cr index 715054a..6f8ba11 100644 --- a/src/main.cr +++ b/src/main.cr @@ -1,10 +1,9 @@ require "./cli" - -Log.define_formatter BaseFormat, "#{message}" - +require "./log" ::Log.setup(:notice, Log::IOBackend.new(formatter: BaseFormat)) +::Log.progname = "(root)" app = DocMachine::Cli.new app.start(ARGV) diff --git a/src/write/cli.cr b/src/write/cli.cr index d6bc1d7..c7b378f 100644 --- a/src/write/cli.cr +++ b/src/write/cli.cr @@ -1,9 +1,9 @@ + require "./config" require "./run" +require "./module" module DocMachine::Write - Log = DocMachine::Log.for("write") - class Cli Log = DocMachine::Write::Log.for("cli") @@ -18,15 +18,20 @@ module DocMachine::Write end commands << ->() : Nil do + Log.debug { "before any" } if args.size < 1 - Log.error { "ERROR: No target given!" } + Log.error { "No target given!" } exit 1 end config.target_directory = args[0] + Log.debug { "before new" } app = DocMachine::Write::Run.new(config) + Log.debug { "before prepare" } app.prepare + Log.debug { "before start" } app.start + Log.debug { "before wait" } app.wait end end diff --git a/src/write/module.cr b/src/write/module.cr new file mode 100644 index 0000000..ea6ae71 --- /dev/null +++ b/src/write/module.cr @@ -0,0 +1,6 @@ + +require "../module" + +module DocMachine::Write + Log = DocMachine::Log.for("write") +end diff --git a/src/write/nodes/module.cr b/src/write/nodes/module.cr new file mode 100644 index 0000000..40f614a --- /dev/null +++ b/src/write/nodes/module.cr @@ -0,0 +1,6 @@ + +require "../module" + +module DocMachine::Write::Nodes + Log = DocMachine::Write::Log.for("nodes") +end diff --git a/src/write/run.cr b/src/write/run.cr index 571e337..0c2afd5 100644 --- a/src/write/run.cr +++ b/src/write/run.cr @@ -18,7 +18,7 @@ module DocMachine::Write # Verify parameters def prepare() if ! File.directory? @config.target_directory - Log.error { "ERROR: target must be a directory" } + Log.error { "Target must be a directory" } exit 1 end From 5689929c83efebb183516d2e7265ac214dfb75a0 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 27 Apr 2023 09:51:17 +0200 Subject: [PATCH 17/25] feat(write): Add basic support for prompts management --- data/prompts/01-each-chapter--build-toc.tpl | 24 +++ data/prompts/prompt-01-chapter-loop.md | 18 -- shard.lock | 4 + shard.yml | 3 + src/write/file_storage.cr | 7 + src/write/run.cr | 172 +++++++++++++++++--- 6 files changed, 183 insertions(+), 45 deletions(-) create mode 100644 data/prompts/01-each-chapter--build-toc.tpl delete mode 100644 data/prompts/prompt-01-chapter-loop.md create mode 100644 src/write/file_storage.cr diff --git a/data/prompts/01-each-chapter--build-toc.tpl b/data/prompts/01-each-chapter--build-toc.tpl new file mode 100644 index 0000000..d547a9f --- /dev/null +++ b/data/prompts/01-each-chapter--build-toc.tpl @@ -0,0 +1,24 @@ +{# GOAL: Build sections object containing subsections #} + +Merci. + +Suit la structure du PROGRAMME DE FORMATION. + +Concentre toi sur le chapitre « {{chapter.title}} ». + +Commence par écrire "boundary: {{ delimiter }}". +Ensuite rédige la table des matière détaillée de ce chapitre en respectant la structure suivante: + +« +{ + "type": "section", + "title": "" + "subsections": [ + { "type": "subsection", "title": "...", "keywords": ["...", "..."] }, + { "type": "subsection", "title": "...", "keywords": ["...", "..."] }, + { "type": "subsection", "title": "...", "keywords": ["...", "..."] } + ] +} +» + +Termine en écrivant "boundary: {{ delimiter }}". diff --git a/data/prompts/prompt-01-chapter-loop.md b/data/prompts/prompt-01-chapter-loop.md deleted file mode 100644 index 8699f1f..0000000 --- a/data/prompts/prompt-01-chapter-loop.md +++ /dev/null @@ -1,18 +0,0 @@ -GOAL: Build sections object containing subsections - -PROMPT: - - Merci. - - Suit la structure du PROGRAMME DE FORMATION. - - Concentre toi sur le chapitre « {{this.title}} ». - - Focalise toi plus spécifiquement sur les sections suivantes « - {% for child in this.children %} - * {{ child }} - {% endfor %} - » de ce chapitre sur lequel on se concentre. - - Rédige la table des matière détaillée de ces différentes sections. - Ajoute également à la fin les différents travaux pratiques possibles pour chaque section. diff --git a/shard.lock b/shard.lock index 4de6f9f..c2f4a12 100644 --- a/shard.lock +++ b/shard.lock @@ -1,5 +1,9 @@ version: 2.0 shards: + baked_file_system: + git: https://github.com/schovi/baked_file_system.git + version: 0.10.0 + cor: git: https://github.com/watzon/cor.git version: 0.1.0+git.commit.9c9e51ac6168f3bd4fdc51d679b65de09ef76cac diff --git a/shard.yml b/shard.yml index e5550d1..48d65e1 100644 --- a/shard.yml +++ b/shard.yml @@ -17,6 +17,9 @@ dependencies: github: crystal-term/prompt crinja: github: straight-shoota/crinja + baked_file_system: + github: schovi/baked_file_system + version: 0.10.0 # FIXME: for prompts rendering diff --git a/src/write/file_storage.cr b/src/write/file_storage.cr new file mode 100644 index 0000000..90ddb40 --- /dev/null +++ b/src/write/file_storage.cr @@ -0,0 +1,7 @@ +require "baked_file_system" + +class FileStorage + extend BakedFileSystem + + bake_folder "../../data/prompts" +end diff --git a/src/write/run.cr b/src/write/run.cr index 0c2afd5..815a7b0 100644 --- a/src/write/run.cr +++ b/src/write/run.cr @@ -1,60 +1,178 @@ # Core require "file_utils" +require "path" # Internal require "./config" +require "./nodes/root_node" # Shards require "term-prompt" +require "crinja" module DocMachine::Write class Run private property config : DocMachine::Write::Config + property root = Nodes::RootNode.new def initialize(@config) end - # Verify parameters - def prepare() + def validate_build_dir() if ! File.directory? @config.target_directory Log.error { "Target must be a directory" } exit 1 end Log.info { "Target directory: #{@config.target_directory}" } - - if !@config.force - prompt = Term::Prompt.new - confirm = prompt.no?("Are you sure you want to proceed?") - exit 1 if !confirm - end end - def start() - Log.info { "== Writeing #{@config.target_directory}" } - p = Path.new(@config.target_directory) - cwd = Dir.current - ["docs", "slides", "images"].each do |dir| - p_sub = p.join(dir) - Log.info { "-- creating #{p_sub}" } - FileUtils.mkdir_p(p_sub) + def ask_confirmation + # if !@config.force + # prompt = Term::Prompt.new + # confirm = prompt.no?("Are you sure you want to proceed?") + # exit 1 if !confirm + # end + end + + def load_templates + pp @config + + context_file = Path[@config.target_directory] / "CONTEXT.tpl" + if ! File.exists? context_file + raise "Context file #{context_file} is missing" end - ["docs", "slides"].each do |dir| - p_sub = p.join(dir) - FileUtils.cd(p_sub) - Log.info { "-- creating link to images in #{p_sub}" } - if File.symlink? "images" - FileUtils.rm "images" - end - FileUtils.ln_sf(Path.new("..","images"), Path.new("images")) - FileUtils.cd(cwd) + @root.context = File.read(context_file) + + audience_file = Path[@config.target_directory] / "AUDIENCE.tpl" + if ! File.exists? audience_file + raise "Audience file #{audience_file} is missing" end - Log.info { "-- creating README.md" } - FileUtils.touch("README.md") + @root.audience = File.read(audience_file) + + goals_file = Path[@config.target_directory] / "GOALS.tpl" + if ! File.exists? goals_file + raise "Audience file #{goals_file} is missing" + end + @root.goals = File.read(goals_file) + + constraints_file = Path[@config.target_directory] / "CONSTRAINTS.tpl" + if ! File.exists? constraints_file + raise "Audience file #{constraints_file} is missing" + end + @root.constraints = File.read(constraints_file) end # Verify parameters + def prepare() + validate_build_dir() + ask_confirmation() + load_templates() + Log.debug { "done" } + end + + ## + ## ContentNode + ## type: ... + ## title: ... + ## keywords: ... + ## content: ... + ## + + def start() + @root.chapters = root.build_chapters() + + @root.chapters.each do |chapter| + chapter.sections = chapter.build_sections() + + chapter.sections.each do |section| + section.subsections = section.build_subsections() + # FIXME(later): section.exercises = section.build_exercises() + + section.subsections.each do |subsection| + subsection.content = subsection.build_content() + subsection.content = subsection.fix_content() + # FIXME(later): subsection.exercises = subsection.build_exercises() + end + end + end + end + + + ## Level 0 - each topic : build TOC (chapter list) + def from_topic_build_chapters + chapter_build_toc_template = FileStorage.get("./../data/prompts/01-each-chapter--build-toc.tpl") + chapters = [{ "title": "Terraform on Azure" }] + + end + + + ## Level 1 - each chapter : build TOC (section list) + # 1. build chat + # - (system) quality & style guidance + # - (user) context + # - (user) audience + # - (user) objectives + # - (user) main toc (chapters) + def from_chapter_build_sections() + delimiter = "34e127df" # FIXME: random 8 bytes hex string + chapters.each do |chapter| + template_vars = { + delimiter: delimiter, + chapter: chapter + } + render = Crinja.render(chapter_build_toc_template, template_vars) + puts render + end + end + + ## Level 2 - each section : build TOC (subsection list) + # 1. build chat + # - (system) quality & style guidance + # - (user) context + # - (user) audience + # - (user) objectives + # - (user) main toc (chapters) + # - (user) chapter toc (sections) + # 2. make openai request + # 3. validate result structure + # 4. create section objects in memory + def from_section_build_subsections() + section_build_toc_tpl = File.read(DOCMACHINE_DATA_PATH / "prompts" / "02-each-section--build-toc.tpl") + end + + + ## Level 2 - each section : build EXERCISES + # 1. build chat + # - (system) quality & style guidance + # - (user) context + # - (user) audience + # - (user) objectives + # - (user) main toc (chapters) + # - (user) chapter toc (sections) + # 2. make openai request + # 3. validate result structure + # 4. create exercises objects in memory + def from_section_build_exercises() + section_build_toc_tpl = File.read(DOCMACHINE_DATA_PATH / "prompts" / "02-each-section--build-exercises.tpl") + end + + def from_subsection_build_content() + ## Level 3 - each subsection : build CONTENT + section_build_toc_tpl = File.read(DOCMACHINE_DATA_PATH / "prompts" / "02-each-subsection--build-content.tpl") + end + + def from_subsection_fix_content() + ## Level 4 - each subsection : build FIXED CONTENT + section_build_toc_tpl = File.read(DOCMACHINE_DATA_PATH / "prompts" / "02-each-subsection--fix-content.tpl") + end + + def from_subsection_build_exercises() + ## Level 1 - each subsection EXERCICES + section_build_toc_tpl = File.read(DOCMACHINE_DATA_PATH / "prompts" / "02-each-subsection--build-exercises.tpl") + end + def wait() end end From 615c377623cabffa927b6d0e8fc6becfa1b1f770 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 27 Apr 2023 10:02:35 +0200 Subject: [PATCH 18/25] feat(write): Add support for templates --- src/write/cli.cr | 6 +++++- src/write/config.cr | 1 + 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/write/cli.cr b/src/write/cli.cr index c7b378f..a14fa5c 100644 --- a/src/write/cli.cr +++ b/src/write/cli.cr @@ -11,12 +11,16 @@ module DocMachine::Write config = Config.new(parent_config) opts.on("write", "Write content target for plan (beta)") do - opts.banner = "Usage: #{PROGRAM_NAME} scaffold [options] TARGET" + opts.banner = "Usage: #{PROGRAM_NAME} write [options] TARGET" opts.on("-f", "--force", "Don't ask for confirmation") do config.force = true end + opts.on("-t", "--template TEMPLATE", "Use given template") do |template_name| + config.template_name = template_name + end + commands << ->() : Nil do Log.debug { "before any" } if args.size < 1 diff --git a/src/write/config.cr b/src/write/config.cr index 9adc918..cb38f72 100644 --- a/src/write/config.cr +++ b/src/write/config.cr @@ -6,6 +6,7 @@ module DocMachine::Write property target_directory : String = "." property force : Bool = false + property template_name : String = "" def initialize(@parent : DocMachine::Config) end From a2272230e2b82070f4e0571c62a45958ae788f62 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 27 Apr 2023 20:48:19 +0200 Subject: [PATCH 19/25] feat(write): Add content nodes support --- src/write/nodes/root_node.cr | 46 ++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/write/nodes/root_node.cr diff --git a/src/write/nodes/root_node.cr b/src/write/nodes/root_node.cr new file mode 100644 index 0000000..a0fb162 --- /dev/null +++ b/src/write/nodes/root_node.cr @@ -0,0 +1,46 @@ + +require "./module" + +module DocMachine::Write::Nodes + class RootNode + property context : String = "" + property audience : String = "" + property goals : String = "" + property constraints : String = "" + property chapters = [] of ChapterNode + + def build_chapters() + [] of ChapterNode + end + end + + class ChapterNode + property sections = [] of SectionNode + + def build_sections() + [] of SectionNode + end + end + + class SectionNode + property subsections = [] of SubsectionNode + + def build_subsections() + [] of SubsectionNode + end + end + + class SubsectionNode + property content = [] of String + + def build_content() + [] of String + end + + def fix_content() + [] of String + end + end +end + + From 81b845fc669472a3a50db760e08b4d298f177e34 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Wed, 14 Feb 2024 14:29:41 +0100 Subject: [PATCH 20/25] feat: add support for port selection Add support for base port selection - add --port PORT and -p PORT options on command line - add naive (not implemented) support for port detection - docs container is now mapped to PORT - slides container is now mapped to PORT+100 --- src/build/cli.cr | 8 ++++++-- src/build/config.cr | 1 + src/build/run.cr | 49 ++++++++++++++++++++++++++++++--------------- 3 files changed, 40 insertions(+), 18 deletions(-) diff --git a/src/build/cli.cr b/src/build/cli.cr index 8cdb4dc..b957f60 100644 --- a/src/build/cli.cr +++ b/src/build/cli.cr @@ -16,12 +16,16 @@ module DocMachine::Build opts.separator "" opts.separator "Builder Options:" + opts.on("-a", "--action ACTION", "Action (watch, build, shell, etc.)") do |action| + config.action = action + end + opts.on("-d", "--data-dir DIR", "Content directory") do |dir| config.data_dir = dir end - opts.on("-a", "--action ACTION", "Action (watch, build, shell, etc.)") do |action| - config.action = action + opts.on("-p", "--port PORT", "Set base port to PORT") do |port| + config.port = port.to_i end opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do diff --git a/src/build/config.cr b/src/build/config.cr index 3c1b2e5..8129259 100644 --- a/src/build/config.cr +++ b/src/build/config.cr @@ -4,6 +4,7 @@ module DocMachine::Build property data_dir : String = Dir.current property action : String = "watch" property enable_tty : Bool = false + property port : Int32 = 5100 def initialize(@parent : DocMachine::Config) end diff --git a/src/build/run.cr b/src/build/run.cr index 0d1c5d0..af91688 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -30,6 +30,17 @@ module DocMachine::Build self._pull_image() end + private def _find_port(port_base) + (port_base..65535).each do |port| + return port if _port_available?(port) + end + raise "No port available" + end + + private def _port_available?(port) + true + end + private def _avoid_duplicates docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip @@ -119,7 +130,7 @@ module DocMachine::Build ## Detect Mkdocs configuration - old format (full) if File.exists?("#{@config.data_dir}/mkdocs.yml") - Log.info { "Mkdocs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" } + Log.info { "Docs: detected mkdocs.yml file. Please rename to mkdocs-patch.yml" } exit 1 end @@ -127,27 +138,33 @@ module DocMachine::Build if File.exists?("#{@config.data_dir}/mkdocs-patch.yml") docker_opt_mkdocs_config = ["-v", "#{@config.data_dir}/mkdocs-patch.yml:/app/mkdocs-patch.yml"] docker_opts.concat docker_opt_mkdocs_config - Log.info { "Mkdocs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" } + Log.info { "Docs: detected mkdocs-patch.yml file. Adding option to command line (#{docker_opt_mkdocs_config})" } else - Log.info { "Mkdocs: no mkdocs-patch.yml detected. Using default files" } - end - - ## Detect slides - if Dir.exists?("#{@config.data_dir}/slides") - docker_opt_marp_port = ["-p", "5200:5200"] - docker_opts.concat docker_opt_marp_port - Log.info { "Slides: detected slides directory. Adding option to command line (#{docker_opt_marp_port})" } - else - Log.info { "Slides: no slides directory detected." } + Log.info { "Docs: no mkdocs-patch.yml detected. Using default files" } end ## Detect docs if Dir.exists?("#{@config.data_dir}/docs") - docker_opt_marp_port = ["-p", "5100:5100"] - docker_opts.concat docker_opt_marp_port - Log.info { "Slides: detected docs directory. Adding option to command line (#{docker_opt_marp_port})" } + Log.info { "Docs: detected docs directory." } + mkdocs_port = _find_port(@config.port) + docker_opt_mkdocs_port = ["-p", "#{mkdocs_port}:5100"] + docker_opts.concat docker_opt_mkdocs_port + Log.notice { "Using port #{mkdocs_port} for docs" } + Log.info { "Docs: Adding option to command line (#{docker_opt_marp_port})" } else - Log.info { "Slides: no slides docs detected." } + Log.info { "Docs: no docs detected." } + end + + ## Detect slides + if Dir.exists?("#{@config.data_dir}/slides") + Log.info { "Slides: detected slides directory." } + marp_port = _find_port(@config.port+100) + docker_opt_marp_port = ["-p", "#{marp_port}:5200"] + docker_opts.concat docker_opt_marp_port + Log.info { "Slides: Adding option to command line (#{docker_opt_marp_port})" } + Log.notice { "Slides: Using port #{marp_port} for slides" } + else + Log.info { "Slides: no slides directory detected." } end docker_opts << @docker_image From b588503b7986ef74daf34074143144df68a56f62 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Wed, 14 Feb 2024 14:34:29 +0100 Subject: [PATCH 21/25] fix: use the right variable for mkdocs port options --- src/build/run.cr | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/build/run.cr b/src/build/run.cr index af91688..0bbf523 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -150,7 +150,7 @@ module DocMachine::Build docker_opt_mkdocs_port = ["-p", "#{mkdocs_port}:5100"] docker_opts.concat docker_opt_mkdocs_port Log.notice { "Using port #{mkdocs_port} for docs" } - Log.info { "Docs: Adding option to command line (#{docker_opt_marp_port})" } + Log.info { "Docs: Adding option to command line (#{docker_opt_mkdocs_port})" } else Log.info { "Docs: no docs detected." } end From a007211e293d2316ad543b456457b7ac2703f59a Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Wed, 14 Feb 2024 14:51:15 +0100 Subject: [PATCH 22/25] feat: add support for port detection --- src/build/run.cr | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/build/run.cr b/src/build/run.cr index 0bbf523..f95591c 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -1,6 +1,7 @@ require "path" require "file_utils" +require "socket" require "./module" require "./config" @@ -38,7 +39,12 @@ module DocMachine::Build end private def _port_available?(port) - true + sock = Socket.new(Socket::Family::INET, Socket::Type::STREAM) + sock.bind(Socket::IPAddress.new("0.0.0.0", port)) + sock.close + return true + rescue ex : Socket::BindError + return false end private def _avoid_duplicates From 9d13f8216f7417679205d74bdc841cd430ea47da Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Wed, 14 Feb 2024 15:29:36 +0100 Subject: [PATCH 23/25] feat: add option for multiple instances --- src/build/cli.cr | 4 ++++ src/build/config.cr | 1 + src/build/run.cr | 11 +++++++---- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/build/cli.cr b/src/build/cli.cr index b957f60..b625c41 100644 --- a/src/build/cli.cr +++ b/src/build/cli.cr @@ -28,6 +28,10 @@ module DocMachine::Build config.port = port.to_i end + opts.on("-m", "--multiple", "Allow multiple instances per dir" ) do |port| + config.multiple_instances = true + end + opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do config.enable_tty = true end diff --git a/src/build/config.cr b/src/build/config.cr index 8129259..5831af6 100644 --- a/src/build/config.cr +++ b/src/build/config.cr @@ -5,6 +5,7 @@ module DocMachine::Build property action : String = "watch" property enable_tty : Bool = false property port : Int32 = 5100 + property multiple_instances : Bool = false def initialize(@parent : DocMachine::Config) end diff --git a/src/build/run.cr b/src/build/run.cr index f95591c..67549df 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -11,7 +11,8 @@ module DocMachine::Build Log = DocMachine::Build::Log.for("run") def initialize(@config : DocMachine::Build::Config) - @basehash = Digest::SHA256.hexdigest(@config.data_dir)[0..6] + data = "#{@config.data_dir}:#{@config.port}" + @basehash = Digest::SHA256.hexdigest(data)[0..6] @docker_name = "docmachine-#{@basehash}" @docker_image = "glenux/docmachine:latest" @docker_opts = [] of String @@ -27,8 +28,8 @@ module DocMachine::Build Log.info { "docker_image = #{@docker_image}" } Log.info { "action = #{@config.action}" } - self._avoid_duplicates() self._pull_image() + self._avoid_duplicates() unless @config.multiple_instances end private def _find_port(port_base) @@ -48,13 +49,15 @@ module DocMachine::Build end private def _avoid_duplicates + Log.info { "Multiple Instances: stopping duplicate containers (for #{@docker_name})" } docker_cid = %x{docker ps -f "name=#{@docker_name}" -q}.strip - Log.info { "docker_name: #{@docker_name}" } - Log.info { "docker_cid: #{docker_cid}" } + Log.info { "Multiple Instances: docker_name: #{@docker_name}" } + Log.info { "Multiple Instances: docker_cid: #{docker_cid || "-"}" } if !docker_cid.empty? Process.run("docker", ["kill", @docker_name]) + Process.run("docker", ["rm", @docker_name]) end end From 1e63606f723741eda4e43cd727b7a0f4d6b4b03c Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 15 Feb 2024 18:56:15 +0100 Subject: [PATCH 24/25] feat: Add support for --no-cache option --- src/build/cli.cr | 6 +++++- src/build/config.cr | 3 ++- src/build/run.cr | 30 ++++++++++++++++++------------ 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/build/cli.cr b/src/build/cli.cr index b625c41..968db9c 100644 --- a/src/build/cli.cr +++ b/src/build/cli.cr @@ -20,6 +20,10 @@ module DocMachine::Build config.action = action end + opts.on("--no-cache", "Disable cache") do |_| + config.enable_cache = false + end + opts.on("-d", "--data-dir DIR", "Content directory") do |dir| config.data_dir = dir end @@ -29,7 +33,7 @@ module DocMachine::Build end opts.on("-m", "--multiple", "Allow multiple instances per dir" ) do |port| - config.multiple_instances = true + config.enable_multiple = true end opts.on("-t", "--tty", "Enable TTY mode (needed for shell)") do diff --git a/src/build/config.cr b/src/build/config.cr index 5831af6..ec33c4d 100644 --- a/src/build/config.cr +++ b/src/build/config.cr @@ -5,7 +5,8 @@ module DocMachine::Build property action : String = "watch" property enable_tty : Bool = false property port : Int32 = 5100 - property multiple_instances : Bool = false + property enable_multiple : Bool = false + property enable_cache : Bool = false def initialize(@parent : DocMachine::Config) end diff --git a/src/build/run.cr b/src/build/run.cr index 67549df..a7cee4f 100644 --- a/src/build/run.cr +++ b/src/build/run.cr @@ -29,7 +29,7 @@ module DocMachine::Build Log.info { "action = #{@config.action}" } self._pull_image() - self._avoid_duplicates() unless @config.multiple_instances + self._avoid_duplicates() unless @config.enable_multiple end private def _find_port(port_base) @@ -68,6 +68,7 @@ module DocMachine::Build else Path[ENV["HOME"], ".cache", "docmachine"] end + ## Build cache if it doesnt exist data_cache_file = data_cache_dir / "image.tar" Log.info { "Checking cache #{data_cache_file}..." } if ! File.exists? data_cache_file.to_s @@ -91,18 +92,23 @@ module DocMachine::Build Log.info { "Cache already exist. Skipping." } end - Log.info { "Loading #{@docker_image} image from cache..." } - docker_image_loaded = false - status = Process.run( - "docker", - ["image", "load", "-i", data_cache_file.to_s], - output: STDOUT - ) - if status.success? - Log.info { "done" } + if @config.enable_cache + Log.info { "Loading #{@docker_image} image from cache..." } + docker_image_loaded = false + status = Process.run( + "docker", + ["image", "load", "-i", data_cache_file.to_s], + output: STDOUT + ) + if status.success? + Log.info { "done" } + else + Log.error { "Unable to load cache image" } + exit 1 + end else - Log.error { "Unable to load cache image" } - exit 1 + Log.info { "Loading #{@docker_image} image from local registry..." } + # FIXME: check that local image exists end end From e6a6da7a78b1be106d69db8e519594910ea72988 Mon Sep 17 00:00:00 2001 From: "Glenn Y. Rolland" Date: Thu, 15 Feb 2024 18:56:31 +0100 Subject: [PATCH 25/25] feat: add more targets to makefile (ex: install) --- Makefile | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 3ea87f8..2fe15e3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,37 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +# +# SPDX-FileCopyrightText: 2023 Glenn Y. Rolland +# Copyright © 2023 Glenn Y. Rolland + +CURRENT_UID := $(shell id -u) +CURRENT_GID := $(shell id -g) +ifeq ($(CURRENT_UID),0) +PREFIX=/usr +else +PREFIX=$(HOME)/.local +endif all: build +prepare: + shards install + build: - shards build --error-trace + shards build --error-trace -Dpreview_mt + @echo SUCCESS + +watch: + watchexec --restart --delay-run 3 -c -e cr make build + +spec: test +test: + crystal spec --error-trace + +install: + install \ + -m 755 \ + bin/docmachine \ + $(PREFIX)/bin + +.PHONY: spec test build all prepare install