~rbn/tlog

ref: ed85dd3f3cc9a42fdbddea0205d24eaef57c35ee tlog/tlog.tcl -rwxr-xr-x 2.2 KiB
ed85dd3fRuben Schuller add main script detection, wrap procs in namespace 10 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#!/usr/bin/env tclsh
package require cmdline
package require Markdown

namespace eval tlog {
	proc verbatim { in } {
		return $in
	}

	proc markdown { in } {
		##nagelfar ignore Unknown command
		return [ ::Markdown::convert $in ]
	}

	proc tcl { in } {
		upvar 1 context context
		return [ eval $in ]
	}

	proc extensions { converters } {
		return [ dict keys $converters ]
	}

	proc page { template contents } {
		##nagelfar ignore Found constant
		return [ dict create template $template contents $contents ]
	}

	proc content_files { dir converters } {
		# find all files with registered processors
		set globs "*{[join [ extensions $converters ] , ]}"
		foreach name [ glob -directory $dir $globs ] {
			lappend files $name
		}
		return $files
	}

	proc contents { files converters } {
		set context [ dict create ]
		foreach { path } $files {
			set f [ open $path r ]
			set converter [ dict get $converters [ file extension $path ] ]
			set name [ file rootname [ lindex [ file split $path ] end ] ]
			if { [ dict exists $context $name ] } {
				error "duplicate content with name: $name"
			}
			dict set context $name [ $converter [ read $f ] ]
			close $f
		}

		return $context
	}

	proc insert { name } {
		upvar 1 $name _name
		return $_name 
	}

	proc execute { template { contextvar context } } {
		upvar 1 $contextvar context
		dict with context {}
		return [ subst $template ]
	}
}

# check if we are sourced or running as main script
if {[info exists argv0] && [file dirname [file normalize [file join [info script] ...]]] eq [file dirname [file normalize [file join $argv0 ...]]] } {
	set options {
		    { t.arg "templates/main.html"	"template file" }
	}

	set usage {[options] [content_dir content_dir ...]}

	try {
		set opts [ ::cmdline::getoptions argv $options $usage ]
	} trap { CMDLINE USAGE } { msg o } {
		puts $msg
		exit 0
	}

	set template_file [ dict get $opts t ]

	set converters [ dict create .html verbatim .md markdown .tcl tcl ]

	set f [ open $template_file r ]
	set template [ read $f ]
	close $f

	set contents {}
	foreach {dir} $argv {
		lappend contents {*}[ ::tlog::content_files $dir $converters ]
	}

	set context [ ::tlog::contents $contents $converters ]
	puts [ ::tlog::execute $template ]
}