gopher2html.awk - gopher2html - AWK script that converts a Gopher response to HTML
HTML hg clone https://bitbucket.org/iamleot/gopher2html
DIR Log
DIR Files
DIR Refs
DIR README
---
gopher2html.awk
---
1 #!/usr/bin/awk -f
2
3 function urlize(type, selector, host, port)
4 {
5
6 return encode("gopher://" host ":" port "/" type selector)
7 }
8
9 function encode(html)
10 {
11
12 gsub(/&/, "\\&", html)
13 gsub(/</, "\\<", html)
14 gsub(/>/, "\\>", html)
15 gsub(/"/, "\\"", html)
16 gsub(/'/, "\\'", html)
17
18 return html
19 }
20
21 function header()
22 {
23 if (ENVIRON["GOPHER2HTML_TYPE"] != "file") {
24 # Print the header
25 print "<html>"
26 print "<body>"
27 print "<pre>"
28 }
29 }
30
31 function footer()
32 {
33 if (ENVIRON["GOPHER2HTML_TYPE"] != "file") {
34 # Print the footer
35 print "</pre>"
36 print "</body>"
37 print "</html>"
38 }
39 }
40
41 BEGIN {
42 FS = "\t"
43 # XXX: Strictly speaking RS should be `\r\n'. However, in the wild it
44 # XXX: can happens that the `\r' is missing. Address that and then strip
45 # XXX: trailing `\r' when parsing responses.
46 RS = "\n"
47
48 TYPE["file"] = "0"
49 TYPE["directory"] = "1"
50 TYPE["error"] = "3"
51 TYPE["search"] = "7"
52 TYPE["image"] = "I"
53 TYPE["gif"] = "g"
54 TYPE["html"] = "h"
55 TYPE["info"] = "i"
56 TYPE["picture"] = "p"
57 TYPE["sound"] = "s"
58
59 header()
60 }
61
62 {
63 sub(/^\r/, "")
64 sub(/\r$/, "")
65
66 type = substr($1, 1, 1)
67 user_name = substr($1, 2)
68 selector = $2
69 host = $3
70 port = $4
71 }
72
73 $0 == "." {
74 # (nothing)
75 next
76 }
77
78 # Text entry
79 ENVIRON["GOPHER2HTML_TYPE"] == "file" {
80 printf("%s\n", $0)
81 next
82 }
83
84 type == TYPE["file"] || type == TYPE["directory"] {
85 printf("<a href=\"%s\">%s</a>\n", urlize(type, selector, host, port), encode(user_name))
86 }
87
88 type == TYPE["error"] {
89 # TODO
90 }
91
92 type == TYPE["search"] {
93 printf("<form action=\"%s\">", urlize(type, selector, host, port))
94 printf("<input type='text' />")
95 printf("<input type='submit' />")
96 printf("</form>\n")
97 }
98
99 type == TYPE["info"] {
100 printf("%s\n", encode(user_name))
101 }
102
103 type == TYPE["html"] {
104 url = substr(selector, 5) # strip `URL:' prefix
105 printf("<a href=\"%s\">%s</a>\n", encode(url), encode(user_name))
106 }
107
108 type == TYPE["image"] || type == TYPE["gif"] || type == TYPE["picture"] {
109 printf("<img src=\"%s\" alt=\"%s\" />\n",
110 urlize(type, selector, host, port), encode(user_name))
111 }
112
113 END {
114 footer()
115 }