beetlebug

Scripts and personal tools

Write small tools for your own files: a sorter for a downloads folder, a report of a bank export, a window for a quick task. Each tool runs with only the capabilities that it needs, so a bug in the tool cannot reach the rest of your files.

The CSV Report window after a drop of bank.csv: a bar for each category of spending and a table of the sums of each month

The picture shows the CSV Report window in ztk. Drop a CSV file on it to see the spending of each category and the sum of each month.

The tools

Tool What it does Capabilities
sort-inbox.tcl Moves each file of a folder into images/, documents/, archives/, audio/, or video/, with a clean name. file below one root folder. With event, it also watches the folder.
csv-report.tcl Sums a CSV of money by category and by month, prints a table, and writes JSON. file and channels below one root folder.
csv-window.tcl The window of the picture, with the same report code. file, channels, and clock, which ztk gives each script.

--root DIR sets the root folder. The script sees DIR as / and reaches no file outside it. With no --allow, a script has no file commands at all.

How it works

The sorter reads the top of the root folder and moves each file. With the capability event, it then reads the changes of a watch each 250 ms:

proc sort_all {} {
    foreach path [lsort [glob -nocomplain -types f /*]] {
        set line [sort_file $path]
        if {$line ne ""} { puts $line }
    }
}

sort_all
# The default runner has no exit command: return ends the script.
if {[info commands vwait] eq ""} { return }

set w [ztcl::watch add /]

The script checks that [pwd] is / before it moves a file. So with no --root, it stops with an error.

The CSV report parses quotes, commas and newlines in fields, and doubled quotes. It keeps each sum in cents as an integer, so the sums are exact. ztcl::json writes the report:

ztcl --root ~/finance --allow file,channels csvlib.tcl csv-report.tcl
== bank.csv
15 rows, 1 skipped, total 6484.56

By category:
  utilities             -274.65
  groceries             -221.30
  transport             -175.00
  books                  -39.99
  uncategorized           -4.50
  income                7200.00

The scripts of one command line share one interpreter, so csvlib.tcl loads first and csv-report.tcl uses it.

Run it

cd examples/usecases/personal-tools
ztcl --root ~/Downloads --allow file sort-inbox.tcl          # sort one time
ztcl --root ~/Downloads --allow file,event sort-inbox.tcl    # sort, then watch
ztcl --root sample --allow file,channels csvlib.tcl csv-report.tcl
ztk csv-window.tcl

What is in ztcl

The root folder, the capabilities, ztcl::watch, and ztcl::json are part of ztcl. The three tools are examples that you can copy and change. sample/bank.csv is made-up data. A real bank export has other column names: change them in report::build of csvlib.tcl.

More