Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Last active March 12, 2018 10:19
Show Gist options
  • Save kou1okada/4144114c7454bfdfbe9b65cc5695beb9 to your computer and use it in GitHub Desktop.
Save kou1okada/4144114c7454bfdfbe9b65cc5695beb9 to your computer and use it in GitHub Desktop.
moodlexmlutil.rb - Utility for xml file of moodle backup.
#!/bin/sh
exec ruby -x "$0" "$@"
#!ruby
# coding: utf-8
require "optparse"
require "logger"
require "hpricot"
$conf = {
:verbose => Logger::WARN,
:list => false,
:extract => {},
}
opts = OptionParser.new
opts.banner = <<EOD
#{File.basename $0} - Utility for xml file of moodle backup.
Copyright (c) 2018 Koichi OKADA. All rights reserves.
This script is distributed under the MIT license.
Usage:
#{File.basename $0} [options] files ...
Options:
EOD
opts.on("-h", "--help") {|v| $conf[:help] = v}
opts.on("-q", "--quiet") {|v| $conf[:verbose] = Logger::ERROR}
opts.on("-v", "--verbose") {|v| $conf[:verbose] = Logger::INFO}
opts.on("-l", "--list") {|v| $conf[:list] = v}
opts.on("-x", "--extract=ID[,FILENAME]") {|v| $conf[:extract][$1] = $3 if /([^,]+)(,(.*))?/.match(v);}
opts.on("-f", "--force") {|v| $conf[:force] = v;}
opts.parse! ARGV
if $conf[:help] || ARGV.length <= 0
puts opts.help
exit
end
verb_label = {
"FATAL" => "\e[35;1mFatal:\e[0m",
"ERROR" => "\e[31;1mError:\e[0m",
"WARN" => "\e[33;1mWarning:\e[0m",
"INFO" => "\e[32;1mInfo:\e[0m",
"DEBUG" => "\e[34;1mDebug:\e[0m",
}
verb = Logger.new(STDERR)
verb.level = $conf[:verbose]
verb.formatter = proc do |severity, datetime, progname, msg|
"#{verb_label[severity]} #{msg}\n"
end
ARGV.each do |fn|
doc = Hpricot.parse(open(fn).read)
(doc/"mod").each do |mod|
puts "%s,\t%s,\t%s,\t%s,\n" % [(mod/"> id").text, (mod/"> modtype").text, (mod/"> name").text, (mod/"> type").text] if $conf[:list]
if $conf[:extract].key?((mod/"id").text)
fn = $conf[:extract][(mod/"id").text]
fn = "%s.%s" % [(mod/"id").text, (mod/"> type").text] if fn.nil?
if File.exist?(fn)
if $conf[:force]
verb.warn "Overwrite a file already exists: '#{fn}'"
else
verb.warn "Skip extract because file already exists: '#{fn}'"
next
end
end
verb.info "extract: '#{fn}'"
open(fn, "w").write (mod/"alltext").text
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment