tcl-hacks

Check-in [f3f967e9df]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:more hacks around being a teapot
Downloads: Tarball | ZIP archive | SQL archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:f3f967e9df48f9e53ed3d2ee422e22f1ca6b6060
User & Date: aspect 2018-07-22 23:46:12
Context
2018-07-24
10:55
move main back where it belongs check-in: 91650d811a user: aspect tags: trunk
2018-07-22
23:46
more hacks around being a teapot check-in: f3f967e9df user: aspect tags: trunk
01:32
merge procmap-tk, some extra workarounds for Tk command weirdness. Geometry managers give stupid errors check-in: b39089759c user: aspect tags: trunk
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to hacks/cuppa/cuppa.tcl.

48
49
50
51
52
53
54

55
56
57
58
59
60
61
62
63
64
65
66
67
...
115
116
117
118
119
120
121





122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

164
165
166
167
168
169
170
171
            );
            insert or replace
                into servers (pri, server,    uri)
                values  ( 1, 'activestate',  'http://teapot.activestate.com'
                ),      ( 2, 'rkeene',       'http://teapot.rkeene.org'
                );
            create table if not exists packages (

                name    text,
                ver     text collate vcompare,
                arch    text, os text, cpu text,
                server  text,
                pkgurl  text,
                primary key (name, ver, arch, os, cpu, server),
                foreign key (server) references servers (server)
            );

            create table if not exists map_os ( teapot text, local text );
            create table if not exists map_cpu ( teapot text, local text );
        }
        init_maps
................................................................................
            set when [clock format $last_checked]
            log::info {Updating cache for $server (last: $when)}
            cache_server $server $uri
        }
    }

    proc cache_server {server uri} {





        set data [geturl [join_url $uri /package/list]]
        set now [clock seconds]
        if { ![regexp {\[\[TPM\[\[(.*)\]\]MPT\]\]} $data -> data]} {
            throw {CUPPA BADTPM} "No TPM data at $uri"
        }
        if {  [catch {llength $data}] } {
            throw {CUPPA BADTPM} "TPM data not a list at $uri"
        }
        db eval {
            delete from packages where server = :server
        }
        foreach record $data {
            lassign $record type pkg ver arch
            if {$type ne "package"} continue
            if {$arch eq "source"}  continue
            regexp {^(.*)(?:-(.*))?$} $arch -> os cpu
            try {
                package vsatisfies $ver 0-
            } on error {e o} {
                log::warn {Bad version: ignoring! $pkg $ver @ $server}
                continue
            }
            set pkgurl [join_url $uri package name $pkg ver $ver arch $arch file]
            db eval {
                insert or replace
                into packages (name, ver, arch, os, cpu, server, pkgurl)
                values (:pkg, :ver, :arch, :os, :cpu, :server, :pkgurl);
            }
        }
        db eval {
            update servers set last_checked = :now where server = :server;
        }
    }

    db::qproc Find {
        name %  ver 0-  arch %  os %  cpu %
    } {
            with t as (
                select distinct name, ver, arch, os, cpu, server, pkgurl, pri
                from packages
                 inner join servers using (server)
                   -- inner join map_cpu on ( cpu like teapot and :cpu like local )

                where name like :name
                  and vsatisfies(ver, :ver)
                  and (cpu like :cpu
                    or exists (select * from map_cpu where cpu like teapot and :cpu like local))
                  and (os like :os
                    or exists (select * from map_os  where os  like teapot and :os  like local))
            )
            select * from t







>





|







 







>
>
>
>
>
|












<
<










|
|








|


|



>
|







48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
...
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140


141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
            );
            insert or replace
                into servers (pri, server,    uri)
                values  ( 1, 'activestate',  'http://teapot.activestate.com'
                ),      ( 2, 'rkeene',       'http://teapot.rkeene.org'
                );
            create table if not exists packages (
                type    text,
                name    text,
                ver     text collate vcompare,
                arch    text, os text, cpu text,
                server  text,
                pkgurl  text,
                primary key (type, name, ver, arch, os, cpu, server),
                foreign key (server) references servers (server)
            );

            create table if not exists map_os ( teapot text, local text );
            create table if not exists map_cpu ( teapot text, local text );
        }
        init_maps
