source: code/trunk/zs_ext.go@ 26

Last change on this file since 26 was 26, checked in by zaitsev.serge, 10 years ago

added word count and time to read functions

File size: 2.3 KB
RevLine 
[24]1package main
2
3import (
[26]4 "bytes"
5 "os"
[24]6 "strconv"
7 "strings"
8 "time"
9
10 "github.com/drhodes/golorem"
[26]11 "github.com/google/gxui/math"
12 "github.com/jaytaylor/html2text"
[24]13)
14
15// zs var <filename> -- returns list of variables and their values
16// zs var <filename> <var...> -- returns list of variable values
17func Var(args []string) string {
18 if len(args) == 0 {
19 return "var: filename expected"
20 } else {
21 s := ""
22 if vars, _, err := md(args[0], globals()); err != nil {
23 return "var: " + err.Error()
24 } else {
25 if len(args) > 1 {
26 for _, a := range args[1:] {
27 s = s + vars[a] + "\n"
28 }
29 } else {
30 for k, v := range vars {
31 s = s + k + ":" + v + "\n"
32 }
33 }
34 }
35 return strings.TrimSpace(s)
36 }
37}
38
39// zs lorem <n> -- returns <n> random lorem ipsum sentences
40func Lorem(args []string) string {
41 if len(args) > 1 {
42 return "lorem: invalid usage"
43 }
44 if len(args) == 0 {
45 return lorem.Paragraph(5, 5)
46 }
47 if n, err := strconv.Atoi(args[0]); err == nil {
48 return lorem.Paragraph(n, n)
49 } else {
50 return "lorem: " + err.Error()
51 }
52}
53
54// zs datefmt <fmt> <date> -- returns formatted date from unix time
55func DateFmt(args []string) string {
56 if len(args) == 0 || len(args) > 2 {
57 return "datefmt: invalid usage"
58 }
59 if n, err := strconv.ParseInt(args[1], 10, 64); err == nil {
60 return time.Unix(n, 0).Format(args[0])
61 } else {
62 return "datefmt: " + err.Error()
63 }
64}
65
66// zs dateparse <fmt> <date> -- returns unix time from the formatted date
67func DateParse(args []string) string {
68 if len(args) == 0 || len(args) > 2 {
69 return "dateparse: invalid usage"
70 }
71 if d, err := time.Parse(args[0], args[1]); err != nil {
72 return "dateparse: " + err.Error()
73 } else {
74 return strconv.FormatInt(d.Unix(), 10)
75 }
76}
[26]77
78// zs wc <file> -- returns word count in the file (markdown, html or amber)
79func WordCount(args []string) int {
80 if os.Getenv("ZS_RECURSION") != "" {
81 return 0
82 }
83 if len(args) != 1 {
84 return 0
85 }
86 os.Setenv("ZS_RECURSION", "1")
87 out := &bytes.Buffer{}
88 if err := build(args[0], out, builtins(), globals()); err != nil {
89 return 0
90 }
91 if s, err := html2text.FromString(string(out.Bytes())); err != nil {
92 return 0
93 } else {
94 return len(strings.Fields(s))
95 }
96}
97
98// zs timetoread <file> -- returns number of minutes required to read the text
99func TimeToRead(args []string) int {
100 wc := WordCount(args)
101 return int(math.Round(float64(wc) / float64(200)))
102}
Note: See TracBrowser for help on using the repository browser.