................................................................................
            set when [clock format $last_checked]
            log::info {Updating cache for $server (last: $when)}
            cache_server $server $uri
        }
    }

    proc cache_server {server uri} {
        if {$server eq "rkeene"} {
            set suffix /package/list
        } else {
            set suffix /list
        }
        set data [geturl [join_url $uri $suffix]]
        set now [clock seconds]
        if { ![regexp {\[\[TPM\[\[(.*)\]\]MPT\]\]} $data -> data]} {
            throw {CUPPA BADTPM} "No TPM data at $uri"
        }
        if {  [catch {llength $data}] } {
            throw {CUPPA BADTPM} "TPM data not a list at $uri"
        }
        db eval {
            delete from packages where server = :server
        }
        foreach record $data {
            lassign $record type pkg ver arch


            regexp {^(.*)(?:-(.*))?$} $arch -> os cpu
            try {
                package vsatisfies $ver 0-
            } on error {e o} {
                log::warn {Bad version: ignoring! $pkg $ver @ $server}
                continue
            }
            set pkgurl [join_url $uri package name $pkg ver $ver arch $arch file]
            db eval {
                insert or replace
                into packages (type, name, ver, arch, os, cpu, server, pkgurl)
                values (:type, :pkg, :ver, :arch, :os, :cpu, :server, :pkgurl);
            }
        }
        db eval {
            update servers set last_checked = :now where server = :server;
        }
    }

    db::qproc Find {
        type "package" name %  ver 0-  arch %  os %  cpu %
    } {
            with t as (
                select distinct type, name, ver, arch, os, cpu, server, pkgurl, pri
                from packages
                 inner join servers using (server)
                   -- inner join map_cpu on ( cpu like teapot and :cpu like local )
                where type like :type
                  and name like :name
                  and vsatisfies(ver, :ver)
                  and (cpu like :cpu
                    or exists (select * from map_cpu where cpu like teapot and :cpu like local))
                  and (os like :os
                    or exists (select * from map_os  where os  like teapot and :os  like local))
            )
            select * from t

Added hacks/cuppa/tpc.tcl.





















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
# actions:
# [x] index update ?server ...?
# [x] index info
# [x] index add /url/
# [x] index del /pattern/
# [x] cache info
# [x] cache drop ?pkginfo to match?
# [x] find ?pkginfo?
# [x] get /pkginfo/
# [x] cat /pkginfo/
# [x] meta /pkginfo/
# [x] deps /pkginfo/
# [x] mkenv directory
# [x] install directory name ?entityinfo?
# [ ] windows: tclsh.bat
# [ ] consider fixing shebang for applications
# [ ] serve .. or produce static teapot tree
#   - nanoweb: GET only, no keepalive, minimal header handling
# [ ] help and error handling
#   - put commands into a namespace with docs
# [ ] modularise and use appdirs
# [ ] parse tclenv.txt -> uninstall
#   - empty interp
# [ ] assemble & distribute
# [ ] isatty() ?
#
# teaparty synthesises a pkgIndex.tcl for tm's.  I don't wanna do that, so
# install needs to know about libpath + tmpath.
#
# different path for native libs?  hm?  good for xplat starkits.

package require http
package require platform
package require sqlite3

source zip.tcl

proc finally {args} {
    tailcall trace add variable :#finally#: unset [list apply [list args $args]]
}

proc dictargs {defaults} {
    upvar 1 args args
    set keys [dict keys $defaults]
    if {[catch {dict size $args}]} {
        tailcall tailcall throw {TCL BAD_ARGS} "Expected dictionary argument with keys in [list $keys]"
    }
    dict for {k v} $args {
        if {$k ni $keys} {
            tailcall tailcall throw {TCL WRONG_ARGS} "Incorrect dictionary argument \"$k\", must be one of [list $keys]"
        }
    }
    set args [dict merge $defaults $args]
    tailcall dict with args {}
}

proc createfile {path data args} {
    set mode "w"
    if {[dict exists $args -binary]} {
        if {[dict get $args -binary]} {
            set mode "wb"
        }
        dict unset args -binary
    }
    if {[file exists $path]} {
        return -code error "File already exists! \"$path\""
    }
    log "Creating file \"$path\""
    set fd [open $path $mode]
    try {
        puts -nonewline $fd $data
    } finally {
        close $fd
    }
    if {$args ne ""} {
        file attributes $path {*}$args
    }
}

proc dedent {text} {
    set text [string trimleft $text \n]
    set text [string trimright $text \ ]
    regexp -line {^ +} $text space
    regsub -line -all ^$space $text ""
}


proc log {text} {
    puts stderr "# $text"
}

proc isatty {} {
    # unix:
    expr {![catch {exec sh -c {stty <&1} <@stdin >@stdout}]}
}

proc geturl {url} {
    set redirs 2
    while {1} {
        set tok [http::geturl $url]
        try {
            upvar 1 $tok state
            if {[set status [::http::status $tok]] ne "ok"} {
                throw {HTTP BAD_STATUS} "HTTP call returned \"$status\""
            }
            set headers [dict map {key val} [::http::meta $tok] {
                set key [string tolower $key]
                set val
            }]
            if {[dict exists $headers location]} {
                if {[incr redirs -1] <= 0} {
                    throw {HTTP TOO_MANY_REDIRECTS} "Too many redirections"
                }
                if {[regexp {^\w+://} $location]} {
                    set base ""
                } elseif {[regexp {^//} $location]} {
                    regexp {^(\w+:)//} $url -> base
                } elseif {[regexp {^/} $location]} {
                    regexp {^(\w+://[^/?]+)} $url -> base
                } else {
                    regexp {^(\w+://.+/)[^/]*} $url -> base
                }
                set location $base$location
                continue
            }
            return [::http::data $tok]
        } finally {
            ::http::cleanup $tok
        }
    }
}

proc join_url {args} {
    set url [join $args /\0/]
    regsub -all {/*\0/*} $url / url
    return $url
}

proc get_tpm {url} {
    set data [geturl $url]
    if {![regexp {\[\[TPM\[\[(.*)\]\]MPT\]\]} $data -> tpm]} {
        throw {TPM MISSING} "No TPM data at \"$url\""
    }
    return $tpm
}

variable map_os {
    tcl         %
    linux-%     linux
    win32       windows
    solaris%    {solaris sunos}
    freebsd     freebsd_%
    irix        irix_%
    macosx%     darwin
}
variable map_cpu {
    ix86        {x86 intel i_86 i86pc}
    sparc       sun4%
    sparc64     {sun4u sun4v}
    universal   %
    {""}        %
    powerpc     ppc
}

proc init_db {} {
    db eval {
        drop table if exists servers;
        drop table if exists pkgindex;
        drop table if exists map_os;
        drop table if exists map_cpu;
        drop table if exists packages;

        create table map_os ( teapot text, local text );
        create table map_cpu ( teapot text, local text );

        create table servers (
            rowid integer primary key asc,
            baseurl text not null,
            last_checked integer not null default 0,
            priority integer not null default 100,
            unique (baseurl)
        );

        create table pkgindex (
            rowid integer primary key,
            type text not null,
            name text not null,
            ver  text not null collate vcompare,
            arch text not null,
            os text not null,
            cpu text not null,
            url text not null,
            server_id integer not null,
            ts text default current_timestamp,
            unique (type, name, ver, arch, os, cpu, server_id),
            foreign key (server_id) references servers (rowid) on delete cascade
        );

        create table packages (
            rowid integer primary key asc,
            data blob not null,
            format text not null,
            pkgindex_id integer,
            ts text default current_timestamp,
            unique (pkgindex_id),
            foreign key (pkgindex_id) references pkgindex (rowid) on delete cascade
        );

        create table meta (
            package_id integer not null,
            key text not null,
            value text not null,
            primary key (package_id, key),
            foreign key (package_id) references packages (rowid) on delete cascade
        );
    }

    if 0 {
    variable map_os
    variable map_cpu
    foreach {teapot local} $map_os {
        foreach t $teapot {
            foreach l $local {
                db eval {
                    insert into map_os (teapot, local) values (:t, :l)
                }
            }
        }
    }
    foreach {teapot local} $map_cpu {
        foreach t $teapot {
            foreach l $local {
                db eval {
                    insert into map_cpu (teapot, local) values (:t, :l)
                }
            }
        }
    }
}
}

proc index:del {baseurl} {
    db eval {
        select baseurl from servers where baseurl like :baseurl
    } row {
        lappend result [row_as_dict row]
    }
    db eval {
        delete from servers where baseurl like :baseurl
    }
    log "Deleted [db total_changes] total items"
    return -type dicts [lappend result]
}

proc index:add {baseurl} {

    log "Indexing $baseurl ..."

    try {
        set data [get_tpm [join_url $baseurl list]]
    } on error {} {
        set data [get_tpm [join_url $baseurl package list]]
    }

    log "$baseurl: [llength $data] entities"

    db eval {insert or ignore into servers (baseurl) values (:baseurl)}
    set server_id [db eval {select rowid from servers where baseurl = :baseurl}]

    db eval { update servers set last_checked = datetime('now', 'localtime') }
    db eval { delete from pkgindex where server_id = $server_id }

    db transaction {
        foreach ent $data {

            lassign $ent type name ver arch

            if {$type eq "profile"} {
                continue
            } elseif {$type eq "redirect"} {
                continue
            }

            set os [lindex [split $arch -] 0]
            set cpu [lindex [split $arch -] end]

            if {[catch {package vsatisfies $ver 0-}]} {
                log "Ignoring bad version [list $name $ver]"
                continue
            }

            set url [join_url $baseurl $type name $name ver $ver arch $arch file]

            db eval {
                insert or replace
                into pkgindex (type, name, ver, arch, os, cpu, server_id, url)
                values (:type, :name, :ver, :arch, :os, :cpu, :server_id, :url);
            }
        }
    }

    log "$baseurl: [db total_changes] entities indexed"
}

proc index:info {args} {
    if {$args eq ""} {
        set args [db eval {select baseurl from servers}]
    }
    foreach baseurl $args {
        db eval {
            select
                baseurl, priority, last_checked,
                count(pkgindex.rowid) as items
            from servers
            left join pkgindex on (server_id = servers.rowid)
            where baseurl = :baseurl
            group by baseurl, priority, last_checked
        } row {
            lappend result [row_as_dict row]
        }
    }
    return -type dicts $result
}

proc cache:drop {args} {
    # FIXME: also support older than X
    dictargs {
        type %
        name %
        ver 0-
        arch ""
        os %
        cpu %
        server %
    }
    set rowids [db eval {
        select
            packages.rowid as rowid
        from packages
        inner join pkgindex on packages.pkgindex_id = pkgindex.rowid
        inner join servers on pkgindex.server_id = servers.rowid
        where 1
          and type like :type
          and name like :name
          and vsatisfies(ver, :ver)
          and (cpu like :cpu
            or exists (select * from map_cpu where cpu like teapot and :cpu like local))
          and (os like :os
            or exists (select * from map_os where os like teapot and :os like local))
          and baseurl like :server
    }]
    log "Deleting [llength $rowids] records"
    db transaction {
        foreach rowid $rowids {
            db eval {
                delete from packages where rowid = :rowid
            }
        }
    }
    return ""
}

proc cache:info {args} {
    dictargs {
        type %
        name %
        ver 0-
        arch ""
        os %
        cpu %
        server %
    }
    db eval {
        select
            type, name, ver, arch
            format,
            length(data) as size,
            baseurl
        from packages
        inner join pkgindex on packages.pkgindex_id = pkgindex.rowid
        inner join servers on pkgindex.server_id = servers.rowid
        where 1
          and type like :type
          and name like :name
          and vsatisfies(ver, :ver)
          and (cpu like :cpu
            or exists (select * from map_cpu where cpu like teapot and :cpu like local))
          and (os like :os
            or exists (select * from map_os where os like teapot and :os like local))
          and baseurl like :server
        order by type, name, ver desc, arch
    } row {
        lappend result [row_as_dict row]
    }
    lappend result
    return -type dicts $result
}

proc find {name args} {
    dictargs {
        type package
        ver 0-
        os ""
        cpu ""
        server %
        limit 99999999
    }
    lassign [split [platform::generic] -] os_ cpu_
    if {$os eq ""} {set os $os_}
    if {$cpu eq ""} {set cpu $cpu_}
    db eval {
        select distinct
            pkgindex.rowid as rowid, type, name, ver, arch, url
        from pkgindex
        inner join servers on (server_id = servers.rowid)
        where 1
          and type like :type
          and name like :name
          and baseurl like :server
          and vsatisfies (ver, :ver)
          and (cpu like :cpu
            or exists (select * from map_cpu where cpu like teapot and :cpu like local))
          and (os like :os
            or exists (select * from map_os where os like teapot and :os like local))
        order by name, ver desc, priority desc
        limit :limit
    } row {
        lappend result [row_as_dict row]
    }
    lappend result
    return -type dicts $result
}

proc row_as_dict {_row} {
    upvar 1 $_row row
    foreach k $row(*) {
        lappend res $k $row($k)
    }
    lappend res
}

proc download {name args} {
    foreach _ [find $name limit 1 {*}$args] {
        dict with _ {}
        log "Downloading $type $name from $url"
        return -type data [geturl $url]
    }
}

proc is_zipdata {data} {
    string match "PK\3\4*" $data
}

proc show {name args} {
    set _ [get $name {*}$args]
    dict with _ {
        set size [string length $data]
        unset data
    }
    return -type dicts [list $_]
}

proc get {name args} {
    foreach _ [find $name limit 1 {*}$args] {
        dict with _ {}
        db eval {
            select format, data from packages where pkgindex_id = :rowid
        } row {
            log "Already have $name $args"
            return -type ignore [dict merge $_ [row_as_dict row]]
        }
        set data [download $name {*}$args]
        if {[is_zipdata $data]} {
            set format "zip"
        } else {
            set format "tm"
        }
        db eval {
            insert into packages (data, format, pkgindex_id) values (:data, :format, :rowid);
        }
        log "Downloaded [string length $data] bytes"
        db eval {
            select format, data from packages where pkgindex_id = :rowid
        } row {
            return -type ignore [dict merge $_ [row_as_dict row]]
        }
    }
}

proc cat {name args} {
    set _ [get $name {*}$args]
    dict with _ {}
    if {$format eq "zip"} {
        return -type binary $data
    } else {
        return -type text $data
    }
}

proc meta {name args} {
    try {
        cat $name {*}$args
    } on ok {data opts} {
        set format [dict get $opts -type]
    }
    if {$format eq "text"} {
        if {![regexp {@@ Meta Begin\s*(.*)\n.*@@ Meta End} $data -> meta]} {
            throw {TPM NO_METADATA} "No metadata in $name $args!"
        }
    } else {
        set zip [Zip new $data]
        set meta [$zip comment]
        if {[regexp {\mMeta\M} $meta]} {
            log "Found metadata in zip comment"
        } else {
            set meta [$zip contents teapot.txt]
            log "Found metadata in zip teapot.txt"
        }
        $zip destroy
    }
    # FIXME: should check first line for eg {Package name version}
    if {$meta eq ""} {
        throw {TPC NO_META} "Metadata not found!"
    }
    set meta [regexp -line -inline -all {^(?:\s*#)?\s*Meta (\S+)\s+(.*)} $meta]
    foreach {_ key val} $meta {
        dict lappend res $key {*}$val
    }
    return -type dict $res
}

proc deps {name args} {
    set meta [meta $name {*}$args]
    foreach req [dict get $meta require] {
        # FIXME: parse properly
        if {[llength $req] > 2} {
            throw {TPM UNIMPLEMENTED} "Unsupported requirement format: $req"
        }
        lassign $req name version
        #if {$name in {Tcl Tk}} continue
        lappend res [list name $name ver $version]
    }
    lappend res
    return -type dicts $res
}

proc main {args} {
    chan configure stdout -buffering none
    set ex [file exists tpc.db]
    sqlite3 db tpc.db
    db eval {
        pragma foreign_keys = on
    }
    db collate  vcompare    {package vcompare}
    db function vsatisfies  {package vsatisfies}

    if {!$ex} {
        init_db
        index:add http://teapot.rkeene.org/
        index:add http://teapot.activestate.com/
    }

    try {
        set r [{*}$args]
    } on error {err opt} {
        log "Error: $err"
        return 1
    } on ok {res opt} {
        if {![dict exists $opt -type]} {
            dict set opt -type text
        }
        switch [dict get $opt -type] {
            ignore {}
            dict {
                array set {} $res
                parray {}
            }
            dicts {
                set row [lindex $res 0]
                dict unset row rowid
                set keys [dict keys $row]
                puts \x1b\[1m[join $keys \t]\x1b\[0m
                foreach row $res {
                    dict unset row rowid
                    puts [join [dict values $row] \t]
                }
            }
            table {
                foreach row $res {
                    puts [join $row \t]
                }
            }
            text {
                puts -nonewline $res
            }
            binary {
                set trans [chan configure stdout -translation]
                chan configure stdout -translation binary
                puts -nonewline stdout $res
                chan configure stdout -translation $trans
            }
            default {
                if {$res ne ""} {puts $res}
            }
        }
    }
    return 0
}

proc mkenv {dir} {
    if {[file isdirectory $dir]} {
        throw {TPC EXISTS} "Directory \"$dir\" already exists!"
    }

    set tclexe [info nameofexe]
    set tclver [info patch]
    regexp {^(\d+).(\d+)} $tclver -> majver minver

    log "Creating Tcl environment in $dir for $tclexe ($tclver)"
    file mkdir $dir
    file mkdir $dir/bin $dir/lib $dir/modules

    set dir [file normalize $dir]

    createfile $dir/bin/activate [dedent [subst -noc {
        # source this file to initialize your env:
        PATH="$dir/bin:\$PATH"
        # FIXME: what if these are already set?
        TCLLIBPATH="$dir/lib"
        TCL${majver}_${minver}_TM_PATH="$dir/modules"
        export PATH TCLLIBPATH TCL${majver}_${minver}_TM_PATH
    }]]

    createfile $dir/bin/tclsh [dedent [subst -noc {
        #!/bin/sh
        . "$dir/bin/activate"
        exec "$tclexe" "\$@"
    }]] -permissions 0755

    createfile $dir/tclenv.txt [dedent [subst {
        # Tcl environment initialised at [clock format [clock seconds]]
        tcl_version $tclver
        platform    [platform::identify]

        bindir      [list bin]
        libdir      [list lib]
        tmdir       [list modules]

    }]]
}

proc install {dir name args} {
    set fd [open $dir/tclenv.txt r+]
    finally close $fd

    # FIXME: read params from this file
    seek $fd 0 end

    # FIXME: follow dependencies
    set _ [get $name {*}$args]
    dict with _ {}

    switch $type {
        "application" {
            createfile [set loc $dir/bin/$name] $data -permissions 0755
        }
        "package" {
            switch $format {
                "tm" {
                    createfile [set loc $dir/modules/$name-$ver.tm] $data
                }
                "zip" {
                    file mkdir [set loc $dir/lib/$name$ver]
                    set z [Zip new $data]
                    foreach ent [$z names] {
                        if {[string match */ $ent]} {
                            file mkdir $loc/$ent
                        } else {
                            createfile $loc/$ent [$z contents $ent] -binary 1
                        }
                    }
                }
                default {
                    throw {TPM UNIMPLEMENTED} "Unsupported entity format \"$format\""
                }
            }
        }
        default {
            throw {TPM UNIMPLEMENTED} "Unsupported entity type \"$type\""
        }
    }

    puts $fd [list installed $name $ver $loc]

    close $fd
}

exit [main {*}$::argv]

Added hacks/cuppa/zip.tcl.





































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
# adapted from http://wiki.tcl.tk/3307
oo::class create Zip {
    variable Data Directory

    constructor {bytes} {
        set Data $bytes
        my ReadDirectory
    }

    method ReadDirectory {} {
        set ofs 21
        while 1 {
            set dir [string range $Data end-$ofs end]
            binary scan $dir i sig
            if {$sig == 0x06054b50} {
                break
            }
            incr ofs            ;# FIXME: this is bloody slow, be more clever
        }
        binary scan $dir issssiis sig disk cddisk nrecd nrec dirsize diroff clen
        dict set Directory() comment [string range $dir 22 [expr {22 + $clen - 1}]]
        if {$disk != 0} {
            throw {ZIP UNSUPPORTED} "Multi-file zip not supported"
        }
        for {set i 0} {$i < $nrec} {incr i} {
            set entry [string range $Data $diroff [incr diroff 46]-1]
            binary scan $entry issssssiiisssssii \
                sig ver mver flag method time date crc csz usz n m k d ia ea ofs
            if {$sig != 0x02014b50} {
                throw {ZIP ERROR} "Bad directory entry at $diroff ([format %x $sig])"
            }
            set name [string range $Data $diroff [incr diroff $n]-1]
            set extra [string range $Data $diroff [incr diroff $m]-1]
            set c [string range $Data $diroff [incr diroff $k]-1]
            set Directory($name) [dict create timestamp [list $date $time] \
                size $csz disksize $usz offset $ofs method $method \
                extra $extra comment $c]
        }
    }
    method names {} {
        lsort [lsearch -inline -exact -all -not [array names Directory] ""]
    }
    method comment {{name ""}} {
        dict get $Directory($name) comment
    }
    method info {name {field ""}} {
        if {$field ne ""} {
            return [dict get $Directory($name) $field]
        }
        return $Directory($name)
    }
    method contents {name} {
        dict with Directory($name) {}
        binary scan [string range $Data $offset [incr offset 30]-1] \
            isssssiiiss sig - - - - - - - - nlen xlen
        if {$sig != 0x04034b50} {
            throw {ZIP NOTAFILE} "not a file record"
        }
        incr offset $nlen
        incr offset $xlen
        set data [string range $Data $offset [incr offset $size]-1]
        if {[string length $data] != $size} {
            error "read length mismatch: $size expected"
        }
        switch $method {
            0   { return $data }
            8   { return [zlib inflate $data] }
            default { throw {ZIP UNSUPPORTED} "Unsupported method $method" }
        }
    }
}

if {[info script] eq $::argv0} {
    set fd [open [lindex $argv 0] rb]
    set data [read $fd]
    Zip create z $data
    puts [z comment]
    foreach n [z names] {
        puts "$n ([z info $n disksize] bytes)"
    }
    puts [z contents teapot.txt]
}

Changes to modules/getline/TODO.

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

# TODO:
#  - output attrs
#  ? modes support
#  - history-incremental-search

#  - cumulative yank
#  ? completion UI choices
#  ? prefix keymaps (eg: ^L=redraw-line; ^L^L=redraw-all-lines)
#  ? numeric arguments
#  ? yank-last-arg?  Not yank ring, stuff that.
#  ? mark
#  ? transpositions
#  ? undo
#  ? ^search^replace and !! and !prefix and !-n

# WIBNI: continuation prompts, colours, completion
#  - M-: to issue commands directly to getline
#  - M-digit digit .. counts so \e5^X^E opens an editor with LAST FIVE LINES OMG

#  - factor command definitions for symmetry, but don't go overboard
#  - attrs
#  - use exceptions for beep, result
#  - inter-line nav without excessive redraw
#  - a manual, with that call graph

# DONE:





>













>







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

# TODO:
#  - output attrs
#  ? modes support
#  - history-incremental-search
#   - make this search-backward and search-forward
#  - cumulative yank
#  ? completion UI choices
#  ? prefix keymaps (eg: ^L=redraw-line; ^L^L=redraw-all-lines)
#  ? numeric arguments
#  ? yank-last-arg?  Not yank ring, stuff that.
#  ? mark
#  ? transpositions
#  ? undo
#  ? ^search^replace and !! and !prefix and !-n

# WIBNI: continuation prompts, colours, completion
#  - M-: to issue commands directly to getline
#  - M-digit digit .. counts so \e5^X^E opens an editor with LAST FIVE LINES OMG
#  - vi-style ESC-prefixed commands, with count
#  - factor command definitions for symmetry, but don't go overboard
#  - attrs
#  - use exceptions for beep, result
#  - inter-line nav without excessive redraw
#  - a manual, with that call graph

# DONE:

Changes to tipple/README.md.

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
 * fossil repo:  `fossil+$url`, must be *well-behaved*

The source directory will be left around (in `DIR/src`) so users can view documentation and examples in there.


## Well-behaved packages

This section needs refreshing:  relying on paths like `lib` and `modules` doesn't work for many sources today; searching for `*.tm` and `pkgIndex.tcl` is likely to work better.

A *well-behaved* package source is expected to Install Correctly by the following means:

    cp -a lib/*     $TCLLIBPATH
    cp -a modules/* $TCL8_6_TM_PATH
    cp -a bin/*     DIR/bin/








|







87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
 * fossil repo:  `fossil+$url`, must be *well-behaved*

The source directory will be left around (in `DIR/src`) so users can view documentation and examples in there.


## Well-behaved packages

This section needs refreshing:  relying on paths like `lib` and `modules` doesn't work for many sources today; searching for `*.tm` and `pkgIndex.tcl` or `tclIndex` is likely to work better.

A *well-behaved* package source is expected to Install Correctly by the following means:

    cp -a lib/*     $TCLLIBPATH
    cp -a modules/* $TCL8_6_TM_PATH
    cp -a bin/*     DIR/bin/