txt
stringlengths
202
72.4k
### ---------------------------------------------------- ### -- mandelbrot ### -- Licenses: ### -- Authors: ### -- File: bin/mandelbrot-parallel.pl ### ---------------------------------------------------- #!/usr/bin/env perl6 use v6; my $max-iterations = 50; my @color_map = ( "0 0 0", "0 0 252", "64 0 252", "124 0 252", "188 0 252", "252 0 252", "252 0 188", "252 0 124", "252 0 64", "252 0 0", "252 64 0", "252 124 0", "252 188 0", "252 252 0", "188 252 0", "124 252 0", "64 252 0", "0 252 0", "0 252 64", "0 252 124", "0 252 188", "0 252 252", "0 188 252", "0 124 252", "0 64 252", "124 124 252", "156 124 252", "188 124 252", "220 124 252", "252 124 252", "252 124 220", "252 124 188", "252 124 156", "252 124 124", "252 156 124", "252 188 124", "252 220 124", "252 252 124", "220 252 124", "188 252 124", "156 252 124", "124 252 124", "124 252 156", "124 252 188", "124 252 220", "124 252 252", "124 220 252", "124 188 252", "124 156 252", "180 180 252", "196 180 252", "216 180 252", "232 180 252", "252 180 252", "252 180 232", "252 180 216", "252 180 196", "252 180 180", "252 196 180", "252 216 180", "252 232 180", "252 252 180", "232 252 180", "216 252 180", "196 252 180", "180 252 180", "180 252 196", "180 252 216", "180 252 232", "180 252 252", "180 232 252", "180 216 252", "180 196 252", "0 0 112", "28 0 112", "56 0 112", "84 0 112", "112 0 112", "112 0 84", "112 0 56", "112 0 28", "112 0 0", "112 28 0", "112 56 0", "112 84 0", "112 112 0", "84 112 0", "56 112 0", "28 112 0", "0 112 0", "0 112 28", "0 112 56", "0 112 84", "0 112 112", "0 84 112", "0 56 112", "0 28 112", "56 56 112", "68 56 112", "84 56 112", "96 56 112", "112 56 112", "112 56 96", "112 56 84", "112 56 68", "112 56 56", "112 68 56", "112 84 56", "112 96 56", "112 112 56", "96 112 56", "84 112 56", "68 112 56", "56 112 56", "56 112 68", "56 112 84", "56 112 96", "56 112 112", "56 96 112", "56 84 112", "56 68 112", "80 80 112", "88 80 112", "96 80 112", "104 80 112", "112 80 112", "112 80 104", "112 80 96", "112 80 88", "112 80 80", "112 88 80", "112 96 80", "112 104 80", "112 112 80", "104 112 80", "96 112 80", "88 112 80", "80 112 80", "80 112 88", "80 112 96", "80 112 104", "80 112 112", "80 104 112", "80 96 112", "80 88 112", "0 0 64", "16 0 64", "32 0 64", "48 0 64", "64 0 64", "64 0 48", "64 0 32", "64 0 16", "64 0 0", "64 16 0", "64 32 0", "64 48 0", "64 64 0", "48 64 0", "32 64 0", "16 64 0", "0 64 0", "0 64 16", "0 64 32", "0 64 48", "0 64 64", "0 48 64", "0 32 64", "0 16 64", "32 32 64", "40 32 64", "48 32 64", "56 32 64", "64 32 64", "64 32 56", "64 32 48", "64 32 40", "64 32 32", "64 40 32", "64 48 32", "64 56 32", "64 64 32", "56 64 32", "48 64 32", "40 64 32", "32 64 32", "32 64 40", "32 64 48", "32 64 56", "32 64 64", "32 56 64", "32 48 64", "32 40 64", "44 44 64", "48 44 64", "52 44 64", "60 44 64", "64 44 64", "64 44 60", "64 44 52", "64 44 48", "64 44 44", "64 48 44", "64 52 44", "64 60 44", "64 64 44", "60 64 44", "52 64 44", "48 64 44", "44 64 44", "44 64 48", "44 64 52", "44 64 60", "44 64 64", "44 60 64", "44 52 64", "44 48 64", ); sub mandel(Complex $c) { my $z = 0i; my $i; loop ($i = 0; $i < $max-iterations; $i++) { if ($z.abs > 2) { return $i + 1; } $z = $z * $z + $c; } return 0; } sub subdivide-for($low, $high, $count, &block) { my $factor = (1.0 / ($count - 1)) * ($high - $low); loop (my $i = 0; $i < $count; $i++) { &block($i, $low + $i * $factor); } } sub mandelbrot($height, $width, $upper-right, $lower-left) { my @lines; subdivide-for($upper-right.re, $lower-left.re, $height, -> $i, $re { @lines[$i] = start { my @line; subdivide-for($re + ($upper-right.im)i, $re + 0i, ($width + 1) / 2, -> $j, $z { @line[$width - $j - 1] = @line[$j] = mandel($z); }); @line.map(-> $value { @color_map[$value] }).join(' '); }; }); say "P3"; say "$width $height"; say "255"; for @lines -> $promise { say $promise.result; } } sub MAIN(Int $height = 31, :$max-iter = 50) { $max-iterations = $max-iter; my $upper-right = -2 + (5/4)i; my $lower-left = 1/2 - (5/4)i; mandelbrot($height +| 1, $height +| 1, $upper-right, $lower-left); }
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:slid1amo2n3e4", "authors": [ "slid1amo2n3e4", "Contributors" ], "build-depends": [ ], "depends": [ "String::Utils", "JSON::Fast", "Data::MessagePack" ], "description": "A Minimally Viable MoarVM debugger.", "license": "Artistic-2.0", "name": "mv2d", "perl": "6.c", "provides": { "App::MoarVM::Debug": "lib/App/MoarVM/Debug.rakumod", "App::MoarVM::Debug::Breakpoints": "lib/App/MoarVM/Debug/Breakpoints.rakumod", "App::MoarVM::Debug::Formatter": "lib/App/MoarVM/Debug/Formatter.rakumod", "MoarVM::Remote": "lib/MoarVM/Remote.rakumod" }, "resources": [ ], "support": { "email": "[email protected]", "source": "https://github.com/slid1amo2n3e4/mv2d.git", "bugtracker": "https://github.com/slid1amo2n3e4/mv2d/issues" }, "source-url": "https://github.com/slid1amo2n3e4/mv2d", "tags": [ "MoarVM", "Debug", "API", "CLI", "Commandline", "Terminal", "Devel", "Development", "Client" ], "test-depends": [ ], "version": "0.1.333" }
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: README.md ### ---------------------------------------------------- Fork of https://github.com/raku-community-modules/App-MoarVM-Debug Usage --------------------- Start the debugger: $ mv2d main.raku Set a breakpoint on line 42: > bp main.raku 42 Then type resume to resume the thread to hit it: > resume Type `help` to see all of the commands. Known Issues ------------ The only stepping mode currently available is Step Into. Backtraces will show incorrect line numbers. Source can be located at: https://github.com/slid1amo2n3e4/mv2d. Comments and Pull Requests are welcome. COPYRIGHT AND LICENSE ===================== Copyright 2017 - 2020 Edument AB Copyright 2024 The Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: dist.ini ### ---------------------------------------------------- name = App-MoarVM-Debug [ReadmeFromPod] filename = doc/App-MoarVM-Debug.rakudoc [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use App::MoarVM::Debug::Formatter; use App::MoarVM::Debug::Breakpoints; plan 1; pass "all modules loaded ok"; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: lib/App/MoarVM/Debug.rakumod ### ---------------------------------------------------- use MoarVM::Remote; use App::MoarVM::Debug::Formatter; use App::MoarVM::Debug::Breakpoints; use JSON::Fast; my str $spaces = " " x 80; my str $backspaces = "\b" x 80; #- global variables ------------------------------------------------------------ my $remote; my $default-thread; my %breakpoints; my %abbreviated; my %reverse-abbreviated; my $abbreviate-length; my $current-file; my @last-command-handles; my $last-command; my $events-lock := Lock.new; my %interesting-events; my constant %name-map = bytecode_file => "Bytecode file", file => "File", line => "Line", name => "Routine name", type => "Frame type" ; #- helper subs ----------------------------------------------------------------- multi sub table-print(Pair:D $pair) { table-print ($pair,) } multi sub table-print(@chunks) { MoarVM::Remote::CLI::Formatter::print-table( @chunks, :%abbreviated, :%reverse-abbreviated, :$abbreviate-length ); } sub boring-metadata($_, $v) { .starts-with("p6opaque") && (.starts-with("p6opaque_unbox") || .ends-with("s_delegate")) ?? $v == -1 !! False } sub remote(str $action, &code-to-remote, :$dont-await) { my int $width = $action.chars; print $action; my $result := $dont-await ?? code-to-remote() !! await code-to-remote(); print $backspaces.substr(0,$width); print $spaces.substr(0,$width); print $backspaces.substr(0,$width); $result } sub thread($thread) { with $thread.defined ?? $thread.Int !! $default-thread { $_ } else { say "Must specify a thread, or do an 'assume thread N' first"; Any } } #- the "help" logic ------------------------------------------------------------ multi sub help(--> Nil) { say qq:to/CMDS/; Supported commands: &bold("dump") [thread number] Print a stacktrace for the given thread. Synonyms: &bold("bt") &bold("frame") frame [thread number] Print single frame information. Synonyms: &bold("fr") &bold("suspend") [thread number] Suspend a thread, or all thread if no thread number is passed. &bold("resume") [thread number] Resume a thread, or all thread if no thread number is passed. &bold("step") into [thread number] Continue running code on the given thread until a different source line is reached. &bold("step over") [thread number] Continue running code on the given thread until a different source line in the same frame, or the current frame is left. &bold("step out") [handle (MVMContext)] [thread number] Continue running code on the given thread until the given frame is reached. To use this for stepping out, get a ctxhandle for the frame you consider "out". &bold("tl") Output a list of all threads and their status. Synonyms: &bold("threads") &bold("ctxhandle") framenumber [thread number] Retrieve a handle for a frame (MVMContext) on the thread's stack. Synonyms: &bold("stackframe") &bold("caller") [handle (MVMContext)] Retrieve a handle for a frame's caller frame (MVMContext) &bold("outer") [handle (MVMContext)] Retrieve a handle for a frame's outer frame (MVMContext) &bold("coderef") frame number [thread number] Retrieve a handle for the code object (MVMCode) for a frame on a thread's stack. &bold("lexicals") [handle (MVMContext)] Retrieve a list of lexicals and handlers for any object lexicals for a given frame. Synonyms: &bold("lex") &bold("all lexicals") [thread number] Retrieve a list of lexicals &bold("all") frames of a given thread. Synonyms: &bold("lex") &bold("metadata") [handle (MVMObject)] Retrieve a bunch of metadata about an object. Synonyms: &bold("meta") &bold("attributes") [handle (MVMObject)] Retrieve a list of all attributes an object has, along with handles for any object values. Synonyms: &bold("attrs") &bold("positionals") [handle (MVMObject)] Retrieve the contents of an object that has positional properties, like an array. Synonyms: &bold("pos") &bold("associatives") [handle (MVMObject)] Retrieve the contents of an object that has associative properties, like a hash. Synonyms: &bold("assoc") &bold("release") [handle handle ...] Releases handles, so the corresponding objects can be garbage collected. &bold("release") all [keep [handle handle ...]] Release all handles allocated by the previous command, optionally keeping the specified handles for further use. &bold("[breakpoint|bp]") [file path]? [line number] [suspend]? [stacktrace]? Sets a breakpoint for a given filename and line number. If filename not given, assume last frame's/command's file. If suspend is 1, execution of the thread that hit it will stop. If stacktrace is 1, every hit will send a stack trace along with it. &bold("breakpoints") Print all breakpoints. Synonyms: &bold("bpl") &bold("clearbp") [id] | "[file path]" [line number] Clear any breakpoints for a given ID or filename and line number. &bold("assume thread") [thread number] If you don't pass a thread number in future commands, this one will be used. &bold("assume no thread") Resets the thread selection. &bold("abbrev") [abbrev-key] Display the full output for any abbreviated field. &bold("abbrev length") length Change the default witdth of columns in printed tables. &bold("debug") [on|off] Turns debugging information on or off, or display whether it's on or off. &bold("color") [on|off] Turn ANSI Colors on or of or display whether it's on or off. CMDS } #- action handling subs -------------------------------------------------------- sub abbrev(Str() $key --> Nil) { say my $header = "Contents of entry $key:"; say "=" x $header.chars; say %abbreviated{$key}; my $footer = "End of Contents of entry $key"; say "=" x $footer.chars; say $footer; } sub abbrev-length(Int() $length --> Nil) { $abbreviate-length = $length; say "Abbreviation length is set to $length"; } # convenience: grab all lexicals on the stack sub all-lexicals($id --> Nil) { with thread($id) -> $thread { my $forget-promise; my @chunks = remote "fetching all lexicals", { my @allframes = (await $remote.dump($thread)).map: { (.<name> // "") eq '<unit-outer>' ?? (last) !! $_ } my $framecount = +@allframes; my @frame-handles; my @all-lexicals; @last-command-handles = Empty; for (^$framecount).reverse { my $handle = await $remote.context-handle($thread, $_); my $lexicals = (await $remote.lexicals($handle)); @last-command-handles.push($handle) if $handle; @frame-handles[$_] = $handle; @all-lexicals[$_] = $lexicals; }; # Check if any handles want to be replaced by an earlier handle, # if they refer to the same thing. my @all-handles = |@frame-handles; @all-handles.append($_.>>.<handle>.values.grep(*.so)) for @all-lexicals; my (@classes, %to-replace, @to-forget); try { @classes = await $remote.equivalences(@all-handles); %to-replace = classes-to-renaming(@classes); @to-forget = %to-replace.keys; } $forget-promise = $remote.release-handles(@to-forget) if @to-forget; (^$framecount).reverse.map: { my $handle := @frame-handles[$_]; my $lexicals := @all-lexicals[$_]; my $framedetails := "$_<name> ($_<file>:$(colored($_<line>, "bold")))" given @allframes[$_]; "Frame $_ - $framedetails - handle: &bold($handle)" => format-lexicals-for-frame($lexicals, handles-seen => @last-command-handles, handle-renaming => %to-replace ) } }, :dont-await; table-print(@chunks); await $_ with $forget-promise; say ""; say "call 'release all' to free these &bold(@last-command-handles.elems()) handles"; } } sub associatives(Int() $handle --> Nil) { my $result := remote "fetching associaitives for handle $handle", { $remote.object-associatives($handle) } my @associatives is List = gather { if $result<kind> eq "obj" { @last-command-handles = Empty; for $result<contents>.list { my @attributes = format-attributes(.value); @last-command-handles.push(.value<handle>) if .value<handle>; take [&bold(.value<handle>), .key, .value<type>, @attributes.join(", ")]; } } else { take ["NYI"]; } } table-print "Associatives in handle &bold($handle)" => @associatives; } multi sub assume-thread(--> Nil) { say "Not going to assume any thread for further commands"; $default-thread = Any; } multi sub assume-thread($thread --> Nil) { with thread($thread) { say "Assuming thread $_ as default for further commands"; $default-thread = $_; } } sub attributes(Int() $handle --> Nil) { my $result := remote "fetching attribute info for $handle", { $remote.attributes($handle) } say "Attributes for handle &bold($handle)"; table-print $result.categorize(*.<class>).map: { "From class $_.key()" => .value.map({ my str $attributes = format-attributes($_).join(", "); my str $type = .<kind>; $type = .<type> if $type eq "obj"; (bold(.<handle> // ""), $type, .<name>, $attributes) }).List } } sub backtrace($id --> Nil) { with thread($id) -> $thread { my @frames := remote "Fetching backtrace of thread $thread", { $remote.dump($thread) } table-print "Stack trace of thread &bold($thread)" => format-backtrace(@frames); } } sub breakpoint( Str() $file, Int() $line, Bool() $suspend = True, Bool() $stacktrace = False --> Nil) { if get-breakpoint(%breakpoints, $file, $line) -> $b { say "A breakpoint for this file and line (suspend={{$b.value<suspend>}} stacktrace={$b.value<stacktrace>}) already exists."; say 'Replace it with this new one? (y/n)'; while my $answer = prompt('> ') { if $answer eq 'y' { clearbp $b.key; last } elsif $answer eq 'n' { return } else { say "It's a y/n answer, but given $answer" } } } my $result := remote "setting breakpoint", { $remote.breakpoint($file, $line, :$suspend, :$stacktrace) } state $id = 1; %breakpoints{$id++} = %(:$file, :$line, :$suspend, :$stacktrace); output-breakpoint-notifications($file, $result<line>, $_, %breakpoints) with $result<notifications>; } sub breakpoint-list { table-print "Breakpoints" => (('id', 'file', 'line', 'suspend', 'stacktrace'), |%breakpoints.sort(*.key).map({ ($_.key, $_.value<file line suspend stacktrace>)>>.List.flat if defined $_.value })); } sub caller(Int() $handle --> Nil) { my $result := remote "fetching caller context for handle $handle", { $remote.caller-context-handle($handle) } say $result.&to-json(:pretty); } multi sub clearbp(Int() $id --> Nil) { say "Breakpoint with this ID ($id) does not exist" and return unless defined %breakpoints{$id}; my ($file, $line) = %breakpoints{$id}<file line>; clearbp $file, $line, $id; } multi sub clearbp(Str() $file, Int() $line, Int() $id? is copy --> Nil) { unless $id { my $b = get-breakpoint(%breakpoints, $file, $line) or say "No breakpoint like that ($file:$line) exists" and return; $id = $b.key; } %breakpoints{$id}:delete; my $result := remote "clearing breakpoint for $file:$line", { $remote.clear-breakpoints($file, $line) } say "Deleted breakpoint for $file:$line with ID $id"; } sub coderef(Int() $frame, $id) { with thread($id) -> $thread { my $result = remote "fetching coderef handle for frame $frame", { $remote.coderef-handle($thread, $frame) } say $result.&to-json(:pretty); } } sub color($state --> Nil) { with $state { wants-color() = $state eq "on"; say "Colored output is now &bold($state)"; } else { say "Colored output is currently &bold(wants-color() ?? "on" !! "off")"; say "(but color is not available; install Terminal::ANSIColor maybe?)" unless has-color; } } sub connect($port) { my $result := remote "connecting to MoarVM remote on localhost port $port", { MoarVM::Remote.connect($port) } say "Connected on localhost port $port"; $result } sub ctxhandle(Int() $frame, $id --> Nil) { with thread($id) -> $thread { my $result := remote "fetching context handle for frame $frame in thread $thread", { $remote.context-handle($thread, $frame)} say $result.&to-json(:pretty); } } sub debug($state --> Nil) { with $state { $remote.debug = $state eq "on"; say "Debug output is now &bold($state)"; } else { say "Debug currently &bold($remote.debug ?? "on" !! "off")"; } } sub decont(Int() $handle, $id --> Nil) { with thread($id) -> $thread { my $result := remote "fetching handle for decontainerized value of handle $handle", { $remote.decontainerize($thread, $handle) } say $result.&to-json(:pretty); } } sub frame(Int() $frame, $id --> Nil) { with thread($id) -> $thread { my @frames := remote "fetching backtrace", { $remote.dump($thread) } if @frames[$frame] -> %frame { temp $abbreviate-length *= 2; table-print "Frame &bold($frame) of thread &bold($thread)" => <bytecode_file file line name type>.map({ if %frame{$_} { bold(%name-map{$_}), %frame{$_} } }).List; } else { say "No frame $frame in thread $thread (0 .. @frames.end())"; } } } sub hllsym($name, $key --> Nil) { with $name { with $key { my $result := remote "fetching HLL sym '$key' in '$name'", { $remote.get-hll-sym($name.Str, $key.Str) } say "handle: ", $result; } else { my $result := remote "fetching names for HLL sym '$name'", { $remote.get-hll-sym-keys($name.Str) } say "Keys in HLL '$name': $result.sort(*.fc)"; } } else { my $result := remote "fetching HLL sym keys", { $remote.get-available-hlls } say "Available HLLs: $result.sort(*.fc)"; } } sub invoke(Int() $handle, *@raw --> Nil) { my $thread = $default-thread; my @arguments = [email protected]({ .[0] eq "i:" ?? ("int", try +.[1]) !! .[0] eq "o:" ?? ("obj", try +.[1]) !! .[0] eq "s:" ?? ("str", .[1].starts-with('"') && .[1].ends-with('"') ?? .[1].substr(1, *-1) !! .[1].Str) !! .[0] eq "so:" ?? ("str", .[1].Int) !! .[0] eq "n:" ?? ("num", .[1].Str.Num) !! die "can't figure out this argument: $_.Str()" }); my str $s = @arguments.elems == 1 ?? "" !! "s"; my $promise := remote "invoking $handle in thread $thread with @arguments.elems() argument$s", { $remote.invoke($thread, $handle, @arguments) } $promise.then: { table-print "Invocation result of &bold($handle) with &bold(+@arguments) arguments" => .result .grep(*.key eq none(<type id>)) .sort(*.value.^name) .map(*.kv) .List; } } sub is-suspended(--> Nil) { say (remote "checking", { $remote.is-execution-suspended }) ?? "No user threads are running" !! "All user threads are running"; } sub lexicals(Int() $handle --> Nil) { @last-command-handles = Empty; my $result := remote "fetching lexicals of $handle", { $remote.lexicals($handle) } table-print "Lexicals of handle &bold($handle)" => format-lexicals-for-frame($result, handles-seen => @last-command-handles); } sub metadata(Int() $handle --> Nil) { my $result := remote "fetching metadata of handle $handle", { $remote.object-metadata($handle) } table-print "Metadata of handle &bold($handle)" => (gather { my @features = flat "positional" xx ?$result<pos_features>, "associative" xx ?$result<ass_features>, "attributes" xx ?$result<attr_features>; take ["Features", @features.join(", ") || "none"]; take ["Size", ($result<size> // 0) ~ " + unmanaged: " ~ ($result<unmanaged_size> // 0)]; for $result.list.sort(*.key) { next if .key eq any <pos_features ass_features attr_features size unmanaged_size>; next if boring-metadata(.key, .value); if .value ~~ Positional { take [.key, .value.join(", ")]; } else { take [.key, .value // "-"]; } } }).List; } sub outer(Int() $handle --> Nil) { my $result := remote "fetching outer context for handle $handle", { $remote.outer-context-handle($handle) } say $result.&to-json(:pretty); } sub positionals(Int() $handle --> Nil) { my $result := remote "fetching positional elements for handle $handle", { $remote.object-positionals($handle) } my $cnt = $result<start>; if $result<kind> eq "obj" { @last-command-handles = Empty; my @elements is List = do for $result<contents>.list { my @attributes = format-attributes($_); @last-command-handles.push($_<handle>) if $_<handle>; [$cnt++, bold($_<handle>), $_<type>, @attributes.join(", ")] } table-print "Positionals in handle &bold($handle)" => @elements; } elsif $result<kind> eq "callsite" { my $cnt = 0; my $name-idx = 0; dd $result<contents>.list; dd $result<callsite><callsite_flags>.list; my @elements is List = do for $result<contents>.list Z $result<callsite><callsite_flags>.list -> ($_, $flags) { my @attributes; push @attributes, "literal" if "literal" (elem) $flags; push @attributes, "named " ~ ($result<callsite><arg_names>[$name-idx++]) if "named" (elem) $flags; if $flags[0] eq "obj" { @attributes.append(format-attributes($_)); [$cnt++, bold($_<handle>), $_<type>, "", @attributes.join(", ")]; } elsif $flags[0] eq "str" { [$cnt++, "", "Str", $_.raku, @attributes.join(", ")]; } elsif $flags[0] eq "int" | "uint" { [$cnt++, "", $flags[0], $_, @attributes.join(", ")]; } else { [$cnt++, "", colored("?", "red"), $_.raku, @attributes.join(", ")]; } } my $cscnt = 0; my $csname-idx = 0; my @callsite is List = do for $result<callsite><callsite_flags>.list { my @attributes; push @attributes, "literal" if "literal" (elem) $_; push @attributes, "named " ~ ($result<callsite><arg_names>[$csname-idx++]) if "named" (elem) $_; [$cscnt++, "", $_[0], "", @attributes.join(", ")] } table-print ["Callsite (arguments shape)" => @callsite, "Positionals in handle &bold($handle)" => @elements]; } else { my @elements is List = do for $result<contents>.list { [$cnt++, $_] } table-print "Positionals in handle &bold($handle)" => @elements; } } sub release-handles(*@handles --> Nil) { my int $elems = @handles.elems; my str $s = $elems == 1 ?? "" !! "s"; remote "releasing $elems handle$s", { $remote.release-handles(@handles.map(*.Int)) } say "Released $elems handle$s"; } sub release-all-handles(*@keep --> Nil) { my $to-free := @last-command-handles (-) @keep.map(*.Int); my int $elems = $to-free.elems; my str $s = $elems == 1 ?? "" !! "s"; remote "releasing $elems handle$s", { $remote.release-handles($to-free.keys) } say @keep ?? "Released $elems handle$s, keeping @keep.elems()" !! "Released $elems handle$s"; @last-command-handles = Empty; } sub resume($thread is copy --> Nil) { $thread = $thread.defined ?? $thread.Int !! Whatever; remote "resuming", { $remote.resume($thread) } say $thread ?? "Resumed thread $thread" !! "Resumed all user threads"; } sub step($type is copy, $id) { with thread($id) -> $thread { $type = $type ?? $type.Str !! "into"; my %named = $type => True; my Promise $step-finished .= new; $events-lock.protect: { my $result := remote "stepping $type", { $remote.step($thread, |%named) } my $before = now; %interesting-events{$result} = -> $event { my $timetext = now >= $before + 3 ?? " last requested $((now - $before).fmt("%6.3f")) ago" !! ""; table-print "Stack trace of thread &bold($event<thread>) after step $type$timetext" => format-backtrace($event<frames>); $step-finished.keep(); "delete"; } } # if the step finishes quite quickly, we wait a tiny moment before # spitting out the prompt again. # If you step into something that blocks, like sleep or IO or whatever, # we don't want to slow the user down. # # The brief wait also makes it possible to just hold down enter # without the repl somehow getting stuck. react { whenever $step-finished { last; } whenever Promise.in(0.07) { last; } } } } sub repeating-step($id, $codetext) { with thread($id) -> $thread { use MONKEY-SEE-NO-EVAL; my $steppercode = EVAL '-> $_ ' ~ $codetext; my Supplier $step-request-supplier .= new; sub one-more-step() { $step-request-supplier.emit(++$); CATCH { say "caught in one-more-step:"; .say; $!.say; } } say "Going to step thread $thread until the given code returns True"; say "Press ctrl-c to interrupt."; say ""; react { whenever $step-request-supplier.Supply { my Promise $step-finished .= new; my $before; $events-lock.protect: { my $result := await $remote.step($thread, :into); $before = now; %interesting-events{$result} = -> $event { $step-finished.keep($event); "delete"; } } my $last-step-finish-tap = do whenever $step-finished -> $event { my &*print-stacktrace = { # Since we are outputting a running "x steps done" # where we keep the line around with backspaces, we # should put empty lines before and after any output say ""; say ""; table-print "Stack trace of thread &bold($event<thread>) after automatic step" => format-backtrace($event<frames>); say ""; say ""; } my $*before = $before; my $*remote = $remote; if $steppercode($event) { say "User-provided stepper function indicated stop."; $step-request-supplier.done; } else { one-more-step; } } # when the sigint handler calls .done on the # step request supply, this LAST block is called. # We have access to the last step finish tap as well # as the last in-use step-finished promise. LAST { # After the user stopped the stepping, don't run the # stepper code any more. $last-step-finish-tap.close; my $start-waiting = now; my $suggestion-timeout-tap = do whenever Promise.in(2) { say ""; say "Step is not finishing quickly. Press ctrl-c a second time to stop waiting"; say ""; } whenever $step-finished { $suggestion-timeout-tap.close; done; } # Let's also output a notification when the step has # finished even if we have aborted this react block. $step-finished.then({ if $start-waiting before now - 2 { say "Step started in a step-until { now - $start-waiting }s ago finished."; } }); } } whenever $step-request-supplier.Supply -> $n { FIRST { say "Starting to step ..."; } print $backspaces.substr(0, 20); print "done $n steps ..."; } whenever signal(SIGINT) { say ""; say "Sigint caught. Will not request any more steps ..."; say ""; $step-request-supplier.done; # We can notify the user about the ability to press ctrl-c a # second time if we're not done immediately. # We don't immediately just exit the whole react block because # leaving a step "hanging" could be undesirable. whenever signal(SIGINT) { say ""; say "Sigint caught a second time. Leaving the stepping process ..."; say ""; done; } last; } $step-request-supplier.emit(0); } } } sub suspend($thread is copy --> Nil) { $thread = $thread.defined ?? $thread.Int !! Whatever; remote "suspending", { $remote.suspend($thread) } say $thread ?? "Suspended thread $thread" !! "Suspended all user threads"; } sub thread-list(--> Nil) { my $result := remote "fetching thread list", { $remote.threads-list } my @threads = <<thread suspended "native id" "num locks" "app lifetime?" name>>.item; for $result.sort(*.<thread>) { @threads.push: ( bold(.<thread>), .<suspended>, .<native_id>.fmt("0x%x"), .<num_locks>, .<app_lifetime>, (.<name> // "") ); } table-print "Threads" => @threads; } #- input handling -------------------------------------------------------------- multi sub MAIN(Str $path, Int $port, Int $abbreviate-length, *@args) is export { say "Welcome to the MoarVM Remote Debugger!"; $current-file = $path; unless %*ENV<_>:exists and %*ENV<_>.ends-with: 'rlwrap' { say ""; say "For best results, please run this program inside rlwrap"; } $remote := connect($port); $remote.events.tap: { $events-lock.protect: { my $id := .<id>; if %interesting-events{$id}:exists { if %interesting-events{$id}($_) eq "delete" { %interesting-events{$id}:delete } } else { say "Got event: "; .say } Nil; } } assume-thread(1); until (my $input = prompt("> ")) === Any { $_ = $input; if m/^$/ { $_ = $last-command; } else { $last-command = $_; } when /:s execution / { is-suspended(); } when /:s sus[p[e[nd?]?]?]? (\d+)? / { suspend $0; } when /:s res[u[m[e?]?]?]? (\d+)? / { resume $0; } when /:s [dump|bt|backtrace] (\d+)? / { backtrace $0; } when /:s [fr|frame] (\d+) (\d+)? / { frame $0, $1; } when / [tl|threads] / { thread-list; } when /:s [ctxhandle|[call|stack]frame] (\d+) (\d+)? / { ctxhandle $0, $1; } when /:s caller (\d+) / { caller $0; } when /:s outer (\d+) / { outer $0; } when /:s coderef (\d+) (\d+)? / { coderef $0, $1; } when /:s all lex[icals]? (\d+)? / { all-lexicals $0; } when /:s lex[icals]? (\d+) / { lexicals $0; } when /:s meta[data]? (\d+) / { metadata $0; } when /:s attr[ibute]?s (\d+) / { attributes $0; } when /:s pos[itionals]? (\d+) / { positionals $0; } when /:s assoc[iatives]? (\d+) / { associatives $0; } when /:s de[cont]? (\d+) (\d+)? / { decont $0, $1; } when /:s clearbp [(\d+) | \"(.*?)\" (\d+)] / { $0.Int ?? clearbp $0 !! clearbp $0, $1; } when /:s [breakpoint|bp][":"|<.ws>] (.*?) (\d+) (\d?) (\d?) / { breakpoint $0.trim ?? $0 !! $current-file, $1, $2 ~~ '0' ?? False !! True , +$3; } when /:s [breakpoints|bpl] / { breakpoint-list; } when /:s release[handles]? (\d+)+ % \s+/ { release-handles |$0; } when /:s release all [handles]? [keep (\d+)+ % \s+]?/ { release-all-handles |$0; } when /:s assume thread (\d+)? / { assume-thread($0); } when /:s assume no thread / { assume-thread; } when /:s s[tep]? u[ntil]? (\d+)? ('{' .* '}') / { repeating-step $0, $1; } when /:s s[tep]? (into|over|out)? (\d+)? / { step $0, $1; } when / invoke \s+ (\d+) [\s+ | $] $<arguments>=(( "i:" | "s:" | "n:" | s? "o:" ) ( \" <-["]>* \" | \S+ ) )* % \s+ $ / { invoke $0, |$<arguments>; } when /:s hll[sym]? [$<hllname>=\S+ [$<hllkey>=\S+]? ]? / { hllsym $<hllname>, $<hllkey>; } when /:s abbrev length (\d+) / { abbrev-length $0; } when /:s abbrev (.*) / { abbrev $0; } when /:s debug [(on|off)]?/ { debug $0; } when /:s color [(on|off)]?/ { color $0; } when /:s help / { help; } default { say "Don't know what to do with '$_'.\nEnter 'help' for options"; } CATCH { default { .say; } } } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: lib/App/MoarVM/Debug/Breakpoints.rakumod ### ---------------------------------------------------- unit module MoarVM::Remote::CLI::Breakpoints; use App::MoarVM::Debug::Formatter; my %files; sub output-breakpoint-notifications(Str $file, Int $line, Supply $notifications, %breakpoints) is export { start { react whenever $notifications.Supply -> $ev { list-file $file, $line, %breakpoints; with $ev<frames> -> $frames { my @this-backtrace = format-backtrace($frames); print-table my @chunks = "Breakpoint on $file:$line hit by thread &bold($ev.<thread>)!" => @this-backtrace;; } else { say "Breakpoint on $file:$line hit by thread &bold($ev.<thread>)!"; } } CATCH { say "Breakpoint handler aborted"; .say; } }; } sub get-breakpoint(%breakpoints, Str $file, Int $line) is export { %breakpoints.pairs.first({ .value<file> eq $file and .value<line> eq $line }) } sub list-file(Str $file, Int $line, %breakpoints --> Nil) is export { %files{$file} = $file.IO.open.lines.list unless %files{$file}:exists; my @lines := %files{$file}; my $index = max $line - 6, 0; my $end-index = min $line + 4, @lines.elems - 1; until $index > $end-index { say get-breakpoint(%breakpoints, $file, $index + 1) ?? 'BR ' !! ' ', $index + 1 eq $line ?? '-->' !! ' ', "{$index + 1} \t @lines[$index]"; $index++; } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: lib/App/MoarVM/Debug/Formatter.rakumod ### ---------------------------------------------------- unit module MoarVM::Remote::CLI::Formatter; use String::Utils <root>; my $has-color = (try require Terminal::ANSIColor) !=== Nil; my $wants-color = $*OUT.t; $! = Nil; our sub wants-color is rw is export { $wants-color } our sub has-color is export { $has-color } our sub colorstrip(Str() $text) is export { if $has-color { Terminal::ANSIColor::EXPORT::DEFAULT::colorstrip($text) } else { $text } } our sub strlen(Str() $what) is nodal is export { if $has-color { Terminal::ANSIColor::EXPORT::DEFAULT::colorstrip($what).chars; } else { $what.chars; } } our sub colored(Str() $what, $how) is export { if $has-color && $wants-color { Terminal::ANSIColor::EXPORT::DEFAULT::colored($what, $how); } else { $what } } our sub bold($what) is export { colored($what, "bold"); } our sub format-attributes($lex-or-attr) is export { flat "concrete" xx ?$_<concrete>, "container" xx ?$_<container>, "value: {$_<value>//""}" xx ($_<value>:exists) given $lex-or-attr; } sub classes-to-renaming(@classes) is export { my %to-replace{Int} = do for @classes { given $_.sort.List { |($_.tail(*-1) X=> $_.head) } } } our sub format-lexicals-for-frame($lexicals, :@handles-seen, :%handle-renaming) is export { gather for $lexicals.kv -> $n, $/ { my @attributes = format-attributes($/); my $orig-handle = $<handle>.Int if $<handle>; my $handle = %handle-renaming{$orig-handle} if %handle-renaming && $orig-handle; $handle //= $orig-handle; @handles-seen.push($handle) if $handle && $handle == $orig-handle && defined @handles-seen; take bold($handle // ""), $<type> || $<kind>, $n, @attributes.join(", "); }.sort({+colorstrip(.[0])}).cache } our sub format-backtrace(@backtrace) is export { my str $root = root @backtrace.map: { my str $name = .<name> || "<anon>"; last if $name eq '<unit>'; with .<bytecode_file> { $_ if $_ } } my int $offset = $root.ends-with("CORE.") ?? $root.chars - 5 !! $root.chars; @backtrace.map({ my str $name = .<name> || "<anon>"; last if $name eq '<unit-outer>'; my str $bytecode = .<bytecode_file> // ""; $bytecode = $bytecode.substr($offset) if $bytecode; ($++, .<type>, $name, "$_<file>:" ~ colored(~$_<line>, "bold"), $bytecode) }).List } our sub print-table(@chunks is copy, :%abbreviated, :%reverse-abbreviated, :$abbreviate-length) is export { sub abbreviate(Str() $text is copy) { if !defined %abbreviated or !defined $abbreviate-length { return $text; } state $wordlist; if strlen($text) > $abbreviate-length { my $key; $wordlist //= do { (try "/usr/share/dict/words".IO.lines().cache) || ( gather loop { given flat((<b c d f g h j k l m n p q r s t v w x z>.pick((1,1,1,2).pick).Slip, <a e i o u y>.pick((1,2).pick).Slip) xx (1,1,1,2,2).pick).join("") { take $_ if $_.chars > 3; } } ).unique[^100].cache }; my @wordcount = flat 1 xx 20, 2 xx 40, 3 xx 100, 4 xx 100, 5 xx 100, 6 xx 100, 7 xx 100, 8 xx 100, 9 xx 100; if defined %reverse-abbreviated and (%reverse-abbreviated{$text}:exists) { $key = %reverse-abbreviated{$text}; } else { repeat { $key = $wordlist.pick(@wordcount.shift)>>.lc.join("-"); } while %abbreviated{$key}:exists; %abbreviated{$key} = $text; %reverse-abbreviated{$text} = $key with %reverse-abbreviated; } $text .= &colorstrip; my $ot = $text; $text = $text.lines()[0]; my $abbrevkey = "... $ot.chars() chars, $ot.lines().elems() lines, key: $key"; $text.substr-rw($text.chars min ($abbreviate-length - $abbrevkey.chars max 0), *) = $abbrevkey; } $text; } my $num-cols = [max] @chunks>>.value.map([max] *>>.elems).flat; if $num-cols == -Inf { say @chunks.raku; try say @chunks[0].key, ": empty."; return; } CATCH { .raku.say; .raku.say for @chunks; } my @col-sizes = 0 xx $num-cols; for @chunks { for .value { @col-sizes >>[max]=>> $_>>.&strlen; } } @col-sizes >>min=>> $_ with $abbreviate-length; my @result; for @chunks -> $chunk { @result.push: "\n"; @result.push: $chunk.key ~ "\n"; for @($chunk.value) -> $line { @result.push: " "; for @$line Z @col-sizes -> ($text, $fieldwidth) { @result.push: $text.&abbreviate.&pad($fieldwidth + 2) } @result.push: "\n"; } } @result.shift; # remove first newline @result.pop; # remove last newline say @result.join(""); } our sub pad(Str() $str, $size) is export { my $result = " " x $size; $result.substr-rw(0..$str.&strlen) = $str; $result; } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- mv2d ### -- Licenses: Artistic-2.0 ### -- Authors: slid1amo2n3e4, Contributors ### -- File: lib/MoarVM/Remote.rakumod ### ---------------------------------------------------- use Data::MessagePack; use Data::MessagePack::StreamingUnpacker; use JSON::Fast; our enum MessageType is export < MT_MessageTypeNotUnderstood MT_ErrorProcessingMessage MT_OperationSuccessful MT_IsExecutionSuspendedRequest MT_IsExecutionSuspendedResponse MT_SuspendAll MT_ResumeAll MT_SuspendOne MT_ResumeOne MT_ThreadStarted MT_ThreadEnded MT_ThreadListRequest MT_ThreadListResponse MT_ThreadStackTraceRequest MT_ThreadStackTraceResponse MT_SetBreakpointRequest MT_SetBreakpointConfirmation MT_BreakpointNotification MT_ClearBreakpoint MT_ClearAllBreakpoints MT_StepInto MT_StepOver MT_StepOut MT_StepCompleted MT_ReleaseHandles MT_HandleResult MT_ContextHandle MT_ContextLexicalsRequest MT_ContextLexicalsResponse MT_OuterContextRequest MT_CallerContextRequest MT_CodeObjectHandle MT_ObjectAttributesRequest MT_ObjectAttributesResponse MT_DecontainerizeHandle MT_FindMethod MT_Invoke MT_InvokeResult MT_UnhandledException MT_OperationUnsuccessful MT_ObjectMetadataRequest MT_ObjectMetadataResponse MT_ObjectPositionalsRequest MT_ObjectPositionalsResponse MT_ObjectAssociativesRequest MT_ObjectAssociativesResponse MT_HandleEquivalenceRequest MT_HandleEquivalenceResponse MT_HLLSymbolRequest MT_HLLSymbolResponse >; class X::MoarVM::Remote::ProtocolError is Exception { has $.attempted; method message { "Something went wrong in communicating with the server while trying to $.attempted" } } class X::MoarVM::Remote::MessageType is Exception { has $.type; method message { "Message type $.type not understood by remote." } } class X::MoarVM::Remote::MessageProcessing is Exception { has $.reason; method message { with $.reason { "Remote encountered an error processing message: $_"; } else { "Remote encountered an unexplained error"; } } } class X::MoarVM::Remote::Version is Exception { has @.versions; method message { "Incompatible remote version: @.versions[]" } } sub recv32be($inbuf) { my $buf = $inbuf.splice(0, 4); [+] $buf.list >>+<>> (24, 16, 8, 0); } sub recv16be($inbuf) { my $buf = $inbuf.splice(0, 2); [+] $buf.list >>+<>> (8, 0); } sub send32be($sock, $num) { my $buf = Buf[uint8].new($num.polymod(255, 255, 255, 255)[^4].reverse); $sock.write($buf); } class MoarVM::Remote { has int $.debug is rw; has $!sock; has $!worker; has Lock $!queue-lock .= new; has @!request-promises; has %!event-suppliers; has %!breakpoint-to-event; has Lock $!id-lock .= new; has int32 $!req_id = 1; has Supply $!worker-events; has Version $.remote-version; has Supplier $!events-supplier = Supplier::Preserving.new; has Supply $.events = $!events-supplier.Supply; submethod TWEAK(:$!sock, :$!worker-events) { self!start-worker; } sub take-greeting(buf8 $buffer) { if $buffer.elems >= "MOARVM-REMOTE-DEBUG\0".chars + 4 { if $buffer.subbuf(0, "MOARVM-REMOTE-DEBUG\0".chars).list eqv "MOARVM-REMOTE-DEBUG\0".encode("ascii").list { $buffer.splice(0, "MOARVM-REMOTE-DEBUG\0".chars); # Currently no need for a specific minor version to be met. my $major = recv16be($buffer); my $minor = recv16be($buffer); if $major != 1 { die X::MoarVM::Remote::Version.new(:versions($major, $minor)); } return Version.new("$major.$minor"); } } False } method connect(MoarVM::Remote:U: Int $port) { start { my @sleep-intervals = 0.5, 1, 1, 2, 4, Failure.new("connection retries exhausted"); my $result; loop { my $sockprom = Promise.new; my $handshakeprom = Promise.new; my $remote-version = Promise.new; my $without-handshake = supply { whenever IO::Socket::Async.connect("localhost", $port) -> $sock { $sockprom.keep($sock); my $handshake-state = 0; my $buffer = buf8.new; whenever $sock.Supply(:bin) { if $handshake-state == 0 { $buffer.append($_); if take-greeting($buffer) -> $version { await $sock.write("MOARVM-REMOTE-CLIENT-OK\0".encode("ascii")); $remote-version.keep($version); $handshake-state = 1; $handshakeprom.keep(); if $buffer { die X::MoarVM::Remote::ProtocolError.new(attempted => "receiving the greeting - and only the greeting"); } } } else { emit $_; } } QUIT { try $handshakeprom.break($_) } } } my $without-handshake-shared = $without-handshake.share; $without-handshake-shared.tap({;}, quit => { try $sockprom.break($_) }); my $worker-events = Data::MessagePack::StreamingUnpacker.new(source => $without-handshake-shared).Supply; my $res = self.bless(sock => (await $sockprom), :$worker-events, remote-version => await $remote-version); $without-handshake-shared.batch(:2seconds).tap({ if $res.debug { my @full = ([~] @$_).list; if @full > 35 { say "received:"; .fmt("%x", " ").say for @full.rotor(40 => 0, :partial); } else { note "received: @full.fmt("%02x", " ")"; } } }); await $handshakeprom; $result = $res; last; CATCH { when .message.contains("connection refused") { sleep @sleep-intervals.shift; } } } $result } } method !start-worker { $!worker //= start react { whenever $!worker-events -> $message { my $task; $!queue-lock.protect: { $task = @!request-promises.grep(*.key == $message<id>).head.value; @!request-promises .= grep(*.key != $message<id>) with $task; } if $message<type>:exists { $message<type> = MessageType($message<type>); } without $task { dd $message if $!debug; with %!event-suppliers{$message<id>} { note "An event handler gets a notification" if $!debug; if $_ ~~ Supplier { .emit($message); } elsif .^can("keep") { .keep($message); %!event-suppliers{$message<id>}:delete; } } else { note "Got notification from moarvm: $message.&to-json(:pretty)" if $!debug; $!events-supplier.emit($message); } next; } note "got reply from moarvm: $message.raku()" if $!debug; if $message<type> == 0 { $task.break(X::MoarVM::Remote::MessageType.new(type => $message<type>)); } elsif $message<type> == 1 { $task.break(X::MoarVM::Remote::MessageProcessing.new(reason => $message<reason>)); } else { $task.keep($message) } LAST $!events-supplier.done(); } QUIT { $!events-supplier.quit($_); } } } method !get-request-id { $!id-lock.protect: { my $res = $!req_id; $!req_id += 2; $res } } method !send-request($type, *%data) { die "Cannot send request; Worker has finished running." if $!worker.status === PromiseStatus::Kept; if $!worker.status === PromiseStatus::Broken { note "Cannot send request; Worker has crashed!"; $!worker.result.self; } my $id = self!get-request-id; my %data-to-send = %data, :$id, :$type; my $packed = Data::MessagePack::pack(%data-to-send); note $packed if $!debug; start { my $prom = Promise.new; $!queue-lock.protect: { @!request-promises.push($id => $prom.vow); } await $!sock.write($packed); await $prom; } } multi method is-execution-suspended() { self!send-request(MT_IsExecutionSuspendedRequest).then({ .result<suspended> }) } method threads-list { self!send-request(MT_ThreadListRequest).then({ .result<threads>.list; }) } multi method suspend(Int $thread) { self!send-request(MT_SuspendOne, :$thread).then({ .result<type> === MT_OperationSuccessful }) } multi method resume(Int $thread) { self!send-request(MT_ResumeOne, :$thread).then({ .result<type> == 3 }) } multi method suspend(Whatever) { self!send-request(MT_SuspendAll).then({ .result<type> == 3 }) } multi method resume(Whatever) { self!send-request(MT_ResumeAll).then({ .result<type> == 3 }) } method context-handle(Int $thread, Int $frame) { self!send-request(MT_ContextHandle, :$thread, :$frame).then({ .result<handle>; }) } method caller-context-handle(Int $handle) { self!send-request(MT_CallerContextRequest, :$handle).then({ .result<handle>; }) } method outer-context-handle(Int $handle) { self!send-request(MT_OuterContextRequest, :$handle).then({ .result<handle>; }) } method coderef-handle(Int $thread, Int $frame) { self!send-request(MT_CodeObjectHandle, :$thread, :$frame).then({ .result<handle>; }) } method lexicals(Int $handle) { self!send-request(MT_ContextLexicalsRequest, :$handle).then({ .result<lexicals>; }) } method attributes(Int $handle) { self!send-request(MT_ObjectAttributesRequest, :$handle).then({ .result<attributes>.list; }) } method decontainerize(Int $thread, Int $handle) { self!send-request(MT_DecontainerizeHandle, :$thread, :$handle).then({ .result<handle>; }) } method find-method(Int $thread, Int $handle, Str $name) { self!send-request(MT_FindMethod, :$thread, :$handle, :$name).then({ .result<handle>; }) } method dump(Int $thread) { self!send-request(MT_ThreadStackTraceRequest, :$thread).then({ .result<frames>.list; }) } method breakpoint(Str $file, Int $line, Bool :$suspend = True, Bool :$stacktrace = True) { self!send-request(MT_SetBreakpointRequest, :$file, line => +$line, :$suspend, :$stacktrace).then({ if .result<type> == MT_SetBreakpointConfirmation { %!breakpoint-to-event{$file => .result<line>}.push(.result<id>); note "setting up an event supplier for event $_.result()<id>" if $!debug; %!event-suppliers{.result<id>} = my $sup = Supplier::Preserving.new; note "set it up" if $!debug; my %ret = flat @(.result.hash), "notifications" => $sup.Supply; note "created return value" if $!debug; %ret } }) } method clear-breakpoints(Str $file, Int $line) { self!send-request(MT_ClearBreakpoint, :$file, :$line).then({ %!breakpoint-to-event{$file => $line}.map({ %!event-suppliers{$_}.done }); .result<type> == MT_OperationSuccessful }) } method release-handles(+@handles) { my @handles-cleaned = @handles.map(+*); self!send-request(MT_ReleaseHandles, handles => @handles-cleaned).then({ .result<type> == MT_OperationSuccessful }) } method object-metadata(Int $handle) { self!send-request(MT_ObjectMetadataRequest, :$handle).then({ .result<metadata> }) } method object-positionals(Int $handle) { self!send-request(MT_ObjectPositionalsRequest, :$handle).then({ .result }) } method object-associatives(Int $handle) { self!send-request(MT_ObjectAssociativesRequest, :$handle).then({ .result }) } multi method step(Int $thread, :$into!) { self!send-request(MT_StepInto, :$thread).then({ .result<id> if .result<type> == MT_OperationSuccessful }) } multi method step(Int $thread, :$over!) { self!send-request(MT_StepOver, :$thread).then({ .result<id> if .result<type> == MT_OperationSuccessful }) } multi method step(Int $thread, :$out!) { self!send-request(MT_StepOut, :$thread).then({ .result<id> if .result<type> == MT_OperationSuccessful }) } method get-available-hlls() { self!send-request(MT_HLLSymbolRequest).then({ .result<keys> if .result<type> == MT_HLLSymbolResponse }); } method get-hll-sym-keys(Str $hll) { self!send-request(MT_HLLSymbolRequest, :$hll).then({ .result<keys> if .result<type> == MT_HLLSymbolResponse }); } method get-hll-sym(Str $hll, Str $name) { self!send-request(MT_HLLSymbolRequest, :$hll, :$name).then({ .result<handle> }); } method invoke(Int $thread, Int $handle, @arguments) { die "malformed arguments: needs to be two-element lists in a list" unless all(@arguments).elems == 2; die "malformed arguments: first entry must be str, int, num, or obj" unless all(@arguments)[0] eq any(<str int num obj>); die "int arguments must have integer numbers" unless @arguments>>[0] ne "int" Z|| so (try @arguments>>[1].Int); die "num arguments must have integer or floating point numbers" unless @arguments>>[0] ne "num" Z|| so (try +@arguments>>[1]); die "str arguments must have a string or be an Int" unless @arguments>>[0] ne "str" Z|| @arguments>>[1] ~~ Str | Int; die "obj arguments must have an integer number" unless @arguments>>[0] ne "obj" Z|| @arguments>>[1] ~~ Int; my @passed-args = @arguments.map({ .[0] eq "int" ?? %(kind => "int", value => +.[1]) !! .[0] eq "str" ?? ( .[1] ~~ Str ?? %(kind => "str", value => ~.[1]) !! %(kind => "str", handle => .[1])) !! .[0] eq "num" ?? %(kind => "num", value => Num(.[1])) !! .[0] eq "obj" ?? %(kind => "obj", handle => .[1].Int) !! $_ }); my $invoke-setup-result = await self!send-request( MT_Invoke, :$thread, :$handle, arguments => @passed-args ); die $invoke-setup-result if $invoke-setup-result.<type> != MT_OperationSuccessful; my Promise $result .= new; %!event-suppliers{$invoke-setup-result<id>} = $result.vow; $result } method equivalences(+@handles) { my @handles-cleaned = @handles.map(+*); if $.remote-version before v1.1 { Promise.broken("Remote does not yet implement equivalences command"); } else { self!send-request(MT_HandleEquivalenceRequest, :handles(@handles-cleaned)).then({ .result<classes>.List if .result<type> == MT_HandleEquivalenceResponse }); } } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:lizmat", "authors": [ "Elizabeth Mattijsen" ], "build-depends": [ ], "depends": [ ], "description": "provide term for epoch in nano seconds", "license": "Artistic-2.0", "name": "nano", "perl": "6.d", "provides": { "nano": "lib/nano.rakumod" }, "resources": [ ], "source-url": "https://github.com/lizmat/nano.git", "tags": [ ], "test-depends": [ ], "version": "0.0.2" }
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/lizmat/nano/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/nano/actions) [![Actions Status](https://github.com/lizmat/nano/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/nano/actions) [![Actions Status](https://github.com/lizmat/nano/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/nano/actions) NAME ==== nano - provide term for epoch in nano seconds SYNOPSIS ======== ```raku use nano; say nano; # 1657823392165615978 ``` DESCRIPTION =========== The `nano` module exports a single term `nano` that returns the number of nano-seconds since January 1, 1970 UTC (1970-01-01T00:00:00Z). It is a more accurate version of the `time` term. AUTHOR ====== Elizabeth Mattijsen <[email protected]> Source can be located at: https://github.com/lizmat/nano . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! COPYRIGHT AND LICENSE ===================== Copyright 2022, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: dist.ini ### ---------------------------------------------------- name = nano [ReadmeFromPod] ; enabled = false filename = doc/nano.rakudoc [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use nano; plan 2; isa-ok nano, Int, 'did we get an Int?'; ok nano > 1657823799207739852, 'did nano work ok?'; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/coverage.rakutest ### ---------------------------------------------------- use Test::Coverage; plan 2; coverage-at-least 100; uncovered-at-most 0; source-with-coverage; report; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- nano ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: lib/nano.rakumod ### ---------------------------------------------------- sub term:<nano>() is export { use nqp; nqp::time } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:raku-community-modules", "author": "Tobias Leich", "build-depends": [ ], "depends": [ ], "description": "Change stringification behaviour of literals", "license": "NOASSERTION", "name": "overload::constant", "perl": "6.*", "provides": { "overload::constant": "lib/overload/constant.rakumod" }, "resources": [ ], "source-url": "https://github.com/raku-community-modules/overload-constant.git", "tags": [ "SLANG", "OVERLOAD" ], "test-depends": [ ], "version": "0.0.3" }
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/linux.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/macos.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) [![Actions Status](https://github.com/raku-community-modules/overload-constant/actions/workflows/windows.yml/badge.svg)](https://github.com/raku-community-modules/overload-constant/actions) NAME ==== overload::constant - Change stringification behaviour of literals SYNOPSIS ======== ```raku use overload::constant; sub integer { "i$^a" } sub decimal { "d$^a" } sub radix { "r$^a" } sub numish { "n$^a" } use overload::constant &integer, &decimal, &radix, &numish; ok 42 ~~ Str && 42 eq 'i42', 'can overload integer'; ok 0.12 ~~ Str && 0.12 eq 'd0.12', 'can overload decimal'; ok .1e-003 ~~ Str && .1e-003 eq 'd.1e-003', 'can overload decimal in scientific notation'; ok :16<FF> ~~ Str && :16<FF> eq 'r:16<FF>', 'can overload radix'; ok NaN ~~ Str && NaN eq 'nNaN', 'can overload other numish things'; ``` DESCRIPTION =========== It is meant to work a bit like Perl's [overload::constant](https://perldoc.perl.org/overload#Overloading-Constants), though it is kind of pre-alpha here. AUTHOR ====== Tobias Leich COPYRIGHT AND LICENSE ===================== Copyright 2014 - 2017 Tobias Leich Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: dist.ini ### ---------------------------------------------------- name = overload::constant [ReadmeFromPod] filename = lib/overload/constant.rakumod [UploadToZef] [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; plan 9; { sub integer { "i$^a" } sub decimal { "d$^a" } sub radix { "r$^a" } sub numish { "n$^a" } use overload::constant &integer, &decimal, &radix, &numish; ok 42 ~~ Str && 42 eq 'i42', 'can overload integer'; ok 0.12 ~~ Str && 0.12 eq 'd0.12', 'can overload decimal'; ok .1e-003 ~~ Str && .1e-003 eq 'd.1e-003', 'can overload decimal in scientific notation'; ok :16<FF> ~~ Str && :16<FF> eq 'r:16<FF>', 'can overload radix'; ok NaN ~~ Str && NaN eq 'nNaN', 'can overload other numish things'; } { sub integer { $^a; 1.0 } use overload::constant &integer; ok 42 == 1.0, 'overloaded integer can return a Rat'; } { sub integer { $^a; 21 } use overload::constant &integer; ok 42 == 21.0, 'overloaded integer can return an integer'; } ok 42 !~~ Str, 'overload only happens inside its scope'; ok 42 == 42.0, 'overload only happens inside its scope'; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- overload::constant ### -- Licenses: NOASSERTION ### -- Authors: ### -- File: lib/overload/constant.rakumod ### ---------------------------------------------------- use nqp; my sub atkeyish(Mu \h, \k) { nqp::atkey(nqp::findmethod(h, 'hash')(h), k) } my role Numish[%handlers] { method numish(Mu $/) { sub call-handler($r) { do given nqp::decont($r) { when Str { $*W.add_string_constant( nqp::unbox_s($_) ) } when Int { $*W.add_numeric_constant($/, 'Int', nqp::unbox_i($_)) } when Num { $*W.add_numeric_constant($/, 'Num', nqp::unbox_n($_)) } when Rat { $*W.add_numeric_constant($/, 'Num', nqp::unbox_n($_.Num)) } } } if atkeyish($/, 'integer') -> $v { $/.make( %handlers<integer> ?? call-handler(%handlers<integer>(nqp::p6box_s($v.Str))) !! $*W.add_numeric_constant($/, 'Int', $v.made) ) } elsif atkeyish($/, 'dec_number') -> $v { $/.make( %handlers<decimal> ?? call-handler(%handlers<decimal>(nqp::p6box_s($v.Str))) !! $v.made ) } elsif atkeyish($/, 'rad_number') -> $v { $/.make( %handlers<radix> ?? call-handler(%handlers<radix>(nqp::p6box_s($v.Str))) !! $v.made ) } else { $/.make( %handlers<numish> ?? call-handler(%handlers<numish>(nqp::p6box_s($/.Str))) !! $*W.add_numeric_constant($/, 'Num', +nqp::p6box_s($/.Str)) ) } } } sub EXPORT(*@handlers) { my %handlers = @handlers.map({$_.name => $_}); $*LANG.refine_slang('MAIN', role {}, Numish[%handlers]); BEGIN Map.new } =begin pod =head1 NAME overload::constant - Change stringification behaviour of literals =head1 SYNOPSIS =begin code :lang<raku> use overload::constant; sub integer { "i$^a" } sub decimal { "d$^a" } sub radix { "r$^a" } sub numish { "n$^a" } use overload::constant &integer, &decimal, &radix, &numish; ok 42 ~~ Str && 42 eq 'i42', 'can overload integer'; ok 0.12 ~~ Str && 0.12 eq 'd0.12', 'can overload decimal'; ok .1e-003 ~~ Str && .1e-003 eq 'd.1e-003', 'can overload decimal in scientific notation'; ok :16<FF> ~~ Str && :16<FF> eq 'r:16<FF>', 'can overload radix'; ok NaN ~~ Str && NaN eq 'nNaN', 'can overload other numish things'; =end code =head1 DESCRIPTION It is meant to work a bit like Perl's L<overload::constant|https://perldoc.perl.org/overload#Overloading-Constants>, though it is kind of pre-alpha here. =head1 AUTHOR Tobias Leich =head1 COPYRIGHT AND LICENSE Copyright 2014 - 2017 Tobias Leich Copyright 2024 Raku Community This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0. =end pod # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: META6.json ### ---------------------------------------------------- { "depends": [ "p6-GLib", "p6-GIO" ], "description": "Perl6 library bindings for GNOME's JSON-GLib library", "version": "r0.1", "meta-version": "0", "license": "GPL-3.0", "source-url": "https://github.com/Xliff/p6-JSON-GLib.git", "provides": { "JSON::GLib::Raw::Definitions" : "lib/JSON/GLib/Raw/Definitions.pm6" , "JSON::GLib::Raw::Generator" : "lib/JSON/GLib/Raw/Generator.pm6" , "JSON::GLib::Raw::ObjectNodeArray" : "lib/JSON/GLib/Raw/ObjectNodeArray.pm6" , "JSON::GLib::Raw::Parser" : "lib/JSON/GLib/Raw/Parser.pm6" , "JSON::GLib::Raw::Path" : "lib/JSON/GLib/Raw/Path.pm6" , "JSON::GLib::Raw::Reader" : "lib/JSON/GLib/Raw/Reader.pm6" , "JSON::GLib::Raw::Exports" : "lib/JSON/GLib/Raw/Exports.pm6" , "JSON::GLib::Raw::Types" : "lib/JSON/GLib/Raw/Types.pm6" , "JSON::GLib::Roles::Signals::Parser" : "lib/JSON/GLib/Roles/Signals/Parser.pm6" , "JSON::GLib::Node" : "lib/JSON/GLib/Node.pm6" , "JSON::GLib::Parser" : "lib/JSON/GLib/Parser.pm6" , "JSON::GLib::Path" : "lib/JSON/GLib/Path.pm6" , "JSON::GLib::Raw::Builder" : "lib/JSON/GLib/Raw/Builder.pm6" , "JSON::GLib::Reader" : "lib/JSON/GLib/Reader.pm6" , "JSON::GLib::Variant" : "lib/JSON/GLib/Variant.pm6" , "JSON::GLib::Array" : "lib/JSON/GLib/Array.pm6" , "JSON::GLib::Builder" : "lib/JSON/GLib/Builder.pm6" , "JSON::GLib::Generator" : "lib/JSON/GLib/Generator.pm6" , "JSON::GLib::Object" : "lib/JSON/GLib/Object.pm6" }, "name": "p6-JSON-GLib", "perl": "6.c", "test-depends": ["Test::META"], "build-depends": [ ], "support": {"source": null}, "authors": ["[email protected]"] }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/10-reader.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Parser; use JSON::GLib::Reader; my $base_array = '[ 0, true, null, "foo", 3.14, [ false ], { "bar" : 42 } ]'; my $base_object = '{ "text" : "hello, world!", "foo" : null, "blah" : 47, "double" : 42.47 }'; my $reader_level = ' { "list": { "181195771": { "given_url": "http://www.gnome.org/json-glib-test" } } }'; # https://bugzilla.gnome.org/show_bug.cgi?id=758580 my $null_value = '{ "v": null }'; my @expected_member_name = <text foo blah double>; subtest 'Base Object', { my ($p, $r) = (JSON::GLib::Parser, JSON::GLib::Reader)».new; $p.load-from-data($base_object); nok $ERROR, 'No errors detected from parser'; $r.root = $p.root; ok $r.is-object, 'Reader currently points to an OBJECT'; is $r.m-elems, 4, 'OBJECT on reader currently has the proper number of members'; my @m = $r.members; ok +@m > 0, 'Members list contains elements'; for @m.kv -> $k, $v { is $v, @expected_member_name[$k], "Member ⌗{ $k } matches expected name of '{ @expected_member_name[$k] }'"; } ok $r.read-member('text'), q«Can read data from the 'text' member»; ok $r.is-value, q«Value associated with the 'text' member is a VALUE»; is $r.string, 'hello, world!', 'Text member contains the proper value'; $r.end-member; nok $r.read-member('bar'), q«Can NOT read data from the 'bar' member»; ok (my $e = $r.get-error), 'Can retrieve error from reader'; ok $e.domain == JSON::GLib::Reader.error, 'Error domain is JSON_READER_ERROR'; ok $e.code == JSON_READER_ERROR_INVALID_MEMBER, 'Error codfe is JSON_READER_ERROR_INVALID_MEMBER'; $r.end-member; nok $r.get-error, 'Error value cleared after call to .end-member'; ok $r.read-element(2), 'Can read 2nd element from reader'; is $r.member, 'blah', q«Member name is 'blah'»; ok $r.is-value, 'Current member is a VALUE element'; is $r.int, 47, 'Current member contains the proper integer value'; $r.end-member; nok $r.get-error, 'Error value cleared after call to .end-member'; $r.read-member('double'); ok $r.double =~= 42.47, q«Double value retrieved from member 'double' matches expected value»; $r.end-member; } subtest 'Base Array', { my ($p, $r) = (JSON::GLib::Parser, JSON::GLib::Reader)».new; $p.load-from-data($base_array); nok $ERROR, 'No errors detected from parser'; $r.root = $p.root; ok $r.is-array, 'Reader currently points to an ARRAY'; is $r.elems, 7, 'ARRAY on reader currently has the proper number of members'; $r.read-element(0); ok $r.is-value, 'Element 0 is a VALUE type'; is $r.int, 0, 'Element 0 contains the proper value'; $r.end-element; $r.read-element(1); ok $r.is-value, 'Element 1 is a VALUE type'; is $r.bool, True, 'Element 1 contains the proper value'; $r.end-element; $r.read-element(3); ok $r.is-value, 'Element 3 is a VALUE type'; is $r.string, 'foo', 'Element 3 contains the proper value'; $r.end-element; $r.read-element(5); $r.is-value, 'Element 5 IS NOT a VALUE type'; nok $r.is-object, 'Element 5 IS NOT an OBJECT type'; ok $r.is-array, 'Element 5 is an ARRAY type'; $r.end-element; $r.read-element(6); ok $r.is-object, 'Element 6 is an OBJECT type'; $r.read-member('bar'); ok $r.is-value, q«Element 6, member 'bar' is a VALUE type»; is $r.int,   42, q«Element 6, member 'bar' contains the correct value»; $r.end-member; $r.end-element; nok $r.read-element(7), 'Element 7 cannot be read'; my $e = $r.get-error; is $e.domain, JSON::GLib::Reader.error, 'ERROR contains the proper domain'; is $e.code, JSON_READER_ERROR_INVALID_INDEX.Int, 'ERROR contains the proper code'; $r.end-element; my $e = $r.get-error; nok $e, 'ERROR cleared after call to .end-element'; } subtest 'Reader Level', { my ($p, $r) = (JSON::GLib::Parser, JSON::GLib::Reader)».new; $p.load-from-data($reader_level); nok $ERROR, 'No errors detected from parser'; $r.root = $p.root; ok $r.m-elems > 0, 'Reader contains at least one member'; ok $r.read-member('list'), q«Can read from member 'list'»; is $r.member, 'list', q«Can confirm that current member is called 'list'»; ok (my $members = $r.list-members), 'Member list is NOT Nil'; ok $r.read-member('181195771'), q«Can read from member '181195771'»; is $r.member, '181195771', q«Can confirm that current member is called '181195771'»; nok $r.read-member('resolved_url'), q«Can NOT read from member 'resolved_url'»; nok $r.member, 'Current member name is Nil'; $r.end-member; is $r.member, '181195771', q«Current member is called '181195771', after call to .end-member»; ok $r.read-member('given_url'), q«Can read from member 'given_url'»; is $r.member, 'given_url', q«Can confirm that current member is 'given_url'»; is $r.string, 'http://www.gnome.org/json-glib-test', 'String value at current node matches expected value'; $r.end-member; is $r.member, '181195771', q«Current member is called '181195771', after call to .end-member»; $r.end-member; is $r.member, 'list', q«Current member is called 'list', after call to .end-member»; $r.end-member; nok $r.member, 'Current member is undefined after call to .end-mamber'; } subtest 'Null Value', { my ($p, $r) = (JSON::GLib::Parser, JSON::GLib::Reader)».new; $p.load-from-data($reader_level); nok $ERROR, 'No errors detected from parser'; $p.load-from-data($null_value); nok $ERROR, 'No errors detected from parser'; $r.root = $p.root; $r.read-member('v'); ok $r.is-value, 'Current reader state points to a VALUE'; nok $r.get-error, 'No error queued in reader'; ok $r.get-value, 'Reader returns a non-Nil value'; }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/09-path.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Generator; use JSON::GLib::Parser; use JSON::GLib::Path; my $json = q:to/JSON/; { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": "8.95" }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": "12.99" }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": "8.99" }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": "22.99" } ], "bicycle": { "color": "red", "price": "19.95" } } } JSON my @expressions = ( { desc => 'INVALID: invalid first character', expr => '/', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY }, { desc => 'INVALID: Invalid character following root', expr => '$ponies', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'INVALID: missing member name or wildcard after dot', expr => '$.store.', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'INVALID: Malformed slice (missing step)', expr => '$.store.book[0:1:]', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'INVALID: Malformed set', expr => '$.store.book[0,1~2]', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'INVALID: Malformed array notation', expr => q«${'store'}», is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'INVALID: Malformed slice (invalid separator)', expr => '$.store.book[0~2]', is-valid => False, error-code => JSON_PATH_ERROR_INVALID_QUERY, }, { desc => 'Title of the first book in the store, using objct notation.', expr => '$.store.book[0].title', res => '["Sayings of the Century"]', is-valid => True, }, { desc => 'Title of the first book in the store, using array notation.', expr => q«$['store']['book'][0]['title']», res => '["Sayings of the Century"]', is-valid => True, }, { desc => 'All the authors from the every book.', expr => '$.store.book[*].author', res => '["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]', is-valid => True, }, { desc => 'All the authors.', expr => '$..author', res => '["Nigel Rees","Evelyn Waugh","Herman Melville","J. R. R. Tolkien"]', is-valid => True, }, { desc => 'Everything inside the store.', expr => '$.store.*', is-valid => True, }, { desc => 'All the prices in the store.', expr => '$.store..price', res => '["8.95","12.99","8.99","22.99","19.95"]', is-valid => True, }, { desc => 'The third book.', expr => '$..book[2]', res => '[{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":"8.99"}]', is-valid => True, }, { desc => 'The last book.', expr => '$..book[-1:]', res => '[{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":"22.99"}]', is-valid => True, }, { desc => 'The first two books.', expr => '$..book[0,1]', res => '[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":"8.95"},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":"12.99"}]', is-valid => True, }, { desc => 'The first two books, using a slice.', expr => '$..book[:2]', res => '[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":"8.95"},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":"12.99"}]', is-valid => True, }, { desc => 'All the books.', expr => q«$['store']['book'][*]», res => '[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":"8.95"},{"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":"12.99"},{"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":"8.99"},{"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":"22.99"}]', is-valid => True, }, { desc => 'All the members of the bicycle object.', expr => '$.store.bicycle.*', res => '["red","19.95"]', is-valid => True, }, { desc => 'The root node.', expr => '$', res => q« [{"store":{"book":[{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":"8.95"}, {"category":"fiction","author":"Evelyn Waugh","title":"Sword of Honour","price":"12.99"}, {"category":"fiction","author":"Herman Melville","title":"Moby Dick","isbn":"0-553-21311-3","price":"8.99"}, {"category":"fiction","author":"J. R. R. Tolkien","title":"The Lord of the Rings","isbn":"0-395-19395-8","price":"22.99"}], "bicycle":{"color":"red","price":"19.95"}}}]».subst(/\s <!before \w>/, '', :g), is-valid => True, } ); sub path-expressions-valid ($k, $e) { my $p = JSON::GLib::Path.new; subtest "/path/expressions/valid/{ $k }", { diag "* { $e<desc> } ('{ $e<expr> }')"; ok $p.compile($e<expr>), 'Path compiles'; nok $ERROR, 'No error detected'; } } sub path-expressions-invalid ($k, $e) { my $p = JSON::GLib::Path.new; subtest "/path/expressions/invalid/{ $k }", { diag "* { $e<desc> } ('{ $e<expr> }')"; nok $p.compile($$e<expr>), 'Path DOES NOT compile'; ok $ERROR, 'An error was detected'; diag $ERROR.gist; is $ERROR.domain, JSON::GLib::Path.error, 'Error domain is JSON_PATH_ERROR'; # cw: Disabled test. For some reason routines are not setting GError.code! #is $ERROR.code, $e<error-code>, "Error code is { $e<errror-code> }"; } } sub path-match ($e) { my ($p, $g, $path) = (JSON::GLib::Parser, JSON::GLib::Generator, JSON::GLib::Path)».new; $p.load-from-data($json); my $root = $p.root; ok $path.compile($e<expr>), 'Path compiles'; my $matches = $path.match($root); is $matches.node-type, JSON_NODE_ARRAY, '.match method returns a node of type ARRAY'; $g.root = $matches; is ~$g, $e<res>, 'Round trip JSON object matches expected data'; } for @expressions.kv -> $k, $v { next unless $v<is-valid>; path-expressions-valid($k, $v); } for @expressions.kv -> $k, $v { next if $v<is-valid>; path-expressions-invalid($k, $v); } subtest 'Path Matching', { for @expressions.kv -> $k, $v { next unless $v<res>; path-match($v); } }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/02-builder.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Builder; use JSON::GLib::Generator; my $complex-object = '{' ~ '"depth1":[' ~ '1,' ~ '{"depth2":' ~ '[' ~ '3,' ~ '[null,false],' ~ '"after array"' ~ '],' ~ '"value2":true' ~ '}' ~ '],' ~ '"object1":{},' ~ '"value3":null,' ~ '"value4":42,' ~ '"":54' ~ '}'; my $empty-object = '{"a":{}}'; my $reset-object = '{"test":"reset"}'; my $reset-array = '["reset"]'; subtest 'Complex', { with (my $b = JSON::GLib::Builder.new) { .begin-object .set-member-name('depth1').begin-array .add(1) .begin-object .set-member-name('depth2').begin-array .add(3) .begin-array .add .add(False) .end-array .add('after array') .end-array .set-member-name('value2').add(True) .end-object .end-array .set-member-name('object1').begin-object.end-object .set-member-name('value3').add .set-member-name('value4').add(42) .set-member-name('').add(54) .end-object } my $g = JSON::GLib::Generator.new; $g.root = $b.root; my $d = $g.to-data; is $d, $complex-object, 'Serialized data is equivalent to string definition'; } subtest 'Empty', { with (my $b = JSON::GLib::Builder.new) { .begin-object .set-member-name('a').begin-object.end-object .end-object } my $g = JSON::GLib::Generator.new; $g.root = $b.root; my $d = $g.to-data; is $d, $empty-object, 'Serialized data is equivalent to string definition'; } subtest 'Reset', { with (my $b = JSON::GLib::Builder.new) { .begin-object .set-member-name('test').add('reset') .end-object } my $g = JSON::GLib::Generator.new; $g.root = $b.root; my $d = $g.to-data; is $d, $reset-object, "Serialized data is equivalent to string definition 1"; $b.reset.begin-array.add('reset').end-array; $g = JSON::GLib::Generator.new; $g.root = $b.root; $d = $g.to-data; is $d, $reset-array, "Serialized data after reset is equivalent to string definition 2"; }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/04-variant.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use GLib::Variant; use JSON::GLib::Variant; my @two-way-test-cases = ( { name => '/boolean', sig => '(b)', vdata => '(true,)', jdata => '[true]' }, { name => "/byte", sig => "(y)", vdata => "(byte 0xff,)", jdata => "[255]" }, { name => "/int16", sig => "(n)", vdata => "(int16 -12345,)", jdata => "[-12345]" }, { name => "/uint16", sig => "(q)", vdata => "(uint16 40001,)", jdata => "[40001]" }, { name => "/int32", sig => "(i)", vdata => "(-7654321,)", jdata => "[-7654321]" }, { name => "/uint32", sig => "(u)", vdata => "(uint32 12345678,)", jdata => "[12345678]" }, { name => "/int64", sig => "(x)", vdata => "(int64 -666999666999,)", jdata => "[-666999666999]" }, { name => "/uint64", sig => "(t)", vdata => "(uint64 1999999999999999,)", jdata => "[1999999999999999]" }, { name => "/handle", sig => "(h)", vdata => "(handle 1,)", jdata => "[1]" }, { name => "/double", sig => "(d)", vdata => "(1.23,)", jdata => "[1.23]" }, { name => "/double-whole", sig => "(d)", vdata => "(123.0,)", jdata => "[123.0]" }, { name => "/string", sig => "(s)", vdata => "('hello world!',)", jdata => "[\"hello world!\"]" }, { name => "/object-path", sig => "(o)", vdata => "(objectpath '/org/gtk/json_glib',)", jdata => "[\"/org/gtk/json_glib\"]" }, { name => "/signature", sig => "(g)", vdata => "(signature '(asna\{sv\}i)',)", jdata => "[\"(asna\{sv\}i)\"]" }, { name => "/maybe/simple/null", sig => "(ms)", vdata => "(\@ms nothing,)", jdata => "[null]" }, { name => "/maybe/simple/string", sig => "(ms)", vdata => "(\@ms 'maybe string',)", jdata => "[\"maybe string\"]" }, { name => "/maybe/container/null", sig => "(m(sn))", vdata => "(\@m(sn) nothing,)", jdata => "[null]" }, { name => "/maybe/container/tuple", sig => "(m(sn))", vdata => "(\@m(sn) ('foo', 0),)", jdata => "[[\"foo\",0]]" }, { name => "/maybe/variant/boolean", sig => "(mv)", vdata => "(\@mv <true>,)", jdata => "[true]" }, { name => "/array/empty", sig => "as", vdata => "\@as []", jdata => "[]" }, { name => "/array/byte", sig => "ay", vdata => "[byte 0x01, 0x0a, 0x03, 0xff]", jdata => "[1,10,3,255]" }, { name => "/array/string", sig => "as", vdata => "['a', 'b', 'ab', 'ba']", jdata => "[\"a\",\"b\",\"ab\",\"ba\"]" }, { name => "/array/array/int32", sig => "aai", vdata => "[[1, 2], [3, 4], [5, 6]]", jdata => "[[1,2],[3,4],[5,6]]" }, { name => "/array/variant", sig => "av", vdata => "[<true>, <int64 1>, <'oops'>, <int64 -2>, <0.5>]", jdata => "[true,1,\"oops\",-2,0.5]" }, { name => "/tuple", sig => "(bynqiuxthds)", vdata => "(false, byte 0x00, int16 -1, uint16 1, -2, uint32 2, int64 429496729, uint64 3, handle 16, 2.48, 'end')", jdata => "[false,0,-1,1,-2,2,429496729,3,16,2.48,\"end\"]" }, { name => "/dictionary/empty", sig => 'a{sv}', vdata => '@a{sv} {}', jdata => '{}' }, { name => "/dictionary/single-entry", sig => '{ss}', vdata => "\{'hello', 'world'\}", jdata => '{"hello":"world"}' }, { name => "/dictionary/string-int32", sig => "a\{si\}", vdata => "\{'foo': 1, 'bar': 2\}", jdata => "\{\"foo\":1,\"bar\":2}" }, { name => "/dictionary/string-variant", sig => "a\{sv\}", vdata => "\{'str': <'hi!'>, 'bool': <true>\}", jdata => "\{\"str\":\"hi!\",\"bool\":true}" }, { name => "/dictionary/int64-variant", sig => "a\{xv\}", vdata => "\{int64 -5: <'minus five'>, 10: <'ten'>\}", jdata => "\{\"-5\":\"minus five\",\"10\":\"ten\"\}" }, { name => "/dictionary/uint64-boolean", sig => "a\{tb\}", vdata => "\{uint64 999888777666: true, 0: false\}", jdata => "\{\"999888777666\":true,\"0\":false}" }, { name => "/dictionary/boolean-variant", sig => "a\{by\}", vdata => "\{true: byte 0x01, false: 0x00\}", jdata => "\{\"true\":1,\"false\":0\}" }, { name => "/dictionary/double-string", sig => "a\{ds\}", vdata => "\{1.0: 'one point zero'\}", jdata => "\{\"1.000000\":\"one point zero\"\}" }, { name => "/variant/string", sig => "(v)", vdata => "(<'string within variant'>,)", jdata => "[\"string within variant\"]" }, { name => "/variant/maybe/null", sig => "(v)", vdata => "(<\@mv nothing>,)", jdata => "[null]" }, { name => "/variant/dictionary", sig => "v", vdata => "<\{'foo': <'bar'>, 'hi': <int64 1024>\}>", jdata => "\{\"foo\":\"bar\",\"hi\":1024\}" }, { name => "/variant/variant/array", sig => "v", vdata => "<[<'any'>, <'thing'>, <int64 0>, <int64 -1>]>", jdata => "[\"any\",\"thing\",0,-1]" }, { name => "/deep-nesting", sig => "a(a(a(a(a(a(a(a(a(a(s))))))))))", vdata => "[([([([([([([([([([('sorprise',)],)],)],)],)],)],)],)],)],)]", jdata => "[[[[[[[[[[[[[[[[[[[[\"sorprise\"]]]]]]]]]]]]]]]]]]]]" }, { name => "/mixed1", sig => "a\{s(syba(od))\}", vdata => "\{'foo': ('bar', byte 0x64, true, [(objectpath '/baz', 1.3), ('/cat', -2.5)])\}", jdata => "\{\"foo\":[\"bar\",100,true,[[\"/baz\",1.3],[\"/cat\",-2.5]]]\}" }, { name => "/mixed2", sig => "(a\{by\}amsvmaba\{qm(sg)\})", vdata => "(\{true: byte 0x01, false: 0x00}, [\@ms 'do', nothing, 'did'], <\@av []>, \@mab nothing, \{uint16 10000: \@m(sg) ('yes', 'august'), 0: nothing\})", jdata => "[\{\"true\":1,\"false\":0},[\"do\",null,\"did\"],[],null,\{\"10000\":[\"yes\",\"august\"],\"0\":null\}]" } ); my @json_to_gvariant_test_cases = ( { name => '/string-to-boolean', sig => '(b)', vdata => '(true,)', jdata => "[\"true\"]" }, { name => '/string-to-byte', sig => '(y)', vdata => '(byte 0xff,)', jdata => "[\"255\"]" }, { name => '/string-to-int16', sig => '(n)', vdata => '(int16 -12345,)', jdata => "[\"-12345\"]" }, { name => '/string-to-uint16', sig => '(q)', vdata => '(uint16 40001,)', jdata => "[\"40001\"]" }, { name => '/string-to-int32', sig => '(i)', vdata => '(-7654321,)', jdata => "[\"-7654321\"]" }, { name => '/string-to-int64', sig => '(x)', vdata => '(int64 -666999666999,)', jdata => "[\"-666999666999\"]" }, { name => '/string-to-uint64', sig => '(t)', vdata => '(uint64 1999999999999999,)', jdata => "[\"1999999999999999\"]" }, { name => '/string-to-double', sig => '(d)', vdata => '(1.23,)', jdata => "[\"1.23\"]" }, { name => '/string-to-double-whole', sig => '(d)', vdata => '(123.0,)', jdata => "[\"123.0\"]" } ); sub gvariant-to-json ($test) { my $v = GLib::Variant.parse($test<sig>, $test<vdata>); #my $d = JSON::GLib::Variant.serialize($v); #ok $d, 'Variant data can be serialized'; my $jd = JSON::GLib::Variant.serialize-data($v); is $jd.chars, $test<jdata>.chars, 'Serialized data is the proper length'; is $jd, $test<jdata>, 'Serialized data matches expected result'; } sub json-to-gvariant ($test) { my $v = JSON::GLib::Variant.deserialize-data($test<jdata>, $test<sig>); my $vd = $v.print; ok $v, 'JSON data can be deserialized'; is $vd, $test<vdata>, 'Deserialized data is correct' } for @two-way-test-cases { subtest "/gvariant/to-json{ .<name> }", { gvariant-to-json($_) } } for @two-way-test-cases { subtest "/gvariant/from-json{ .<name> }", { json-to-gvariant($_) } } for @json_to_gvariant_test_cases { subtest "/gvariant/from-json{ .<name> }", { json-to-gvariant($_) } }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/stream-load.json ### ---------------------------------------------------- [ { "hello" : "world!\n" } ]
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/07-object.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Node; use JSON::GLib::Object; subtest 'Empty Object', { my $o = JSON::GLib::Object.new; is $o.size, 0, 'Object has no members at start'; nok $o.get-members, 'Object members list returns Falsy'; } subtest 'Add Member', { my $o = JSON::GLib::Object.new; my $n = JSON::GLib::Node.new( :null ); is $o.size, 0, 'Object has no members at start'; $o.set-member('Null', $n); is $o.size, 1, 'Object has 1 member after adding Null => Nil'; my $no = $o.get-member('Null'); is $no.node-type, JSON_NODE_NULL, "Value at member 'Null' is undefined"; } subtest 'Set Member', { my $o = JSON::GLib::Object.new; my $n = JSON::GLib::Node.init-string('Hello'); is $o.size, 0, 'Object has no members at start'; $o.set-member('String', $n); is $o.size, 1, "Object has 1 member after adding 'String' => 'Hello' "; $n = $o.get-member('String'); is $n.node-type, JSON_NODE_VALUE, "Retrieved node from 'String' is a VALUE node"; is $n.string, 'Hello', "Value node contains the value 'Hello'"; $n.string = 'World'; diag 'After setting node contents to "World"'; is $n.node-type, JSON_NODE_VALUE, "Retrieved node from 'String' is a VALUE node"; is $n.string, 'World', "Value node contains the value 'World'"; diag 'After setting node contents to "Goodbye"'; $n.string = 'Goodbye'; is $n.string, 'Goodbye', "Value node contains the value 'Goodbye'"; diag 'NULL content checks'; $o.set-member('Array', JsonArray); $n = $o.get-member('Array'); is $n.node-type, JSON_NODE_NULL, "Retrieved node from 'Array' is a NULL node"; $o.set-member('Object', JsonObject); $n = $o.get-null-member('Object'); ok $n, "Retrieved node from 'Object' is a NULL node"; $o.set-member('', Nil); $n = $o.get-null-member(''); ok $n, "Retrieved node from 'Object' is a NULL node"; } # Skipping test_get_member_default as routines now deprecated! subtest 'Remove Member', { my $o = JSON::GLib::Object.new; my $n = JSON::GLib::Node.new(JSON_NODE_NULL); $o.set-member('Null', $n); $o.remove-member('Null'); is $o.size, 0, 'Object has no members after Add/Remove operation'; } sub create-test-object { my $o = JSON::GLib::Object.new; $o.set_member(.[0], .[1]) for ('integer', 42), ('boolean', True), ('string', 'hello'), ('double', 3.14159), ('null', Nil), ('', 0); $o; } { use NativeCall; use GLib::Roles::Pointers; class TestForeachFixture is repr<CStruct> does GLib::Roles::Pointers { has gint $.n-members is rw; } my %verify = ( integer => { type => JSON_NODE_VALUE, gtype => G_TYPE_INT64.Int }, boolean => { type => JSON_NODE_VALUE, gtype => G_TYPE_BOOLEAN.Int }, string => { type => JSON_NODE_VALUE, gtype => G_TYPE_STRING.Int }, double => { type => JSON_NODE_VALUE, gtype => G_TYPE_DOUBLE.Int }, null => { type => JSON_NODE_NULL, gtype => G_TYPE_INVALID.Int }, '' => { type => JSON_NODE_VALUE, gtype => G_TYPE_INT64.Int } ); sub verify-foreach ($o, $mn, $n is copy, $ud is copy) { CATCH { default { .message.say } } $n = JSON::GLib::Node.new($n); $ud = cast(TestForeachFixture, $ud); is $n.node-type, %verify{$mn}<type>, "Node type '$mn' matches type of " ~ %verify{$mn}<type>; is $n.value-type, %verify{$mn}<gtype>, "Node GType '$mn' matches type of " ~ %verify{$mn}<gtype>; $ud.n-members++; } subtest 'Test Foreach', { my $o = create-test-object; my $f = TestForeachFixture.new; $o.foreach-member(&verify-foreach, $f.p); is $f.n-members, $o.size, 'Iterated proper number of times through foreach!'; } subtest 'Test Iter', { my $i = (my $o = create-test-object).iter; my $f = TestForeachFixture.new; while $i.next -> $io { verify-foreach($o, $io[0], $io[1].JsonNode, $f.p) } is $f.n-members, $o.size, 'Iterated proper number of times through foreach!'; } } subtest 'Empty Member', { my $o = JSON::GLib::Object.new; $o.set-string-member('string', ''); ok $o.has-member('string'), 'Object retains null member "string"'; is $o.get-string-member('string'), '', 'Member "string" is the null string'; $o.set-string-member('null', Str); ok $o.has-member('null'), "Object retains null member 'null'"; is $o.get-string-member('null'), Str, 'Member "null" is Nil'; $o.set-null-member('array'); is $o.get-array-member('array'), Nil, 'Member "array" is Nil'; $o.set-object-member('object', JsonObject); ok $o.get-member('object'), "Retrieved member 'object' is NOT Nil"; is $o.get-object-member('object'), Nil, 'Retrieved object member is Nil' }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/01-array.t ### ---------------------------------------------------- use v6.c; use Test; use GLib::GList; use JSON::GLib::Raw::Types; use JSON::GLib::Array; use JSON::GLib::Node; use JSON::GLib::Object; subtest 'Empty Array', { my $a = JSON::GLib::Array.new; is $a.elems, 0, 'Array count is 0'; nok $a.elements, 'Array has no elements'; } subtest 'Adding Array elements', { my $a = JSON::GLib::Array.new; my $n = JSON::GLib::Node.new(JSON_NODE_NULL); is $a.elems, 0, 'Starting with an empty array'; $a.add-element($n); is $a.elems, 1, 'Array contains one element'; $n = $a[0]; is $n.node-type, JSON_NODE_NULL, 'First element is a NULL node'; $a.add-int-element(42); is $a.elems, 2, 'Array contains two elements'; is $a.get-int-element(1), 42, 'Array[1] is 42'; $a.add-double-element(3.14); is $a.elems, 3, 'Array contains three elements'; ok $a.get-double-element(2) ≅ 3.14, 'Array[2] is 3.14 (within reason)'; $a.add-boolean-element(True); is $a.elems, 4, 'Array contains four elements'; ok $a.get-boolean-element(3), 'Array[3] contains a boolean True value'; $a.add-string-element("Hello"); is $a.elems, 5, 'Array contains five elements'; is $a.get-string-element(4), 'Hello', 'Array[4] contains the string "Hello"'; $a.add-string-element; nok $a.get-string-element(5), 'Array[5] is NULL'; ok $a.get-element(5).defined, 'Array[5] is not a NULL JsonNode'; ok $a.get-null-element(5), 'Array[5] contains a JsonNode that is NULL'; $a.add-array-element; nok $a.get-array-element(6), 'Array[6] contains a NULL element'; ok $a.get-null-element(6), '.get-null-element(6) also returns NULL'; $a.add-object-element(JSON::GLib::Object.new); ok $a.get-object-element(7), 'Array[7] does contains a non-NULL element'; $a.add-object-element; nok $a.get-object-element(8), 'Array[8] contains a NULL element'; ok $a.get-null-element(8), '.get-null-element(8) also returns NULL'; } subtest 'Removing Array elements', { my $a = JSON::GLib::Array.new; my $n = JSON::GLib::Node.new; $a.add-element($n); $a.remove-element(0); nok $a.elems, 'Array contains no elements after add+remove operation'; } { use NativeCall; class TestForeachFixture is repr<CStruct> { has GList $!elements; has gint $.n_elements is rw; has gint $.iterations is rw; method elements is rw { Proxy.new: FETCH => -> $ { $!elements }, STORE => -> $, GList() \l { $!elements := l }; } } my @type-verify = ( [ G_TYPE_INT64 , JSON_NODE_VALUE ], [ G_TYPE_BOOLEAN, JSON_NODE_VALUE ], [ G_TYPE_STRING , JSON_NODE_VALUE ], [ G_TYPE_INVALID, JSON_NODE_NULL ] ); subtest 'Test Foreach Elements', { my $a = JSON::GLib::Array.new; my $f = TestForeachFixture.new; $a.add($_) for 42, True, 'hello', Nil; my $e = $a.elements(:glist); $f.elements = $e.GList; ok $f.elements.defined, 'Array has elements'; $f.n_elements = $a.elems; is $f.n_elements, $e.elems, 'Fixture and element counts agree'; $f.iterations = 0; $a.foreach-element(-> *@a { # CATCH { default { .message.say } } my $fix-data = cast(TestForeachFixture, @a[* - 1]); my $list = GLib::GList.new($fix-data.elements); my $node = JSON::GLib::Node.new( @a[2] ); my $i = @a[1]; ok $list.find($node.JsonNode.p), "Found element in iteration { $i }"; is $node.node-type, @type-verify[$i][1], "Node types are correct in iteration { $i }"; is $node.value-type, @type-verify[$i][0].Int, "Value types are correct in iteration { $i }"; $fix-data.iterations++; }, cast(Pointer, $f) ); is $f.iterations, $f.n_elements, 'Went the proper number of iterations'; } }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/03-generator.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Array; use JSON::GLib::Generator; use JSON::GLib::Node; use JSON::GLib::Object; use JSON::GLib::Parser; constant LC_NUMERIC = 1; my $empty-array = '[]'; my $empty-object = '{}'; my $simple-array = '[true,false,null,42,"foo"]'; my $nested-array = '[true,[false,null],42]'; my $simple-object = '{"Bool1":true,"Bool2":false,"Null":null,"Int":42,"":54,"String":"foo"}'; # taken from the RFC 4627, Examples section my $nested-object = '{' ~ '"Image":{' ~ '"Width":800,' ~ '"Height":600,' ~ '"Title":"View from 15th Floor",' ~ '"Thumbnail":{' ~ '"Url":"http://www.example.com/image/481989943",' ~ '"Height":125,' ~ '"Width":"100"' ~ '},' ~ '"IDs":[116,943,234,38793]' ~ '}' ~ '}'; my @pretty-examples = ( "[\n]", "\{\n\}", "[\n" ~ "\ttrue,\n" ~ "\tfalse,\n" ~ "\tnull,\n" ~ "\t\"hello\"\n" ~ ']', "\{\n" ~ "\t\"foo\" : 42,\n" ~ "\t\"bar\" : true,\n" ~ "\t\"baz\" : null\n" ~ '}' ); my @decimal-separators = ( C => { sep => '.', matches => True }, de => { sep => ',', matches => False }, en => { sep => '.', matches => True }, fr => { sep => ',', matches => False } ); sub do-checks ($d, $m) { say "checking '$d' (expected '$m')" if %*ENV<JSON-GLIB-VERBOSE>; is $d.chars, $m.chars, 'Generated data is the expected length'; is $d, $m, 'Generated data is the proper serialization'; } subtest 'Empty Array', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_ARRAY); $root.take-array( JSON::GLib::Array.new ); $gen.root = $root; ($gen.pretty, $gen.indent) = (False, 0); $gen.indent-char = ' '; my $d = $gen.to-data; is $d.chars, $empty-array.chars, 'Generated data is the expected length'; is $d, $empty-array, 'Generated data is the proper serialization'; is $gen.pretty.so, False, 'Generator Pretty attribute set to False'; is $gen.indent, 0, 'Generator returns 0 indent level'; is $gen.indent-char, ' '.ord, 'Generator indent char is a space'; } subtest 'Empty Object', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_OBJECT); $root.take-object( JSON::GLib::Object.new ); ($gen.root, $gen.pretty) = ($root, False); do-checks($gen.to-data, $empty-object); } subtest 'Simple Array', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_ARRAY); my $array = JSON::GLib::Array.new(:sized, 5); $array.add($_) for True, False, Nil, 42, 'foo'; $root.take-array($array); ($gen.root, $gen.pretty) = ($root, False); do-checks(~$gen, $simple-array); } subtest 'Nested Array', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_ARRAY); my $array = JSON::GLib::Array.new(:sized, 3); $array.add(True); { my $nested = JSON::GLib::Array.new(:sized, 2); $nested.add($_) for False, Nil; $array.add($nested); } $array.add(42); $root.take-array($array); ($gen.root, $gen.pretty) = ($root, False); do-checks(~$gen, $nested-array); } subtest 'Simple Object', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_OBJECT); my $object = JSON::GLib::Object.new; $object.set-member(.key, .value) for Bool1 => True, Bool2 => False, Null => Nil, Int => 42, '' => 54, String => 'foo'; $root.take-object($object); ($gen.root, $gen.pretty) = ($root, False); my $d = ~$gen; do-checks(~$gen, $simple-object); } subtest 'Nested Object', { my $gen = JSON::GLib::Generator.new; my $root = JSON::GLib::Node.new(JSON_NODE_OBJECT); my $object = JSON::GLib::Object.new; $object.set-member(.key, .value) for Width => 800, Height => 600, Title => 'View from 15th Floor'; { my $nested = JSON::GLib::Object.new; $nested.set-member(.key, .value) for Url => 'http://www.example.com/image/481989943', Height => 125, Width => 100.Str; $object.set-member('Thumbnail', $nested); } { my $array = JSON::GLib::Array.new; $array.add($_) for 116, 943, 234, 38793; $object.set-member('IDs', $array); } my $nested = JSON::GLib::Object.new; $nested.set-member('Image', $object); $root.take-object($nested); ($gen.root, $gen.pretty) = ($root, 0); do-checks(~$gen, $nested-object); } subtest 'Decimal Separator', { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); my $gen = JSON::GLib::Generator.new; sub setlocale (int32, Str) returns Str is native { * } my $old-locale = setlocale(LC_NUMERIC, Str); ($n.double, $gen.root) = (3.14, $n); for @decimal-separators { setlocale(LC_NUMERIC, .key); my $s = ~$gen; say "DecimalSeparatorSubtest: value: { $n.double.fmt('%.2f') } - string '{ $s }'" if %*ENV<JSON-GLIB-VERBOSE>; ok $s, 'Generated string is defined'; is $s.contains( .value<sep> ), .value<matches>, "Separator for { .key } meets match requirement"; } setlocale(LC_NUMERIC, $old-locale); } subtest 'Double stays Double', { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); my $gen = JSON::GLib::Generator.new; ($n.double, $gen.root) = (1, $n); is ~$gen, '1.0', 'A double value returns a double-typed node.' } subtest 'Pretty', { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); my $gen = JSON::GLib::Generator.new; my $p = JSON::GLib::Parser.new; ($gen.pretty, $gen.indent, $gen.indent-char) = (True, 1, "\t"); for @pretty-examples { $p.load-from-data($_); my $root = $p.root; ok $root, "Root node for parsed '{ .subst(/\n/, '\\n', :g) }' is defined"; $gen.root = $root; do-checks(~$gen, $_); } } my @string-fixtures = ( [ 'abc', '"abc"' ], [ "a\x7fxc", "\"a\\u007fxc\"" ], [ "a{ 0o033.chr }xc", "\"a\\u001bxc\"" ], [ "a\nxc", "\"a\\nxc\"" ], [ "a\\xc", "\"a\\\\xc\"" ], #[ "Barney B\303\244r", "\"Barney B\303\244r\"" ] [ "Barney B\xc3\xa4r", "\"Barney B\xc3\xa4r\"" ] ); subtest 'String Encode', { for @string-fixtures { my $gen = JSON::GLib::Generator.new; my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.string = .[0]; $gen.root = $n; diag .map( *.subst(/\n/, '\\n', :g) ).join('|'); do-checks(~$gen, .[1]); } }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/08-parser.t ### ---------------------------------------------------- use v6.c; use Test; #use NativeCall; use JSON::GLib::Raw::Types; use GLib::MainLoop; use GLib::Unicode; use JSON::GLib::Node; use JSON::GLib::Object; use JSON::GLib::Parser; use GIO::Roles::GFile; my $empty-string = ''; my $empty-array = '[ ]'; my $empty-object = '{ }'; my @base-values = ( { val => 'null', type => JSON_NODE_NULL, gtype => G_TYPE_INVALID }, do { my %h = ( val => 42, type => JSON_NODE_VALUE, gtype => G_TYPE_INT64 ); %h<verify> = -> $n { $n.get-int == %h<val> }; %h }, do { my %h = ( val => True, type => JSON_NODE_VALUE, gtype => G_TYPE_BOOLEAN ); %h<verify> = -> $n { $n.get-bool == %h<val> }; %h }, do { my %h = ( val => '"string"', type => JSON_NODE_VALUE, gtype => G_TYPE_STRING ); %h<verify> = -> $n { $n.get-string eq %h<val>.substr(1, %h<val>.chars - 2) }; %h }, do { my %h = ( val => 10.2e3, type => JSON_NODE_VALUE, gtype => G_TYPE_DOUBLE ); %h<verify> = -> $n { $n.get-double =~= %h<val> }; %h }, do { my %h = ( val => -1, type => JSON_NODE_VALUE, gtype => G_TYPE_INT64 ); %h<verify> = -> $n { $n.get-int == %h<val> }; %h }, do { my %h = ( val => -3.14, type => JSON_NODE_VALUE, gtype => G_TYPE_DOUBLE ); %h<verify> = -> $n { $n.get-double =~= %h<val> }; %h } ); my @simple-arrays = ( { str => '[ true ]', len => 1, element => 0, type => JSON_NODE_VALUE, gtype => G_TYPE_BOOLEAN.Int }, { str => '[ true, false, null ]', len => 3, element => 2, type => JSON_NODE_NULL, gtype => G_TYPE_INVALID.Int }, { str => '[ 1, 2, 3.14, "test" ]', len => 4, element => 3, type => JSON_NODE_VALUE, gtype => G_TYPE_STRING.Int } ); my @nested-arrays = « '[ 42, [ ], null ]' '[ [ ], [ true, [ true ] ] ]' '[ [ false, true, 42 ], [ true, false, 3.14 ], "test" ]' '[ true, { } ]' '[ false, { "test" : 42 } ]' '[ { "test" : 42 }, null ]' '[ true, { "test" : 42 }, null ]' '[ { "channel" : "/meta/connect" } ]' »; my @simple-objects = ( { str => '{ "test" : 42 }', size => 1, member => 'test', type => JSON_NODE_VALUE, gtype => G_TYPE_INT64.Int }, { str => '{ "foo" : "bar", "baz" : null }', size => 2, member => 'baz', type => JSON_NODE_NULL, gtype => G_TYPE_INVALID.Int }, { str => '{ "name" : "", "state" : 1 }', size => 2, member => 'name', type => JSON_NODE_VALUE, gtype => G_TYPE_STRING.Int }, { str => '{ "channel" : "/meta/connect" }', size => 1, member => 'channel', type => JSON_NODE_VALUE, gtype => G_TYPE_STRING.Int }, { str => '{ "halign":0.5, "valign":0.5 }', size => 2, member => 'valign', type => JSON_NODE_VALUE, gtype => G_TYPE_DOUBLE.Int }, { str => '{ "" : "emptiness" }', size => 1, member => '', type => JSON_NODE_VALUE, gtype => G_TYPE_STRING.Int } ); my @nested-objects; @nested-objects.push: q:to/NESTED-OBJECT/.chomp; { "array" : [ false, "foo" ], "object" : { "foo" : true } } NESTED-OBJECT @nested-objects.push: q:to/NESTED-OBJECT/.chomp; { "type" : "ClutterGroup", "width" : 1, "children" : [ { "type" : "ClutterRectangle", "children" : [ { "type" : "ClutterText", "text" : "hello there" } ] }, { "type" : "ClutterGroup", "width" : 1, "children" : [ { "type" : "ClutterText", "text" : "hello" } ] } ] } NESTED-OBJECT my @assignments = ( { str => 'var foo = [ false, false, true ]', var => 'foo' }, { str => 'var bar = [ true, 42 ];', var => 'bar' }, { str => 'var baz = { "foo" : false }', var => 'baz' } ); # Need trailing comma, otherwise an implied .pairs is called on the Hash. my @unicode = ( { str => '{ "test" : "foo ' ~ chr(0x00e8) ~ '" }', member => 'test', match => 'foo è' }, ); subtest 'Empty with Parser', { sub test-empty-with-parser ($p) { unless $p.load-from-data($empty-string) { say "Error: { $ERROR.message }"; exit 1; } nok $p.get-root, 'Parser returned a NULL value for empty-string'; } my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; test-empty-with-parser($p); $p = JSON::GLib::Parser.new( :immutable ); isa-ok $p, JSON::GLib::Parser, 'Immutable Parser created successfully'; test-empty-with-parser($p); } subtest 'Base Value', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @base-values { unless $p.load-from-data( .<val>.lc.Str ) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } my $root = $p.root; ok $root, "'{ .<val> }' - root node was obtained successfully"; nok $root.parent, "'{ .<val> }' - root node has no parent"; is $root.node-type, .<type>, "'{ .<val> }' - root node is of the expected type"; ok .<verify>($root), "'{ .<val> }' - root node satisfies validation test" if .<verify>; } } subtest 'Empty Array', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; unless $p.load-from-data($empty-array) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } my $root = $p.root; ok $root, 'Root node was obtained successfully'; is $root.node-type, JSON_NODE_ARRAY, 'Root node is an ARRAY node'; nok $root.parent, 'Root node has no parent'; my $a = $root.get-array; ok $a, 'Array node at root is NOT Nil'; is $a.elems, 0, 'Array node has 0 length'; } subtest 'Simple Array', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @simple-arrays { unless $p.load-from-data( .<str> ) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } diag "'{ .<str> }'"; my $root = $p.root; ok $root, 'Root node was obtained successfully'; nok $root.parent, 'Root node has no parent'; my $arr = $root.get-array; ok $arr, 'Array node at root is NOT Nil'; is $arr.elems, .<len>, 'Parsed array length agrees with expected result'; my $n = $arr[ .<element> ]; ok $n, "Node at Element { .<element> } is NOT Nil"; is +$n.parent.JsonNode.p, +$root.JsonNode.p, 'Parent node is the root node'; is $n.node-type, .<type>, 'Node type agrees with expected result'; is $n.value-type, .<gtype>, 'Value type agrees with expected result'; } } subtest 'Nested Array', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @nested-arrays { unless $p.load-from-data($_) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } diag $_; my $root = $p.root; ok $root, 'Root node was obtained successfully'; nok $root.parent, 'Root node has no parent'; my $arr = $root.get-array; ok $arr.elems > 0, 'Array has a non-zero length'; } } { sub common-object-tests($p, $root is rw, $o is rw) { $root = $p.root; $o = $root.get-object; ok $root, 'Root node was obtained successfully'; nok $root.parent, 'Root node has no parent'; is $root.node-type, JSON_NODE_OBJECT, 'Root node is an OBJECT type'; ok $o, 'Object retrieved from root is NOT Nil'; } subtest 'Empty Object', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; unless $p.load-from-data($empty-object) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } my ($root, $o); common-object-tests($p, $root, $o); is $o.elems, 0, 'Object has no entries'; } subtest 'Simple Object', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @simple-objects { unless $p.load-from-data( .<str> ) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } diag .<str>; my ($root, $o); common-object-tests($p, $root, $o); is $o.elems, .<size>, 'Object contains the expected number of members'; my $n = $o.get-member( .<member> ); ok $n, "Member '{ .<member> }' retrieved successfully"; is +$n.parent.JsonNode.p, +$root.JsonNode.p, 'Node parent is the root node'; is $n.node-type, .<type>, "Node is the expected type ({ .<type> })"; is $n.value-type, .<gtype>, "Node's value is the expected type ({ .<gtype> })"; } } subtest 'Nested Objects', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @nested-objects { unless $p.load-from-data($_) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } diag $_; my ($root, $o); common-object-tests($p, $root, $o); ok $o.elems > 0, 'Object is not empty'; } } } subtest 'Assignment', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @assignments { unless $p.load-from-data( .<str> ) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } my $var; diag .<str>; ok $p.has-assignment($var), 'Parser properly detects assignment'; ok $var.chars, "Parser returns non-empty variable name of '{ $var }'"; is $var, .<var>, 'Parser variable name matches expected result'; } } subtest 'Unicode Escape', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; for @unicode { diag .<str>; unless $p.load-from-data( .<str> ) { diag "Error: { $ERROR.message }" if %*ENV<JSON_GLIB_VERBOSE>; exit 1; } my $root = $p.root; my $o = $root.get-object; ok $root, 'Root node was obtained successfully'; is $root.node-type, JSON_NODE_OBJECT, 'Root note is of OBJECT type'; ok $o, 'Object retrieved from root node is NOT Nil'; ok $o.elems > 0, 'Object contains at least 1 member'; my $mn = $o.get-member( .<member> ); is $mn.node-type, JSON_NODE_VALUE, "Member '{ .<member> }' is of VALUE type"; is $mn.string, .<match>, 'Member value matches expected result'; ok GLib::UTF8.validate($mn.string), 'Retrieved value is a valid utf-8 string'; } } subtest 'Stream Sync', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; my $fp = $*CWD.add('t').add('stream-load.json'); my $f = GIO::Roles::GFile.new_for_path($fp); my $s = $f.read; if $ERROR { say "Error! -- { $ERROR.message }"; exit 1; } ok $s, "Successfully opened stream to $fp"; $p.load-from-stream($s); if $ERROR { say "Error! -- { $ERROR.message }"; exit 1; } my $root = $p.root; ok $root, 'Root node was obtained successfully'; is $root.node-type, JSON_NODE_ARRAY, 'Root node is an ARRAY type'; my $a = $root.get-array; is $a.elems, 1, 'Array holds only 1 element'; my $o = (my $on = $a[0]).get-object; is $on.node-type, JSON_NODE_OBJECT, 'First element of the array is an OBJECT'; ok $o.has-member('hello'), "Object contains the member 'hello'"; } { sub check-stream-load-json ($p) { my $root = $p.root; ok $root, 'Root node from async load is NOT Nil'; is $root.node-type, JSON_NODE_ARRAY, 'Root node is an ARRAY'; my $array = $root.get-array; is $array.elems, 1, 'Array contains only 1 element'; my $on = $array[0]; is $on.node-type, JSON_NODE_OBJECT, 'First element of the array is an OBJECT'; my $o = $on.get-object; ok $o.has-member('hello'), 'Object has a member called "hello"'; } subtest 'Stream Async', { my $p = JSON::GLib::Parser.new; isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; my $fp = $*CWD.add('t').add('stream-load.json'); my $f = GIO::Roles::GFile.new_for_path($fp); my $s = $f.read; nok $ERROR, 'No error detected upon load'; ok $s, 'Stream initialized, successfully'; my $ml = GLib::MainLoop.new; $p.load-from-stream-async($s, -> $, $result, $ { CATCH { default { .message.say } } $p.load-from-stream-finish($result); check-stream-load-json($p); $ml.quit; }); $ml.run; } # cw: Not found in recent sources....removed? # subtest 'Load from Mapped', { # my $p = JSON::GLib::Parser.new; # isa-ok $p, JSON::GLib::Parser, 'Parser created successfully'; # # my $fp = $*CWD.add('t').add('stream-load.json'); # $p.load-from-mapped($fp.absolute); # nok $ERROR, 'Mapped file loaded with no error'; # check-stream-load-json($p); # } # # test_mapped_file_error # test_mapped_json_error }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/06-node.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use GLib::Value; use JSON::GLib::Node; use JSON::GLib::Object; my $n = JSON::GLib::Node.new(JSON_NODE_NULL); my $c = $n.copy; sub test-node-copy($t, $a = '', $v = Nil) { my $n = JSON::GLib::Node.new($t); $n."$a"() = $v if $a && $v; my $c = $n.copy; is $n.node-type, $c.node-type, "({ $t }) Node and copy have same node type "; is $n.value-type, $c.value-type, "({ $t }) Node and copy have same value type"; is $n.type-name, $c.type-name, "({ $t }) Node and copy have same type name "; } { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.int = 42; is $n.int, 42, 'JSON node can get and set int value' } { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.double = 3.14159; ok $n.double =~= 3.14159, 'JSON node can get and set a double value'; } { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.boolean = True; ok $n.boolean, 'JSON node can get and set a boolean value'; } { my $string = 'Hello World'; my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.string = $string; is $n.string, $string, 'JSON node can get and set a string value'; } { test-node-copy(JSON_NODE_NULL); test-node-copy(JSON_NODE_VALUE, 'string', 'hello'); } { my $n = JSON::GLib::Node.new(JSON_NODE_OBJECT); my $o = JSON::GLib::Object.new; my $v = JSON::GLib::Node.new(JSON_NODE_VALUE); $v.int = 42;; $o.set-member('answer', $v); $n.take-object($o); my $c = $n.copy; is $n.node-type, $c.node-type, 'Constructed object and copy are the same node type'; is +$n.object.JsonObject.p, +$c.object.JsonObject.p, 'Constructed object and copy have same contents'; } { my $n = JSON::GLib::Node.new(JSON_NODE_NULL); ok $n.is-null, 'JSON node holds null object'; is $n.node-type, JSON_NODE_NULL, 'JSON node has NULL node-type'; is $n.value-type, G_TYPE_INVALID.Int, 'JSON node has value type of INVALID'; is $n.type-name, 'NULL', 'JSON node has type-name of "NULL'; } { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.int = 0; is $n.int, 0, 'Node can set and get a value of 0'; nok $n.get-boolean, 'Node boolean value resolves to FALSE'; nok $n.is-null, 'Node is not null'; $n.int = 42; is $n.int, 42, 'Node can set and get a value of 42'; ok $n.double =~= 42, 'Node can retrieve the int value of 42 as a double'; ok $n.get-boolean, 'Node boolean value resolves to TRUE'; nok $n.is-null, 'Node is not null'; } { my $n = JSON::GLib::Node.new(JSON_NODE_VALUE); $n.double = 3.14; ok $n.double =~= 3.14, 'Node can set and get a value of 3.14'; is $n.int, 3, 'Node can retrieve the int value as 3'; ok $n.boolean, 'Node boolean value resolves to TRUE'; } # This test loses its value unless it is LOW LEVEL, hence the long way # 'round seen inside. { my ($n, $value) = ( JSON::GLib::Node.new(JSON_NODE_VALUE) ); sub test-value($v, $vt, $vn) { $value."$vn"() = $v; is $value.type, $vt, 'Value is of type ' ~ $vt; is $value."$vn"(), $v, 'Value is set to ' ~ $v; my $check = $n.value = $value; is $value.type, $check.type, 'Value and check-value have the same type'; is $value."$vn"(), $check."$vn"(), 'Value and check-value have the same value'; is $value.type, $vt, 'Check-value has a type of ' ~ $vt; is $check."$vn"(), $v, 'Check-value is set to ' ~ $v; } is $n.node-type, JSON_NODE_VALUE, 'Node has node-type of VALUE'; $value = GLib::Value.new(G_TYPE_INT64); test-value(42, G_TYPE_INT64, 'int64'); $value = GLib::Value.new(G_TYPE_STRING); test-value('Hello, World!', G_TYPE_STRING, 'string'); } { my ($n, $value) = ( JSON::GLib::Node.new(JSON_NODE_VALUE) ); is $n.node-type, JSON_NODE_VALUE, 'Created node has node-type of VALUE'; sub test-value-promote ($v, $pt, $o, $p) { $value."$o"() = $v; my $check = $n.value = $value; is $check.type, $pt, 'Checked-value has type of ' ~ $pt; is-approx $check.value, $v, 0.00001, 'Check-value has the appropriate value, within tolerance'; isnt $value.type, $check.type, 'Value and check-value DO NOT have matching types'; is-approx $value."$o"(), $check."$p"(), 0.00001, 'Value matches check-value, within tolerance'; } $value = GLib::Value.new(G_TYPE_INT); test-value-promote(42, G_TYPE_INT64, 'int', 'int64'); $value = GLib::Value.new(G_TYPE_FLOAT); test-value-promote(3.14159, G_TYPE_DOUBLE, 'float', 'double'); } sub init-node($v, :$all = False) { my $m = do given $v.WHAT { when Nil { 'null' } when Str { 'string' } when Num { 'double' } when Bool { 'boolean' } when Int { 'int' } # default { Can be an error condition } default { die "Unknown seal type '$_'" } } my $rv = JSON::GLib::Node."init-{ $m }"($v); $all.not ?? $rv !! ($rv, $m); } { sub test-seal ($v) { my ($n, $m) = init-node($v, :all); nok $n.is-immutable, "$m node starts off as immutable"; $n.seal; ok $n.is-immutable, "$m node immutable after .seal()"; } test-seal(1); test-seal(15.2); test-seal('hi there'); test-seal(Nil); { my $obj = JSON::GLib::Object.new( JSON::GLib::Node.new( :object ) ); my $n = JSON::GLib::Node.new($obj, :object); nok $n.is-immutable, 'Node starts off immutable'; nok $obj.is-immutable, 'Object starts off immutable'; $n.seal; ok $n.is-immutable, 'Node is immutable'; ok $obj.is-immutable, 'Object is immutable'; } { my $arr = JSON::GLib::Array.new( JSON::GLib::Node.new( :array ) ); my $n = JSON::GLib::Node.new($arr, :array); nok $n.is-immutable, 'Array Node starts off immutable'; nok $arr.is-immutable, 'Array Object starts off immutable'; $n.seal; ok $n.is-immutable, 'Node is immutable'; ok $arr.is-immutable, 'Object is immutable'; } } { sub test-immutable($v, $nv) { my ($e, $m); my $p = start { CATCH { when X::JSON::GLib::Node::NoSetImmutable { $e = $_ } } my $n; ($n, $m) = init-node($v, :all); $n.seal; $n."$m"() = $nv; } await $p; isa-ok $e, X::JSON::GLib::Node::NoSetImmutable, "Could not set immutable '$m' value"; } test-immutable(5, 1); test-immutable(True, False); test-immutable(5.6, 1.1); test-immutable('bonghits', 'asdasd'); { my $e; my $p = start { CATCH { when X::JSON::GLib::Node::NoSetImmutable { $e = $_ } } my $n = JSON::GLib::Node.init-int(5); $n.seal; $n.value = gv_int(50); } await $p; isa-ok $e, X::JSON::GLib::Node::NoSetImmutable, 'Could not set immutable GValue value'; } { my $e; my $p = start { CATCH { when X::JSON::GLib::Node::NoSetImmutable { $e = $_ } } my $n = JSON::GLib::Node.init-int(5); $n.seal; my ($mut, $imut) = JSON::GLib::Object.new xx 2; my ($pmut, $pimut) = ( JSON::GLib::Node.init-object($mut), JSON::GLib::Node.init-object($imut) ); $pimut.seal; $mut.set-member('test', $n); $n.parent = $pmut; $mut.remove-member('test'); $n.clear-parent; $n.parent = $pimut; } await $p; isa-ok $e, X::JSON::GLib::Node::NoSetImmutable, 'Could not set immutable object value'; } }
### ---------------------------------------------------- ### -- p6-JSON-GLib ### -- Licenses: GPL-3.0 ### -- Authors: [email protected] ### -- File: t/05-invalid.t ### ---------------------------------------------------- use v6.c; use Test; use JSON::GLib::Raw::Types; use JSON::GLib::Parser; sub test-specific-invalidity ($j, $c) { my $parser = JSON::GLib::Parser.new; isa-ok $parser, JSON::GLib::Parser, 'JSON::GLib::Parser can be instantiated'; my $res = $parser.load-from-data($j); nok $res, "JSON::GLib::Parser recognizes '{ $j }' as invalid"; is $ERROR.domain, JSON::GLib::Parser.error_quark, 'ERROR is in the proper domain'; is $ERROR.code, $c.Int, 'ERROR contains the proper code'; if %*ENV<JSON_GLIB_DEBUG> { diag "invalid data: '{ $j }'"; diag "expected error: { $ERROR.message }"; } } multi sub test-invalid ($j, 'bareword') { test-specific-invalidity($j, JSON_PARSER_ERROR_INVALID_BAREWORD); } multi sub test-invalid ($j, 'missing-comma') { test-specific-invalidity($j, JSON_PARSER_ERROR_MISSING_COMMA); } multi sub test-invalid ($j, 'trailing-comma') { test-specific-invalidity($j, JSON_PARSER_ERROR_TRAILING_COMMA); } multi sub test-invalid ($j) { my $parser = JSON::GLib::Parser.new; isa-ok $parser, JSON::GLib::Parser, 'JSON::GLib::Parser can be instantiated'; my $res = $parser.load-from-data($j); nok $res, "JSON::GLib::Parser recognizes '{ $j }' as invalid"; ok $ERROR, 'Global $ERROR is defined'; diag "expected error: { $ERROR.message }" if $*ENV<JSON-GLIB-DEBUG>; } my @tests = ( # Barewords [ 'bareword-1', 'rainbows' ], [ 'bareword-2', '[ unicorns ]' ], [ 'bareword-3', '{ \"foo\" : ponies }' ], [ 'bareword-4', '[ 3, 2, 1, lift_off ]' ], [ 'bareword-5', '{ foo : 42 }' ], # values [ 'values-1', '[ -false ]' ], # assignment [ 'assignment-1', 'var foo' ], [ 'assignment-2', 'var foo = no' ], [ 'assignment-3', 'var = true' ], [ 'assignment-4', 'var blah = 42:' ], [ 'assignment-5', 'let foo = true;'], # arrays [ 'array-1', '[ true, false' ], [ 'array-2', '[ true }' ], [ 'array-3', '[ "foo" : 42 ]' ], # objects [ 'object-1', '{ foo : 42 }' ], [ 'object-2', '{ 42 : "foo" }' ], [ 'object-3', '{ "foo", 42 }' ], [ 'object-4', '{ "foo" : 42 ]' ], [ 'object-5', '{ "blah" }' ], [ 'object-6', '{ "a" : 0 "b" : 1 }' ], [ 'object-7', '{ null: false }' ], # missing commas [ 'missing-comma-1', '[ true false ]' ], [ 'missing-comma-2', '{ "foo": 42 "bar": null }' ], # trailing commas [ 'trailing-comma-1', '[ true, ]' ], [ 'trailing-comma-2', '{ "foo" : 42, }' ] ); for @tests -> $t { given $t[0] { when .starts-with('bareword') { test-invalid($t[1], 'bareword') } when .starts-with('missing-comma') { test-invalid($t[1], 'missing-comma') } when .starts-with('trailing-comma') { test-invalid($t[1], 'trailing-comma') } default { test-invalid($t[1]) } } }
### ---------------------------------------------------- ### -- pack6 ### -- Licenses: MIT ### -- Authors: Loren ### -- File: META6.json ### ---------------------------------------------------- { "auth": "github:araraloren", "depends": [ "JSON::Fast", "Compress::Zlib", "Getopt::Advance", "File::Directory::Tree", "File::Which" ], "description": "An tools can easily create CPAN tarball for you!", "resources": [], "version": "0.4", "license": "MIT", "source-url": "https://github.com/araraloren/raku-pack6", "provides": { "CPAN::Pack6": "lib/CPAN/Pack6.rakumod", "CPAN::Tar": "lib/CPAN/Tar.rakumod", "CPAN::Convert": "lib/CPAN/Convert.rakumod" }, "name": "pack6", "perl": "6.*", "test-depends": [], "build-depends": [], "support": { "bugtracker": "https://github.com/araraloren/raku-pack6/issues", "source": "https://github.com/araraloren/raku-pack6" }, "authors": "Loren" }
### ---------------------------------------------------- ### -- pack6 ### -- Licenses: MIT ### -- Authors: Loren ### -- File: t/00-sanity.rakutest ### ---------------------------------------------------- use CPAN::Pack6; use Test; done-testing;
### ---------------------------------------------------- ### -- pack6 ### -- Licenses: MIT ### -- Authors: Loren ### -- File: lib/CPAN/Tar.rakumod ### ---------------------------------------------------- unit class CPAN::Tar; # Please note this is just implement a part of USTAR standard ! use experimental :pack; use nqp; class THeader { ... } once { for THeader.^attributes -> $attr { my $name = $attr.name.substr(2); THeader.^add_method("set-{$name}", method ($header: buf8 $v) { $header.set-buf($attr.get_value($header), $v); $header; }); } } has $.out; submethod TWEAK() { unless $!out.defined { die "Please provide something can write for CPAN::Tar!"; } } method !prepare-header($path, $name) { my THeader $header .= new; $header.init(); $header.set-size( buf8.new: pack( "A*", sprintf "%011s", nqp::stat($path, nqp::const::STAT_FILESIZE).base(8) )); my ($prefix, $rname) = self!make-file-name($name); $header.set-name($rname); $header.set-prefix($prefix); $header.gen-checksum(); $header; } method !make-file-name($name) { my $buf = buf8.new: pack("A*", $name); my $count = $buf.elems; $count = 155 if $count > 155; while $count > 0 && $buf[$count - 1] != 0x2f { $count--; } return ($buf.subbuf(0, $count - 1), $buf.subbuf($count)); } method !end-record($size is copy) { my $count = 0; while $size % 512 != 0 { $count++; $size++; } if $count > 0 { $!out.write(buf8.new: 0 xx $count); } } method add(Str:D $path, Str:D $name) { my $header = self!prepare-header($path, $name); $header.out($!out); given $path.IO.open(:r) { while (my $buf = .read()) { $!out.write($buf); } .close(); } self!end-record(nqp::stat($path, nqp::const::STAT_FILESIZE)); } method pack() { my THeader $header .= new; $header.out($!out); $header.out($!out); $!out.close(); } class THeader { has @.name; has @.mode; has @.uid; has @.gid; has @.size; has @.mtime; has @.checksum; has @.type; has @.linkname; has @.magic; has @.ver; has @.uname; has @.gname; has @.devmajor; has @.devminor; has @.prefix; has @.padding; submethod TWEAK() { @!name := buf8.new(0 xx 100); @!mode := buf8.new(0 xx 8); @!uid := buf8.new(0 xx 8); # ignore @!gid := buf8.new(0 xx 8); # ignore @!size := buf8.new(0 xx 12); @!mtime := buf8.new(0 xx 12); @!checksum := buf8.new(0 xx 8); @!type := buf8.new(0 xx 1); @!linkname := buf8.new(0 xx 100); @!magic := buf8.new(0 xx 6); @!ver := buf8.new(0 xx 2); @!uname := buf8.new(0 xx 32); # ignore @!gname := buf8.new(0 xx 32); @!devmajor := buf8.new(0 xx 8); @!devminor := buf8.new(0 xx 8); @!prefix := buf8.new(0 xx 155); @!padding := buf8.new(0 xx 12); } method set-buf(@dest, $buf) { @dest.subbuf-rw(0, $buf.elems) = $buf; } method init() { self.set-buf(@!magic, buf8.new(pack("A*", "ustar"))); self.set-buf(@!ver, buf8.new(pack("A*", " "))); self.set-buf(@!mtime, buf8.new(pack("A*", sprintf "%011s", time.base(8)))); self.set-buf(@!gname, buf8.new(pack("A*", "users"))); self.set-buf(@!mode, buf8.new(pack("A*", sprintf "%07s", 0o644.base(8)))); } sub __checksum($sum is rw, $buf) { for ^$buf.elems -> $i { $sum += $buf[$i] +& 0xff; } } method gen-checksum() { my Int $sum = 0; __checksum($sum, @!name); __checksum($sum, @!mode); __checksum($sum, @!uid); __checksum($sum, @!gid); __checksum($sum, @!size); __checksum($sum, @!mtime); $sum += ' '.ord for ^8; __checksum($sum, @!type); __checksum($sum, @!linkname); __checksum($sum, @!magic); __checksum($sum, @!ver); __checksum($sum, @!uname); __checksum($sum, @!gname); __checksum($sum, @!devmajor); __checksum($sum, @!devminor); __checksum($sum, @!prefix); __checksum($sum, @!padding); self.set-buf(@!checksum, buf8.new(pack("A*", sprintf "%06s", $sum.base(8)))); } method out($out) { $out.write(@!name); $out.write(@!mode); $out.write(@!uid); $out.write(@!gid); $out.write(@!size); $out.write(@!mtime); $out.write(@!checksum); $out.write(@!type); $out.write(@!linkname); $out.write(@!magic); $out.write(@!ver); $out.write(@!uname); $out.write(@!gname); $out.write(@!devmajor); $out.write(@!devminor); $out.write(@!prefix); $out.write(@!padding); } }
### ---------------------------------------------------- ### -- pack6 ### -- Licenses: MIT ### -- Authors: Loren ### -- File: lib/CPAN/Convert.rakumod ### ---------------------------------------------------- unit module CPAN::Convert; use File::Which; &*pack6-hook.wrap(&default-hook); # $path is the directory that files are ready # convert asciidoc to markdown, using asciidoctor and pandoc sub default-hook(Str:D $path) { my @stack; # set the CWD to src directory, so we can get clean path of file/dir @stack.push: $path.IO; while +@stack > 0 { for @stack.pop.dir() -> $f { @stack.push($f) if $f.d; if $f.f && $f.extension eq "adoc" { &convert-asciidoc($f.Str, $f.subst(/"adoc"$/, "md")); $f.unlink; } } } } sub convert-asciidoc(Str:D $path, Str:D $out) { if check-dependence(< asciidoctor iconv pandoc >) { die "Can not find command: ", $_; } my @commands = [ 'asciidoctor' => [ "-b", "docbook", $path, "-o", "{$path}.xml" ], 'iconv' => [ "-t", "utf8", "$path.xml", "-o", "{$path}.xml2"], -> { unlink("{$path}.xml"); }, 'pandoc' => [ "-f", "docbook", "-t", "gfm", "{$path}.xml2", "-o", $out], -> { unlink("{$path}.xml2"); }, ]; for @commands -> $cmd { if $cmd ~~ Callable { &$cmd(); } else { if simple-run($cmd.key, @($cmd.value())) != 0 { die "Run command failed: ", $cmd.gist; } } } } sub simple-run(Str $cmd, @args) { my $proc = do if $*DISTRO.is-win { run('cmd', '/c', $cmd, |@args); } else { run($cmd, |@args); }; $proc; } sub check-dependence(@cmds --> Str) { for @cmds -> $cmd { if ! which($cmd).defined { return $cmd; } } }
### ---------------------------------------------------- ### -- pack6 ### -- Licenses: MIT ### -- Authors: Loren ### -- File: lib/CPAN/Pack6.rakumod ### ---------------------------------------------------- unit module CPAN::Pack6; sub excluded-default($_) { $_ eq '.' || $_ eq '..' } our proto copy-module-to(Str:D $src, Str:D $dest, |) {*} # copy file to directory our multi sub copy-module-to(Str:D $src, Str:D $dest, &ex) { my (@stack, @dirs, @files); my ($ddir, $old) = ($dest.IO, $*CWD); # set the CWD to src directory, so we can get clean path of file/dir chdir($src); @stack.push: ".".IO; while +@stack > 0 { for @stack.pop.dir(test => { !&ex($_) && !&excluded-default($_) }) -> $f { @stack.push($f) if $f.d; $f.d ?? @dirs.push($f.Str) !! @files.push([ $f, $f.Str ]); } } chdir($old); # create directory tree first $ddir.add($_).mkdir for @dirs; # copy the file .[0].copy($ddir.add(.[1])) for @files; } # copy file to directory our multi sub copy-module-to(Str:D $src, Str:D $dest) { my (@stack, @dirs, @files); my ($ddir, $old) = ($dest.IO, $*CWD); # set the CWD to src directory, so we can get clean path of file/dir chdir($src); @stack.push: ".".IO; while +@stack > 0 { for @stack.pop.dir() -> $f { @stack.push($f) if $f.d; $f.d ?? @dirs.push($f.Str) !! @files.push([ $f, $f.Str ]); } } chdir($old); # create directory tree first $ddir.add($_).mkdir for @dirs; # copy the file .[0].copy($ddir.add(.[1])) for @files; }
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:lizmat", "authors": [ "Elizabeth Mattijsen" ], "build-depends": [ ], "depends": [ ], "description": "low-level path introspection utility functions", "license": "Artistic-2.0", "name": "path-utils", "perl": "6.d", "provides": { "path-utils": "lib/path-utils.rakumod" }, "resources": [ ], "source-url": "https://github.com/lizmat/path-utils.git", "tags": [ "IO", "STAT", "PATH", "PDF", "MOARVM", "NAUGHTY", "READABLE", "WRITABLE", "EXECUTABLE", "SETUID", "SETGID", "STICKY", "GIT", "GITHUB" ], "test-depends": [ ], "version": "0.0.21" }
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) [![Actions Status](https://github.com/lizmat/path-utils/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/path-utils/actions) NAME ==== path-utils - low-level path introspection utility functions SYNOPSIS ======== ```raku use path-utils; # export all subs use path-utils <path-exists>; # only export sub path-exists say path-exists($filename); 0 or 1 ``` DESCRIPTION =========== path-utils provides a number of low-level path introspection utility functions for those cases where you're interested in performance, rather than functionality. All subroutines take a (native) string as the only argument. Note that these functions only return native `int` and native `num` values, which can be used in conditions without any problems, just don't expect them to be upgraded to `Bool` values. Also note that all functions (except `path-exists`) expect the path to exist. An exception will be thrown if the path does not exist. The reason for this is that in situations where you are already sure a path exists, there is no point checking for its existence again if you e.g. would like to know its size. SELECTIVE IMPORTING =================== ```raku use path-utils <path-exists>; # only export sub path-exists ``` By default all utility functions are exported. But you can limit this to the functions you actually need by specifying the names in the `use` statement. To prevent name collisions and/or import any subroutine with a more memorable name, one can use the "original-name:known-as" syntax. A semi-colon in a specified string indicates the name by which the subroutine is known in this distribution, followed by the name with which it will be known in the lexical context in which the `use` command is executed. ```raku use path-utils <path-exists:alive>; # export "path-exists" as "alive" say alive "/etc/passwd"; # 1 if on Unixy, 0 on Windows ``` EXPORTED SUBROUTINES ==================== In alphabetical order: path-accessed ------------- Returns number of seconds since epoch as a `num` when path was last accessed. path-blocks ----------- Returns the number of filesystem blocks allocated for this path. path-block-size --------------- Returns the preferred I/O size in bytes for interacting wuth the path. path-created ------------ Returns number of seconds since epoch as a `num` when path was created. path-device-number ------------------ Returns the device number of the filesystem on which the path resides. path-exists ----------- Returns 1 if paths exists, 0 if not. path-filesize ------------- Returns the size of the path in bytes. path-gid -------- Returns the numeric group id of the path. path-git-repo ------------- Returns the path of the Git repository associated with the **absolute** path given, or returns the empty string if the path is not part inside a Git repository. Note that this not mean that the file is actually part of that Git repository: it merely indicates that the returned path returned `True` with `path-is-git-repo`. path-hard-links --------------- Returns the number of hard links to the path. path-has-setgid --------------- The path has the SETGID bit set in its attributes. path-inode ---------- Returns the inode of the path. path-is-device -------------- Returns 1 if path is a device, 0 if not. path-is-directory ----------------- Returns 1 if path is a directory, 0 if not. path-is-empty ------------- Returns 1 if the path has a filesize of 0. path-is-executable ------------------ Returns a non-zero integer value if path is executable by the current user. path-is-github-repo ------------------- Returns 1 if path appears to be the top directory in a GitHub repository (as recognized by having a `.github` directory in it). path-is-git-repo ---------------- Returns 1 if path appears to be the top directory in a Git repository (as recognized by having a <.git> directory in it). path-is-group-executable ------------------------ Returns a non-zero integer value if path is executable by members of the group of the path. path-is-group-readable ---------------------- Returns a non-zero integer value if path is readable by members of the group of the path. path-is-group-writable ---------------------- Returns a non-zero integer value if path is writable by members of the group of the path. path-is-moarvm -------------- Returns 1 if path is a `MoarVM` bytecode file (either from core, or from a precompiled module file), 0 if not. path-is-owned-by-user --------------------- Returns a non-zero integer value if path is owned by the current user. path-is-owned-by-group ---------------------- Returns a non-zero integer value if path is owned by the group of the current user. path-is-owner-executable ------------------------ Returns a non-zero integer value if path is executable by the owner of the path. path-is-owner-readable ---------------------- Returns a non-zero integer value if path is readable by the owner of the path. path-is-owner-writable ---------------------- Returns a non-zero integer value if path is writable by the owner of the path. path-is-pdf ----------- Returns 1 if path looks a `PDF` file, judging by its magic number, 0 if not. path-is-readable ---------------- Returns a non-zero integer value if path is readable by the current user. path-is-regular-file -------------------- Returns 1 if path is a regular file, 0 if not. path-is-sticky -------------- The path has the STICKY bit set in its attributes. path-is-symbolic-link --------------------- Returns 1 if path is a symbolic link, 0 if not. path-is-text ------------ Returns 1 if path looks like it contains text, 0 if not. path-is-world-executable ------------------------ Returns a non-zero integer value if path is executable by anybody. path-is-world-readable ---------------------- Returns a non-zero integer value if path is readable by anybody. path-is-world-writable ---------------------- Returns a non-zero integer value if path is writable by any body. path-is-writable ---------------- Returns a non-zero integer value if path is writable by the current user. path-meta-modified ------------------ Returns number of seconds since epoch as a `num` when the meta information of the path was last modified. path-mode --------- Returns the numeric unix-style mode. path-modified ------------- Returns number of seconds since epoch as a `num` when path was last modified. path-uid -------- Returns the numeric user id of the path. AUTHOR ====== Elizabeth Mattijsen <[email protected]> Source can be located at: https://github.com/lizmat/path-utils . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! COPYRIGHT AND LICENSE ===================== Copyright 2022, 2023, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: _config.yml ### ---------------------------------------------------- theme: jekyll-theme-leap-day
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: dist.ini ### ---------------------------------------------------- name = path-utils [ReadmeFromPod] ; enabled = false filename = doc/path-utils.rakudoc [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use path-utils; plan 56; my str $file = $?FILE; my str $dir = $file.IO.parent.absolute; is-deeply path-exists($file), 1, "does $file exist"; is-deeply path-exists($dir), 1, "does $dir exist"; is-deeply path-exists("foo"), 0, "does foo NOT exist"; is-deeply path-is-regular-file($file), 1, "is $file a regular file"; is-deeply path-is-regular-file($dir), 0, "is $dir NOT a regular file"; is-deeply path-is-directory($dir), 1, "is $dir a directory"; is-deeply path-is-directory($file), 0, "is $file NOT a directory"; is-deeply path-is-device($file), 0, "is $file NOT a device"; is-deeply path-is-device($dir), 0, "is $dir NOT a device"; is-deeply path-is-symbolic-link($file), 0, "is $file NOT a symlink"; is-deeply path-is-symbolic-link($dir), 0, "is $dir NOT a symlink"; is-deeply path-is-text( $file), 1, "does $file contain text"; is-deeply path-is-moarvm($file), 0, "is $file NOT a MoarVM file"; is-deeply path-is-pdf($file), 0, "is $file NOT a PDF file"; isa-ok path-created($file), Num, "is $file created a Num"; isa-ok path-accessed($file), Num, "is $file accessed a Num"; isa-ok path-modified($file), Num, "is $file accessed a Num"; isa-ok path-meta-modified($file), Num, "is $file accessed a Num"; isa-ok path-uid($file), Int, "is $file uid an Int"; isa-ok path-gid($file), Int, "is $file gid an Int"; isa-ok path-inode($file), Int, "is $file inode an Int"; isa-ok path-inode($dir), Int, "is $dir inode an Int"; isa-ok path-device-number($file), Int, "is $file device-number an Int"; isa-ok path-device-number($dir), Int, "is $dir device-number an Int"; isa-ok path-hard-links($file), Int, "is $file hard-links an Int"; isa-ok path-hard-links($dir), Int, "is $dir hard-links an Int"; isa-ok path-inode($file), Int, "is $file inode an Int"; isa-ok path-inode($dir), Int, "is $dir inode an Int"; isa-ok path-block-size($file), Int, "is $file block-size an Int"; isa-ok path-block-size($dir), Int, "is $dir block-size an Int"; isa-ok path-blocks($file), Int, "is $file blocks an Int"; isa-ok path-blocks($dir), Int, "is $dir blocks an Int"; isa-ok path-filesize($file), Int, "is $file filesize an Int"; isa-ok path-filesize($dir), Int, "is $dir filesize an Int"; nok path-is-empty($file), "is $file not empty"; if Rakudo::Internals.IS-WIN { isa-ok path-mode($file), Int , "is $file mode an Int"; isa-ok path-mode($dir), Int , "is $dir mode an Int"; isa-ok path-filesize($file), Int, "is $file filesize ok"; pass "Windows mode checks unreliable" for ^18; } else { is-deeply path-mode($file), 33188, "is $file mode ok"; is-deeply path-mode($dir), 16877, "is $dir mode ok"; is-deeply path-filesize($file), 4009, "is $file filesize ok"; ok path-is-readable($file), "is $file readable by user"; ok path-is-writable($file), "is $file writable by user"; nok path-is-executable($file), "is $file executable by user"; ok path-is-group-readable($file), "is $file group readable"; nok path-is-group-writable($file), "is $file group writable"; nok path-is-group-executable($file), "is $file group executable"; ok path-is-world-readable($file), "is $file world readable"; nok path-is-world-writable($file), "is $file world writable"; nok path-is-world-executable($file), "is $file world executable"; ok path-is-readable($dir), "is $dir readable by user"; ok path-is-writable($dir), "is $dir writable by user"; ok path-is-executable($dir), "is $dir executable by user"; ok path-is-group-readable($dir), "is $dir group readable"; nok path-is-group-writable($dir), "is $dir group writable"; ok path-is-group-executable($dir), "is $dir group executable"; ok path-is-world-readable($dir), "is $dir world readable"; nok path-is-world-writable($dir), "is $dir world writable"; ok path-is-world-executable($dir), "is $dir world executable"; } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/02-selective-importing.rakutest ### ---------------------------------------------------- use Test; my constant @subs = < path-accessed path-block-size path-blocks path-created path-device-number path-exists path-is-directory path-filesize path-gid path-git-repo path-hard-links path-has-setgid path-has-setuid path-inode path-is-device path-is-empty path-is-executable path-is-git-repo path-is-github-repo path-is-group-executable path-is-group-readable path-is-group-writable path-is-owned-by-group path-is-owned-by-user path-is-owner-executable path-is-owner-readable path-is-owner-writable path-is-readable path-is-regular-file path-is-sticky path-is-symbolic-link path-is-text path-is-world-executable path-is-world-readable path-is-world-writable path-is-writable path-meta-modified path-mode path-modified path-uid >; plan @subs + 2; my $code; for @subs { $code ~= qq:!c:to/CODE/; { use path-utils '$_'; ok MY::<&$_>:exists, "Did '$_' get exported?"; } CODE } $code ~= qq:!c:to/CODE/; { use path-utils <path-is-text:textual>; ok MY::<&textual>:exists, "Did 'textual' get exported?"; is MY::<&textual>.name, 'path-is-text', 'Was the original name ok?'; } CODE $code.EVAL; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/01-dev.rakutest ### ---------------------------------------------------- use Test; use path-utils; plan 10; my str $file = $?FILE; my str $t = $?FILE.IO.parent.absolute; my str $dir = $?FILE.IO.parent.parent.absolute; nok path-is-git-repo($t), "is $t NOT a Git repo"; nok path-is-github-repo($t), "is $t NOT a GitHub repo"; ok path-is-git-repo($dir), "is $dir a Git repo"; ok path-is-github-repo($dir), "is $dir a GitHub repo"; ok path-is-owned-by-user($file), "is $file owned by user"; ok path-is-owned-by-user($dir), "is $file owned by user"; ok path-is-owned-by-group($file), "is $file owned by group"; ok path-is-owned-by-group($dir), "is $file owned by group"; is-deeply path-git-repo($t), $dir, "is $dir the Git repo of $t"; is-deeply path-git-repo($?FILE), $dir, "is $dir the Git repo of $file"; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/coverage.rakutest ### ---------------------------------------------------- use Test::Coverage; plan 2; coverage-at-least 47; uncovered-at-most 76; source-with-coverage; report; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- path-utils ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: lib/path-utils.rakumod ### ---------------------------------------------------- # This is a naughty module using NQP use nqp; INIT quietly my int $uid = +$*USER // 0; INIT quietly my int $gid = +$*GROUP // 0; INIT my str $dir-sep = $*SPEC.dir-sep; my constant LFLF = 2570; # "\n\n" as a 16bit uint my constant MOARVM = 724320148219055949; # "MOARVM\r\n" as a 64bit uint my constant BIT16 = nqp::const::BINARY_SIZE_16_BIT +| nqp::const::BINARY_ENDIAN_LITTLE; my constant BIT64 = nqp::const::BINARY_SIZE_64_BIT +| nqp::const::BINARY_ENDIAN_LITTLE; # Turn a Block into a WhateverCode, which guarantees here are no # phasers that need to be taken into account, and there a no # return statements my sub WC($block is raw) { my $wc := nqp::create(WhateverCode); nqp::bindattr( $wc,Code,'$!do',nqp::getattr($block,Code,'$!do') ); nqp::bindattr( $wc,Code,'$!signature',nqp::getattr($block,Code,'$!signature') ); nqp::bindattr( $wc,Code,'@!compstuff',nqp::getattr($block,Code,'@!compstuff') ); $wc } my sub path-is-moarvm(str $path) { nqp::iseq_i(nqp::filereadable($path),1) && do { my $fh := nqp::open($path, 'r'); my $buf := nqp::create(buf8.^pun); nqp::readfh($fh, $buf, 16384); nqp::closefh($fh); # A pure MoarVM bytecode file if nqp::isge_i(nqp::elems($buf),8) && nqp::iseq_i(nqp::readuint($buf,0,BIT64), MOARVM) { 1 } # Possibly a module precomp file else { my int $last = nqp::elems($buf) - 8; my int $offset; # Find the first \n\n nqp::while( nqp::isle_i($offset,$last) && nqp::isne_i(nqp::readuint($buf,$offset++,BIT16), LFLF), nqp::null ); # Found \n\n followed by MoarVM magic number nqp::isle_i($offset, $last) && nqp::iseq_i(nqp::readuint($buf,$offset + 1,BIT64), MOARVM) } } } my constant PDF = 1178882085; # "%PDF" as a 32bit uint my constant BIT32 = nqp::const::BINARY_SIZE_32_BIT +| nqp::const::BINARY_ENDIAN_LITTLE; my sub path-is-pdf(str $path) { nqp::iseq_i(nqp::filereadable($path),1) && do { my $fh := nqp::open($path, 'r'); my $buf := nqp::create(buf8.^pun); nqp::readfh($fh, $buf, 4); nqp::closefh($fh); nqp::isge_i(nqp::elems($buf),4) && nqp::iseq_i(nqp::readuint($buf,0,BIT32), PDF) } } my constant PRINTABLE = do { my int @table; @table[$_] = 1 for flat "\t\b\o33\o14".ords, 32..126, 128..255; @table } my sub path-is-text(str $path) { nqp::iseq_i(nqp::filereadable($path),1) && do { my $fh := nqp::open($path, 'r'); my $buf := nqp::create(buf8.^pun); nqp::readfh($fh, $buf, 4096); nqp::closefh($fh); my int $limit = nqp::elems($buf); my int $printable; my int $unprintable; my int $i = -1; # Algorithm shamelessly copied from Jonathan Worthington's # Data::TextOrBinary module, converted to NQP ops for speed nqp::while( nqp::islt_i(++$i,$limit), nqp::stmts( nqp::if( (my int $check = nqp::atpos_i($buf,$i)), nqp::if( # not a NULL byte, check nqp::iseq_i($check,13), nqp::if( nqp::isne_i(nqp::atpos_i($buf,++$i),10), (return 0), # \r not followed by \n hints binary ), nqp::if( nqp::isne_i($check,10), # Ignore lone \n nqp::if( nqp::atpos_i(PRINTABLE,$check), ++$printable, ++$unprintable ) ) ), (return 0) # NULL byte, so binary. ) ) ); nqp::isge_i(nqp::bitshiftr_i($printable,7),$unprintable) } } my constant &path-exists = WC -> str $_ { nqp::stat($_,nqp::const::STAT_EXISTS) } my constant &path-is-directory = WC -> str $_ { nqp::stat($_,nqp::const::STAT_ISDIR) } my constant &path-is-regular-file = WC -> str $_ { nqp::stat($_,nqp::const::STAT_ISREG) } my constant &path-is-device = WC -> str $_ { nqp::stat($_,nqp::const::STAT_ISDEV) } my constant &path-is-symbolic-link = WC -> str $_ { nqp::stat($_,nqp::const::STAT_ISLNK) } my constant &path-created = WC -> str $_ { nqp::stat_time($_,nqp::const::STAT_CREATETIME) } my constant &path-accessed = WC -> str $_ { nqp::stat_time($_,nqp::const::STAT_ACCESSTIME) } my constant &path-modified = WC -> str $_ { nqp::stat_time($_,nqp::const::STAT_MODIFYTIME) } my constant &path-meta-modified = WC -> str $_ { nqp::stat_time($_,nqp::const::STAT_CHANGETIME) } my constant &path-uid = WC -> str $_ { nqp::stat($_,nqp::const::STAT_UID) } my constant &path-gid = WC -> str $_ { nqp::stat($_,nqp::const::STAT_GID) } my constant &path-inode = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_INODE) } my constant &path-device-number = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_DEV) } my constant &path-mode = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_MODE) } my constant &path-hard-links = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_NLINKS) } my constant &path-filesize = WC -> str $_ { nqp::stat($_,nqp::const::STAT_FILESIZE) } my constant &path-is-empty = WC -> str $_ { nqp::iseq_i(nqp::stat($_,nqp::const::STAT_FILESIZE),0) } my constant &path-block-size = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_BLOCKSIZE) } my constant &path-blocks = WC -> str $_ { nqp::stat($_,nqp::const::STAT_PLATFORM_BLOCKS) } my constant &path-is-readable = WC -> str $_ { nqp::filereadable($_) } my constant &path-is-writable = WC -> str $_ { nqp::filewritable($_) } my constant &path-is-executable = WC -> str $_ { nqp::fileexecutable($_) } my constant &path-has-setuid = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),2048) } my constant &path-has-setgid = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),1024) } my constant &path-is-sticky = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),512) } my constant &path-is-owner-readable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),256) } my constant &path-is-owner-writable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),128) } my constant &path-is-owner-executable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),64) } my constant &path-is-group-readable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),32) } my constant &path-is-group-writable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),16) } my constant &path-is-group-executable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),8) } my constant &path-is-world-readable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),4) } my constant &path-is-world-writable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),2) } my constant &path-is-world-executable = WC -> str $_ { nqp::bitand_i(nqp::stat($_,nqp::const::STAT_PLATFORM_MODE),1) } my sub path-is-owned-by-user(str $path) { nqp::iseq_i(nqp::stat($path,nqp::const::STAT_UID),$uid) } my sub path-is-owned-by-group(str $path) { nqp::iseq_i(nqp::stat($path,nqp::const::STAT_GID),$gid) } my sub path-git-repo(str $path) { my str @parts = nqp::split($dir-sep, $path); my str $repo; nqp::while( nqp::elems(@parts) && nqp::not_i(path-is-git-repo( ($repo = nqp::join($dir-sep, @parts)), )), nqp::pop_s(@parts) ); nqp::elems(@parts) ?? $repo !! "" } my sub path-is-git-repo(str $path) { my str $dotgit = $path ~ $dir-sep ~ ".git"; nqp::stat($dotgit,nqp::const::STAT_EXISTS) && nqp::stat($dotgit,nqp::const::STAT_ISDIR) } my sub path-is-github-repo(str $path) { my str $dotgithub = $path ~ $dir-sep ~ ".github"; nqp::stat($dotgithub,nqp::const::STAT_EXISTS) && nqp::stat($dotgithub,nqp::const::STAT_ISDIR) } my sub EXPORT(*@names) { Map.new: @names ?? @names.map: { if UNIT::{"&$_"}:exists { UNIT::{"&$_"}:p } else { my ($in,$out) = .split(':', 2); if $out && UNIT::{"&$in"} -> &code { Pair.new: "&$out", &code } } } !! UNIT::.grep: { .key.starts-with('&') && .key ne '&EXPORT' } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:lizmat", "authors": [ "Elizabeth Mattijsen" ], "build-depends": [ ], "depends": [ ], "description": "A fast recursive file / directory finder", "license": "Artistic-2.0", "name": "paths", "perl": "6.d", "provides": { "paths": "lib/paths.rakumod" }, "resources": [ ], "source-url": "https://github.com/lizmat/paths.git", "tags": [ "PATH", "RECURSE", "FINDER" ], "test-depends": [ ], "version": "10.1" }
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: README.md ### ---------------------------------------------------- [![Actions Status](https://github.com/lizmat/paths/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/paths/actions) [![Actions Status](https://github.com/lizmat/paths/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/paths/actions) [![Actions Status](https://github.com/lizmat/paths/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/paths/actions) NAME ==== paths - A fast recursive file / directory finder SYNOPSIS ======== ```raku use paths; .say for paths; # all files from current directory .say for paths($dir); # all files from $dir .say for paths(:dir(* eq '.git')); # files in ".git" directories .say for paths(:file(*.ends-with(".json"); # all .json files .say for paths(:recurse); # also recurse in non-accepted dirs .say for paths(:follow-symlinks); # also recurse into symlinked dirs .say for paths(:!file); # only produce directory paths say is-regular-file('/etc/passwed'); # True (on Unixes) ``` DESCRIPTION =========== By default exports two subroutines: `paths` (returning a `Seq` of absolute path strings of files (or directories) for the given directory and all its sub-directories (with the notable exception of `.` and `..`). And `is-regular-file`, which returns a `Bool` indicating whether the given absolute path is a regular file. SELECTIVE IMPORTING =================== ```raku use paths <paths>; # only export sub paths ``` By default all utility functions are exported. But you can limit this to the functions you actually need by specifying the names in the `use` statement. To prevent name collisions and/or import any subroutine with a more memorable name, one can use the "original-name:known-as" syntax. A semi-colon in a specified string indicates the name by which the subroutine is known in this distribution, followed by the name with which it will be known in the lexical context in which the `use` command is executed. ```raku use path <paths:find-all-paths>; # export "paths" as "find-all-paths" .say for find-all-paths; ``` EXPORTED SUBROUTINES ==================== paths ----- The `paths` subroutine returns a `Seq` of absolute path strings of files for the given directory and all its sub-directories (with the notable exception of `.` and `..`). ### ARGUMENTS * directory The only positional argument is optional: it can either be a path as a string or as an `IO` object. It defaults to the current directory (also when an undefined value is specified). The (implicitely) specified directory will **always** be investigated, even if the directory name does not match the `:dir` argument. If the specified path exists, but is not a directory, then only that path will be produced if the file-matcher accepts the path. In all other cases, an empty `Seq` will be returned. * :dir The named argument `:dir` accepts a matcher to be used in smart-matching with the basename of the directories being found. If accepted, will produce both files as well as other directories to recurse into. It defaults to skipping all of the directories that start with a period (also if an undefined value is specified). * :file The named argument `:file` accepts a matcher to be used in smart-matching with the basename of the file being found. It defaults to `True`, meaning that all possible files will be produced (also if an undefined values is specified). If the boolean value `False` is specified, then **only** the paths of directories will be produced. * :recurse Flag. The named argument `:recurse` accepts a boolean value to indicate whether subdirectories that did **not** match the `:dir` specification, should be investigated as well for other **directories** to recurse into. No files will be produced from a directory that didn't match the `:dir` argument. By default, it will not recurse into directories. * :follow-symlinks The named argument `:follow-symlinks` accepts a boolean value to indicate whether subdirectories, that are actually symbolic links to a directory, should be investigated as well. By default, it will not. is-regular-file --------------- ```raku say is-regular-file('/etc/passwed'); # True (on Unixes) ``` Returns a `Bool` indicating whether the given absolute path is a regular file. AUTHOR ====== Elizabeth Mattijsen <[email protected]> Source can be located at: https://github.com/lizmat/paths . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! COPYRIGHT AND LICENSE ===================== Copyright 2021, 2022, 2024 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: dist.ini ### ---------------------------------------------------- name = paths [ReadmeFromPod] ; enable = false filename = doc/paths.rakudoc [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml [UploadToZef]
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/03-selective-importing.rakutest ### ---------------------------------------------------- use Test; my constant @subs = <paths is-regular-file>; plan @subs + 2; my $code; for @subs { $code ~= qq:!c:to/CODE/; { use paths '$_'; ok MY::<&$_>:exists, "Did '$_' get exported?"; } CODE } $code ~= qq:!c:to/CODE/; { use paths <paths:find-all-paths>; ok MY::<&find-all-paths>:exists, "Did 'alive' get exported?"; is MY::<&find-all-paths>.name, 'paths', 'Was the original name ok?'; } CODE $code.EVAL; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use paths; plan 28; (my $dir := $*SPEC.tmpdir.add("paths.test-" ~ rand)).mkdir; (my $foo := $dir.add("foo")).mkdir; (my $one := $foo.add("one.json")).spurt("one.json"); (my $foobar := $foo.add("bar")).mkdir; (my $two := $foobar.add("two.json")).spurt("two.json"); (my $three := $foobar.add("three.txt")).spurt("three.txt"); (my $foobardot := $foobar.add(".dot")).mkdir; (my $four := $foobardot.add("four.t")).spurt("four.t"); (my $five := $foobardot.add("five.t")).spurt("five.t"); LEAVE { .unlink for $five, $four, $three, $two, $one; .rmdir for $foobardot, $foobar, $foo; } my $root = $dir.absolute.subst('\\' ,'/', :global); my $from = $root.chars + 1; my @got; sub verify-path-roots($plan, |c) is test-assertion { my @seen; subtest 'test path roots', { plan $plan; for paths(|c).map(*.subst: '\\', '/', :global) -> $path { ok $path.starts-with($root), "root of $path.IO.basename() ok"; @seen.push($path.substr($from)); } } @got := @seen.sort.List; } sub verify-files(@expected, $comment) is test-assertion { subtest $comment => { plan 1 + @expected; is-deeply @got, @expected, 'are all files accounted for'; for @expected { my $io := $dir.add($_); is $io.slurp, $io.basename, "is the content '$io.basename()'"; } } } verify-path-roots 3, $dir; verify-files < foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir'; verify-path-roots 2, $dir, :!file; is-deeply @got, < foo foo/bar >, 'did we get all the directories for $dir'; verify-path-roots 3, $dir, :dir(Any), :file(Any); verify-files < foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for Any / Any'; verify-path-roots 2, $dir, :dir(Any), :!file; is-deeply @got, < foo foo/bar >, 'did we get all the directories for Any'; verify-path-roots 5, $dir, :dir; verify-files < foo/bar/.dot/five.t foo/bar/.dot/four.t foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir :dir'; verify-path-roots 3, $dir, :dir, :!file; is-deeply @got, < foo foo/bar foo/bar/.dot >, 'did we get all the directories for $dir :dir'; verify-path-roots 2, $dir, :file(*.ends-with('.json')); verify-files < foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir :file(*.ends-with(json))'; verify-path-roots 0, $dir, :file(*.ends-with('.t')); is +@got, 0, 'did we get no paths for $dir :file(*.ends-with(t))'; verify-path-roots 0, $dir, :dir(* eq '.dot'); is +@got, 0, 'did we get no paths for $dir :dir(* eq .dot)'; verify-path-roots 0, $dir, :dir(* eq '.dot'), :!file; is +@got, 0, 'did we get no directories for $dir :dir(* eq .dot)'; verify-path-roots 2, $dir, :dir(* eq '.dot'), :recurse; verify-files < foo/bar/.dot/five.t foo/bar/.dot/four.t >, 'did we get all the paths for $dir :dir(* eq .dot) :recurse'; verify-path-roots 1, $dir, :dir(* eq '.dot'), :recurse, :!file; is-deeply @got, ('foo/bar/.dot',), 'did we get all the directories for $dir :dir(* eq .dot) :recurse'; verify-path-roots 1, $three; verify-files ('foo/bar/three.txt',), 'did we get the single existing file'; ok is-regular-file($*PROGRAM.absolute), 'is this a regular file'; nok is-regular-file($*PROGRAM.parent.absolute), 'is parent not a regular file'; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/02-symlinks.rakutest ### ---------------------------------------------------- use Test; use paths; (my $tmpdir := $*SPEC.tmpdir.resolve.add("paths.test-" ~ rand)).mkdir; (my $dir := $tmpdir.add("dir")).mkdir; (my $foo := $tmpdir.add("foo")).mkdir; (my $symfoo := $dir.add("symfoo")).unlink; LEAVE { $symfoo.unlink; .rmdir for $foo, $dir, $tmpdir; } if $foo.symlink($symfoo) && $symfoo.e { plan 16; (my $one := $foo.add("one.json")).spurt("one.json"); (my $foobar := $foo.add("bar")).mkdir; (my $two := $foobar.add("two.json")).spurt("two.json"); (my $three := $foobar.add("three.txt")).spurt("three.txt"); (my $foobardot := $foobar.add(".dot")).mkdir; (my $four := $foobardot.add("four.t")).spurt("four.t"); (my $five := $foobardot.add("five.t")).spurt("five.t"); LEAVE { .unlink for $five, $four, $three, $two, $one, $symfoo; .rmdir for $foobardot, $foobar; } my $root := $tmpdir.absolute.subst('\\' ,'/', :global); my $from := $root.chars + 1; my @got; sub verify-path-roots($plan, |c) is test-assertion { my @seen; subtest 'test path roots', { plan $plan; for paths(:follow-symlinks, |c).map(*.subst: '\\', '/', :global) -> $path { ok $path.starts-with($root), "root of $path.IO.basename() ok"; @seen.push($path.substr($from)); } } @got := @seen.sort.List; } sub verify-files(@expected, $comment) is test-assertion { subtest $comment => { plan 1 + @expected; is-deeply @got, @expected, 'are all files accounted for'; for @expected { my $io := $tmpdir.add($_); is $io.slurp, $io.basename, "is the content '$io.basename()'"; } } } verify-path-roots 3, $dir; verify-files < foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir'; verify-path-roots 3, $dir, :dir(Any), :file(Any); verify-files < foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir'; verify-path-roots 5, $dir, :dir; verify-files < foo/bar/.dot/five.t foo/bar/.dot/four.t foo/bar/three.txt foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir :dir'; verify-path-roots 2, $dir, :file(*.ends-with('.json')); verify-files < foo/bar/two.json foo/one.json >, 'did we get all the paths for $dir :file(*.ends-with(json))'; verify-path-roots 0, $dir, :file(*.ends-with('.t')); is +@got, 0, 'did we get no paths for $dir :file(*.ends-with(t))'; verify-path-roots 0, $dir, :dir(* eq '.dot'); is +@got, 0, 'did we get no paths for $dir :dir(* eq .dot)'; verify-path-roots 2, $dir, :dir(* eq '.dot'), :recurse; verify-files < foo/bar/.dot/five.t foo/bar/.dot/four.t >, 'did we get all the paths for $dir :dir(* eq .dot) :recurse'; verify-path-roots 1, $three; verify-files ('foo/bar/three.txt',), 'did we get the single existing file'; } else { plan 1; pass "Could not create symlink for testing"; } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/coverage.rakutest ### ---------------------------------------------------- use Test::Coverage; coverage-at-least 50; uncovered-at-most 40; source-with-coverage; report; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- paths ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: lib/paths.rakumod ### ---------------------------------------------------- # This is a naughty module, inspired by Rakudo::Internals.DIR-RECURSE use nqp; my class Files does Iterator { has str $!prefix; # currently active prefix for entries has str $!dir-sep; # directory separator to use has $!dir-matcher; # matcher for accepting dir names has $!file-matcher; # matcher for accepting file names has $!recurse; # recurse on non-matching dirs? has $!readable-files; # only produce readable files has $!follow-symlinks; # whether to follow symlinks has $!handle; # currently active nqp::opendir() handle has $!todo; # list of abspaths of dirs to do still has $!seen; # has of abspaths of dirs seen already has $!dir-accepts-files; # produce files in current dir if accepted method !SET-SELF( str $abspath, $dir-matcher, $file-matcher, $recurse, $follow-symlinks, $readable-files ) { # Set up first dir, return empty handed if failed nqp::handle( ($!handle := nqp::opendir($abspath)), 'CATCH', (return Rakudo::Iterator.Empty) ); $!dir-matcher := $dir-matcher; $!file-matcher := $file-matcher; $!recurse := $recurse; $!follow-symlinks := $follow-symlinks; $!readable-files := $readable-files; $!dir-sep = $*SPEC.dir-sep; $!seen := nqp::hash; $!todo := nqp::list_s; $!prefix = nqp::concat($abspath,$!dir-sep); $!dir-accepts-files := True; self } method new( str $abspath, $dir-matcher, $file-matcher, $recurse, $follow-symlinks, $readable-files ) { nqp::stat($abspath,nqp::const::STAT_EXISTS) ?? nqp::stat($abspath,nqp::const::STAT_ISDIR) ?? nqp::create(self)!SET-SELF( $abspath, $dir-matcher, $file-matcher, $recurse, $follow-symlinks, $readable-files ) !! $file-matcher.ACCEPTS($abspath) ?? Rakudo::Iterator.OneValue($abspath) !! Rakudo::Iterator.Empty !! Rakudo::Iterator.Empty } method !entry(--> str) { nqp::until( nqp::isnull($!handle) || nqp::isnull_s(my str $entry = nqp::nextfiledir($!handle)) || (nqp::isne_s($entry,'.') && nqp::isne_s($entry,'..')), nqp::null ); nqp::if(nqp::isnull_s($entry),'',$entry) } method !next() { nqp::until( nqp::chars(my str $entry = self!entry), nqp::stmts( nqp::unless( nqp::isnull($!handle), nqp::stmts( nqp::closedir($!handle), ($!handle := nqp::null), ) ), nqp::if( nqp::elems($!todo), nqp::stmts( (my str $abspath = nqp::pop_s($!todo)), nqp::handle( ($!handle := nqp::opendir($abspath)), 'CATCH', 0 ), nqp::unless( nqp::isnull($!handle), nqp::stmts( # opendir failed ($!dir-accepts-files := $!dir-matcher.ACCEPTS( nqp::substr( $abspath, nqp::add_i(nqp::rindex($abspath,$!dir-sep),1) ) )), ($!prefix = nqp::concat($abspath,$!dir-sep)) ) ) ), return '' # we're done, totally ) ) ); $entry } method pull-one() { nqp::while( nqp::chars(my str $entry = self!next), nqp::if( nqp::stat( (my str $path = nqp::concat($!prefix,$entry)), nqp::const::STAT_EXISTS ), nqp::if( nqp::stat($path,nqp::const::STAT_ISREG) && nqp::iseq_i($!readable-files,nqp::filereadable($path)) && $!dir-accepts-files && $!file-matcher.ACCEPTS($entry), (return $path), nqp::if( $!follow-symlinks || nqp::not_i(nqp::fileislink($path)), nqp::if( nqp::stat($path,nqp::const::STAT_ISDIR), nqp::stmts( nqp::if( nqp::fileislink($path), $path = IO::Path.new( $path,:CWD($!prefix)).resolve.absolute ), nqp::if( nqp::not_i(nqp::existskey($!seen,$path)) && ($!recurse || $!dir-accepts-files), nqp::stmts( nqp::bindkey($!seen,$path,1), nqp::push_s($!todo,$path) ) ) ) ) ) ) ) ); IterationEnd } method is-deterministic(--> False) { } } my class Directories does Iterator { has str $!prefix; # currently active prefix for entries has str $!dir-sep; # directory separator to use has $!dir-matcher; # matcher for accepting dir names has $!recurse; # recurse on non-matching dirs? has $!follow-symlinks; # whether to follow symlinks has $!handle; # currently active nqp::opendir() handle has $!todo; # list of abspaths of dirs to do still has $!seen; # has of abspaths of dirs seen already method !SET-SELF( str $abspath, $dir-matcher, $recurse, $follow-symlinks ) { # Set up first dir, return empty handed if failed nqp::handle( ($!handle := nqp::opendir($abspath)), 'CATCH', (return Rakudo::Iterator.Empty) ), $!dir-matcher := $dir-matcher; $!recurse := $recurse.Bool; $!follow-symlinks := $follow-symlinks; $!dir-sep = $*SPEC.dir-sep; $!seen := nqp::hash; $!todo := nqp::list_s; $!prefix = nqp::concat($abspath,$!dir-sep); self } method new( str $abspath, $dir-matcher, $recurse, $follow-symlinks ) { nqp::stat($abspath,nqp::const::STAT_EXISTS) && nqp::stat($abspath,nqp::const::STAT_ISDIR) ?? nqp::create(self)!SET-SELF( $abspath, $dir-matcher, $recurse, $follow-symlinks ) !! Rakudo::Iterator.Empty } method !entry(--> str) { nqp::until( nqp::isnull($!handle) || nqp::isnull_s(my str $entry = nqp::nextfiledir($!handle)) || (nqp::isne_s($entry,'.') && nqp::isne_s($entry,'..')), nqp::null ); nqp::if(nqp::isnull_s($entry),'',$entry) } method !next() { nqp::until( nqp::chars(my str $entry = self!entry), nqp::stmts( nqp::unless( nqp::isnull($!handle), nqp::stmts( nqp::closedir($!handle), ($!handle := nqp::null), ) ), nqp::if( nqp::elems($!todo), nqp::stmts( (my str $abspath = nqp::pop_s($!todo)), nqp::handle( ($!handle := nqp::opendir($abspath)), 'CATCH', 0 ), nqp::unless( nqp::isnull($!handle), ($!prefix = nqp::concat($abspath,$!dir-sep)) ) ), return '' # we're done, totally ) ) ); $entry } method pull-one() { nqp::while( nqp::chars(my str $entry = self!next), nqp::if( nqp::stat( (my str $path = nqp::concat($!prefix,$entry)), nqp::const::STAT_EXISTS ), nqp::if( $!follow-symlinks || nqp::not_i(nqp::fileislink($path)), nqp::if( nqp::stat($path,nqp::const::STAT_ISDIR), nqp::stmts( nqp::if( nqp::fileislink($path), $path = IO::Path.new( $path,:CWD($!prefix)).resolve.absolute ), (my $accepted := $!dir-matcher.ACCEPTS($entry)), nqp::if( nqp::not_i(nqp::existskey($!seen,$path)) && ($!recurse || $accepted), nqp::stmts( nqp::bindkey($!seen,$path,1), nqp::push_s($!todo,$path) ) ), nqp::if( $accepted, (return $path) ) ) ) ) ) ); IterationEnd } method is-deterministic(--> False) { } } my sub is-regular-file(str $path) is export { nqp::hllbool( nqp::stat($path,nqp::const::STAT_EXISTS) && nqp::stat($path,nqp::const::STAT_ISREG) ) } my sub paths( $abspath? is copy, Mu :$dir is copy, Mu :$file, :$recurse, :$follow-symlinks, Bool:D :$readable-files = True, --> Seq:D) is export { $abspath = ($abspath // "./").IO.absolute; $dir //= -> str $elem { nqp::not_i(nqp::eqat($elem,'.',0)) } Seq.new: $file<> =:= False ?? Directories.new: $abspath, $dir, $recurse, $follow-symlinks !! Files.new: $abspath, $dir, $file // True, $recurse, $follow-symlinks, $readable-files.Int } my sub EXPORT(*@names) { Map.new: @names ?? @names.map: { if UNIT::{"&$_"}:exists { UNIT::{"&$_"}:p } else { my ($in,$out) = .split(':', 2); if $out && UNIT::{"&$in"} -> &code { Pair.new: "&$out", &code } } } !! UNIT::.grep: { .key.starts-with('&') && .key ne '&EXPORT' } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- python::itertools ### -- Licenses: ### -- Authors: ### -- File: META6.json ### ---------------------------------------------------- { "perl" : "6.*", "name" : "python::itertools", "version" : "1.0.3", "description" : "Port of python itertools", "auth" : "zef:ahalbert", "depends" : [ ], "provides" : { "python::itertools" : "lib/python/itertools.rakumod" }, "source-url" : "git://github.com/ahalbert/raku-itertools.git" }
### ---------------------------------------------------- ### -- python::itertools ### -- Licenses: ### -- Authors: ### -- File: LICENSE ### ---------------------------------------------------- Copyright (c) <2016>, <Armand Halbert> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project.
### ---------------------------------------------------- ### -- python::itertools ### -- Licenses: ### -- Authors: ### -- File: README.md ### ---------------------------------------------------- Module ------ python::itertools - A direct port of Python's itertools to perl6. Description ----------- It provides all the functionality that python's itertools does, including lazy evaluation. In the future, I'd like to maximize the performance of these functions. Function signatures may be a little different. I needed a ``itertools.combinations_with_replacement`` and couldn't find an easy builtin or library to do it. So why not write the library myself? It turns out perl6 has most of these functions built in already. Unfortunatley, I did not realize that until after writing it. Oops. Copying ------- Copyright (c) 2016 Armand Halbert. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms in LICENSE. Prerequisites ------------- * perl6 (Obviously) Build/Installation ------------------ For now, clone from this repository. Author ------ Armand Halbert <[email protected]>
### ---------------------------------------------------- ### -- python::itertools ### -- Licenses: ### -- Authors: ### -- File: t/itertools.t ### ---------------------------------------------------- use v6; use Test; use lib 'lib'; use python::itertools; plan 37; is accumulate([1,2,3,4,5]), [1, 3, 6, 10, 15]; is accumulate((1,2,3,4,5)), [1, 3, 6, 10, 15]; is accumulate([1,2,3,4,5], func => &[*] ), [1, 2, 6, 24, 120]; is accumulate([1,2,3,4,5], initial => 100), [100, 101, 103, 106, 110, 115]; is accumulate([2,3,4,5], func => &[*], initial => -1 ), [-1, -2, -6, -24, -120]; dies-ok { batched(('a','b','c','d','e','f','g'), -1); }; is batched(('a','b','c','d','e','f','g'), 2), (('a', 'b'), ('c', 'd'), ('e', 'f'), ('g')); is chain((1,2,3,4),("a","b","c"),("1",2)), (1,2,3,4,"a","b","c","1",2); is combinations(('a','b','c','d'), 2), (('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d'), ('c','d')); is combinations_with_replacement(('a','b','c'), 2), (('a','a'), ('a','b'), ('a','c'), ('b','b'), ('b','c'), ('c','c')); is compress(['a','b','c','d'], [True,False,True,False]), ['a','c']; is compress(['a','b','c','d'], [1,1,0,1])[^3], ['a','b','d']; is count(10)[^5], (10,11,12,13,14); is count(10, 2)[^5], (10,12,14,16,18); dies-ok { cycle([]); }; is cycle(['a','b','c','d'])[^6], ['a','b','c','d','a','b']; is dropwhile([1,4,6,4,1], {$_ < 5;}), [6,4,1]; is filterfalse({ $_ % 2 == 1}, 0..5), [0,2,4]; is groupby(['a','b','a','a','a','b','b','c','a']), (('a','a','a','a','a'),('b','b','b'),('c')); is groupby(0..5, { $_ % 2 }), ((0, 2, 4),(1, 3, 5)); is islice(('a','b','c','d','e','f','g') , 2), ('a', 'b'); is islice(('a','b','c','d','e','f','g') , 2, 4), ('c', 'd'); is islice(('a','b','c','d','e','f','g') , 2, Nil), ('c', 'd', 'e', 'f', 'g'); is islice(('a','b','c','d','e','f','g') , 0, Nil, step => 2), ('a', 'c', 'e', 'g'); is pairwise(('a','b','c','d','e','f','g')), (('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g')); is pairwise(['a']), List; is permutations(('A', 'B', 'C', 'D'), 2), (('A', 'B') , ('A', 'C'), ('A','D'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')); is product([0,1], :repeat(3)), ((0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)); is product([0,1], [0,1]), ((0,0), (0,1), (1,0), (1,1)); is product([0,1], [0,1], :repeat(2)), ((0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)); dies-ok { repeat("3",-1)[^5]; }; is repeat("3",0)[^5], [3,3,3,3,3]; is repeat("3",3), [3,3,3]; is starmap(&sum, ((1,2,3), (4,5,6))), (6, 15); is takewhile([1,4,6,4,1], {$_ < 5;}), [1,4]; is tee(1..5 ,3), (1..5, 1..5, 1..5); is zip_longest((1,2,3,4),(1,2), (-1,-2,-3), :fillvalue("0")), ((1,1,-1), (2,2,-2), (3,"0",-3), (4, "0","0")); done-testing;
### ---------------------------------------------------- ### -- python::itertools ### -- Licenses: ### -- Authors: ### -- File: lib/python/itertools.rakumod ### ---------------------------------------------------- use v6; my $VERSION = "1.0.2"; unit module python::itertools; =begin pod =head1 NAME python::itertools =head1 SYNOPSIS A direct port of Python's itertools to perl6. =head1 DESCRIPTION It provides all the functionality that python's itertools does, including lazy evaluation. In the future, I'd like to maximize the performance of these functions. Function signatures may be a little different. I needed a itertools.combinations_with_replacement and couldn't find an easy builtin or library to do it. So why not write the library myself? It turns out raku has most of these functions built in already. Unfortunatley, I did not realize that until after writing it. Oops. =head1 FUNCTIONS =head2 accumulate(@iterable, $func=&[+]) Gathers accumulated sums, or accumulated results of other binary functions (specified via the optional $func argument). If $func is supplied, it should be a function of two arguments. =begin code accumulate((1,2,3,4,5)) --> (1, 3, 6, 10, 15) accumulate((1,2,3,4,5), &[*]) --> (1, 2, 6, 24, 120) =end code =head2 batched(@iterable, $n) groups items of @iterable into lists of size $n. If there's not enough to create a list of size $n, then takes the remaining items. =begin code batched(('a','b','c','d','e','f','g'), 2) -> (('a', 'b'), ('c', 'd'), ('e', 'f'), ('g')) =end code =head2 combinations(@iterable, $r) Gathers all combinations of length $r from @iterable, not allowing repeated elements =begin code combinations(('a','b','c','d'), 2) -> (('a','b'), ('a','c'), ('a','d'), ('b','c'), ('b','d'), ('c','d')); =end code =head2 combinations_with_replacement(@iterable, $r) Gathers all combinations of length $r from @iterable, allowing elements to repeat. =begin code combinations_with_replacement(('a','b','c'), 2) -> (('a','a'), ('a','b'), ('a','c'), ('b','a'), ('b','b'), ('b','c'), ('c','a'), ('c','b'), ('c','c')); =end code =head2 chain(*@iterables) Merges all of *@iterables into a single list. =begin code chain(("A","B","C"), ("D","E","F")) --> ("A", "B", "C", "D", "E", "F") =end code =head2 count($start is copy, $step=1) Gathers values from $start, increasing by $step each time. Infinte list. =begin code count(10)[^5] --> (10, 11, 12, 13, 14) count(10, 2)[^5], (10,12,14,16,18); =end code =head2 compress(@elements, @selectors) Returns all members of @elements where the corresponding ?@selector is True. =begin code compress(['a','b','c','d'], [True,False,True,False]) -> ['a','c'] =end code =head2 cycle(@iterable ) Creates an infinite repeating List from @iterable =begin code cycle(['a','b','c','d'])[^6] -> ['a','b','c','d','a','b'] =end code =head2 dropwhile(@elements, $predicate=Bool) Shifts @elements until $predicate evaluates to False and gathers remaining elements =begin code dropwhile([1,4,6,4,1], {$_ < 5;}) --> [6,4,1]; =end code =head2 filterfalse($predicate, @iterable) Filters elements from @iterable where $predicate is False =begin code filterfalse({ $_ % 2 == 1}, 0..5) -> [0,2,4]; =end code =head2 groupby(@iterable, $key={ $_} ) Groups elements into Lists by a function defined in $key. Default is the identity function. =begin code groupby(['a','b','a','a','a','b','b','c','a']) -> (('a','a','a','a','a'),('b','b','b'),('c')); groupby(0..5, { $_ % 2 }) -> ((0, 2, 4),(1, 3, 5)); =end code =head2 islice(@iterable, $stop) =head2 islice(@iterable, $start, $stop, :$step=1) Slices @iterable from $start to $stop, skipping $step-1 elements. If only $stop is defined, starts from 0. If $stop is Nil, uses the entire @iterable; =begin code islice(('a','b','c','d','e','f','g') , 2) -> ('a', 'b'); islice(('a','b','c','d','e','f','g') , 2, 4) -> ('c', 'd'); islice(('a','b','c','d','e','f','g') , 2, Nil) -> ('c', 'd', 'e', 'f', 'g'); islice(('a','b','c','d','e','f','g') , 0, Nil, step => 2) -> ('a', 'c', 'e', 'g'); =end code =head2 pairwise(@iterable) Creates sucessive overlapping pairs of elements from @iterable. If @iterable has less than 2 elements, returns empty list =begin code pairwise(('a','b','c','d','e','f','g')) -> (('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e'), ('e', 'f'), ('f', 'g')); pairwise(['a']) -> (); =end code =head2 permutations(@iterable, $r) Creates sucessive $r-length permutations from iterable. If $r is Nil, uses the length of @iterable as $r =begin code permutations(('A', 'B', 'C', 'D'), 2) -> (('A', 'B') , ('A', 'C'), ('A','D'), ('B', 'A'), ('B', 'C'), ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), ('D', 'B'), ('D', 'C')); =end code =head2 product(**@iterables, :$repeat=1) Duplicates each item in @iterables $repeat times and then creates the cartesian product of all items. =begin code product([0,1], :repeat(3)) -> ((0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)); product([0,1], [0,1]) -> ((0,0), (0,1), (1,0), (1,1)); product([0,1], [0,1], :repeat(2)) -> ((0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)); =end code =head2 repeat($obj, Int $times=0) Gathers $obj $times times or Infintely if $times is 0. =begin code repeat("3")[^5] -> [3,3,3,3,3]; repeat("3",3) -> [3,3,3]; =end code =head2 starmap($function, @iterable) Gathers items where each item in @iterable is computed with $function. Used instead of map when argument parameters are already grouped in tuples from a single iterable (the data has been “pre-zipped" =begin code starmap(&sum, ((1,2,3), (4,5,6))) -> (6, 15) =end code =head2 tee(@iterable, $n) Gathers $n independent @iterable; =begin code tee(1..5 ,3) -> (1..5, 1..5, 1..5); =end code =head2 takewhile(@elements, $predicate=Bool) Gathers items from @elements until $predicate evaluates to False. =begin code takewhile([1,4,6,4,1], {$_ < 5;}) -> [1,4]; =end code =head2 zip_longest(@elements, :$fillvalue=Nil) zips elements from each of @iterables. If the iterables are of uneven length, fillvalue replaces the missing values. Iteration continues until the longest iterable is exhausted. =begin code zip_longest((1,2,3,4),(1,2), (-1,-2,-3), :fillvalue("0")) -> ((1,1,-1), (2,2,-2), (3,"0",-3), (4, "0","0")); =end code =end pod sub accumulate(@iterable, :$func=&[+], :$initial=Nil) is export { my $accumulator = $initial; gather { for @iterable { if !$accumulator.defined { $accumulator = $_; } else { take $accumulator; $accumulator = $func($accumulator, $_); } } take $accumulator; } } sub batched(@iterable, $n) is export { my $index = 0; die "n must be greater than 0." if $n < 1; gather { while $index < @iterable.elems { take (@iterable[$index..$index+$n-1].grep({ $_ !=== Nil }).List); $index += $n; } } } sub chain(*@iterables) is export { @iterables } sub count($start is copy, $step=1) is export { $start, *+$step ... *; } #TODO: combinations sub combinations(@iterable, $r) is export { gather { combinations_helper(@iterable, [], $r, False); } } sub combinations_with_replacement(@iterable, $r) is export { gather { combinations_helper(@iterable, [], $r, True); } } sub combinations_helper(@iterable, @state, $r, $replacement=False) { for [email protected] { @state.push(@iterable[$_]); if $r > 1 { if $replacement { combinations_helper(@iterable[$_..*-1], @state, $r-1, $replacement); } else { combinations_helper(@iterable[$_+1..*-1], @state, $r-1, $replacement); } @state.pop; } else { my @return = @state.List; @state.pop; take @return; } } } sub compress(@elements, @selectors) is export { gather { for zip(@elements, @selectors) -> ($element, $selector) { take $element if (?$selector); } } } sub cycle(@iterable) is export { die "iterable must be a list" unless @iterable; gather { while True { take $_ for @iterable; } } } sub dropwhile(@elements, $predicate=Bool) is export { gather { my $index = 0; ++$index while $index < @elements.elems and $predicate(@elements[$index]); take $_ for @elements[$index..*-1]; } } sub filterfalse($predicate, @iterable) is export { @iterable.grep({ not $predicate($_); }).List; } sub groupby(@iterable is copy, $key={ $_ }) is export { gather { my @rest = @iterable.Array; while ?@rest { my $head = $key(@rest.first); take (@rest ==> grep { $head eqv $key($_)}).List; @rest = (@rest ==> grep { not ($head eqv $key($_))}); } } } multi sub islice(@iterable, $stop) is export { islice(@iterable, 0, $stop); } multi sub islice(@iterable, $start, $stop, :$step=1) is export { my $index = 0 ; gather { for @iterable { if ($index >= $start and ($stop === Nil or $index < $stop) and ($index - $start) % $step == 0) { take $_;} $index++; } } } sub pairwise(@iterable) is export { my $index = 0; return List if @iterable.elems < 2; gather { while $index < @iterable.elems - 1 { take @iterable[$index..$index+1]; $index += 1; } } } sub permutations(@iterable, $r=Nil) is export { $r = @iterable.elems if $r === Nil; gather { permutations_helper(@iterable, [], $r); } } sub permutations_helper(@iterable, @state, $r) { for [email protected] { @state.push(@iterable[$_]); if $r > 1 { if $_ == 0 { permutations_helper(@iterable[1..*-1], @state, $r-1); } elsif $_ == @iterable.elems - 1 { permutations_helper(@iterable[0..*-2], @state, $r-1); } else { permutations_helper((|@iterable[0..$_-1], |@iterable[$_+1..*-1]), @state, $r-1); } @state.pop; } else { my @return = @state.List; @state.pop; take @return; } } } sub product(**@iterables, :$repeat=1) is export { die unless $repeat > 0; if $repeat > 1 { my @repeated = (); @iterables = (@iterables ==> map -> @it {@it xx $repeat} ); for @iterables -> @it { for @it -> @r { @repeated.push(@r); } } @iterables = @repeated; } gather { take $_ for ([X] @iterables); } } sub repeat($obj, Int $times=0) is export { die "times-repeated in repeats must be > -1." unless $times >= 0; gather { if $times == 0 { take $obj while True; } else { take $obj for 1..$times; } } } sub starmap($function, @iterable) is export { @iterable.map({.$function}) } sub takewhile(@elements, $predicate=Bool) is export { gather { for @elements { last unless $predicate($_); take $_; } } } sub tee(@iterable is copy, Int $n) is export { gather { take @iterable for 1..$n; } } sub zip_longest(**@iterables, :$fillvalue = Nil) is export { my $longest = (@iterables ==> map -> @it { @it.elems } ==> max); my $index = 0; gather { while $index < $longest { my @result = (); for @iterables -> @it { if $index < @it.elems { @result.push(@it[$index]); } else { @result.push($fillvalue); } } take @result; ++$index; } } }
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: META6.json ### ---------------------------------------------------- { "auth": "zef:lizmat", "authors": [ "Elizabeth Mattijsen" ], "build-depends": [ ], "depends": [ "Git::Files:ver<0.0.8+>:auth<zef:lizmat>", "hyperize:ver<0.0.4+>:auth<zef:lizmat>", "paths:ver<10.1+>:auth<zef:lizmat>", "path-utils:ver<0.0.21+>:auth<zef:lizmat>", "Trap:ver<0.0.2+>:auth<zef:lizmat>" ], "description": "Plumbing to be able to look for stuff", "license": "Artistic-2.0", "name": "rak", "perl": "6.d", "provides": { "rak": "lib/rak.rakumod" }, "resources": [ ], "source-url": "https://github.com/lizmat/rak.git", "tags": [ "RAK", "SEARCH", "PLUMBING" ], "test-depends": [ ], "version": "0.0.65" }
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: README.md ### ---------------------------------------------------- ### -- Chunk 1 of 2 [![Actions Status](https://github.com/lizmat/rak/actions/workflows/linux.yml/badge.svg)](https://github.com/lizmat/rak/actions) [![Actions Status](https://github.com/lizmat/rak/actions/workflows/macos.yml/badge.svg)](https://github.com/lizmat/rak/actions) [![Actions Status](https://github.com/lizmat/rak/actions/workflows/windows.yml/badge.svg)](https://github.com/lizmat/rak/actions) NAME ==== rak - plumbing to be able to look for stuff SYNOPSIS ======== ```raku use rak; # look for "foo" in all .txt files from current directory my $rak = rak / foo /, :file(/ \.txt $/); # show results for $rak.result -> (:key($path), :value(@found)) { if @found { say "$path:"; say .key ~ ':' ~ .value for @found; } } ``` DESCRIPTION =========== The `rak` subroutine provides a mostly abstract core search (plumbing) functionality to be used by modules such as (porcelain) `App::Rak`. THEORY OF OPERATION =================== The `rak` subroutine basically goes through 6 steps to produce a `Rak` object. ### 1. Acquire sources The first step is determining the objects that should be searched for the specified pattern. If an object is a `Str`, it will be assumed that it is a path specification of a file to be searched in some form and an `IO::Path` object will be created for it. Related named arguments are (in alphabetical order): <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:dir</td> <td>filter for directory basename check to include</td> </tr> <tr> <td>:file</td> <td>filter for file basename check to include</td> </tr> <tr> <td>:files-from</td> <td>file containing filenames as source</td> </tr> <tr> <td>:ioify</td> <td>code to create IO::Path-like objects with</td> </tr> <tr> <td>:paths</td> <td>paths to recurse into if directory</td> </tr> <tr> <td>:paths-from</td> <td>file containing paths to recurse into</td> </tr> <tr> <td>:recurse-symlinked-dir</td> <td>recurse into symlinked directories</td> </tr> <tr> <td>:recurse-unmatched-dir</td> <td>recurse into directories not matching :dir</td> </tr> <tr> <td>:sources</td> <td>list of objects to be considered as source</td> </tr> <tr> <td>:under-version-control</td> <td>only include paths under version control</td> </tr> </tbody> </table> The result of this step, is a (potentially lazy and hyperable) sequence of objects. ### 2. Filter applicable objects Filter down the list of sources from step 1 on any additional filesystem related properties. This assumes that the list of objects created are strings of absolute paths to be checked (except where otherwise indicated). <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:accept</td> <td>given an IO::Path, is path acceptable</td> </tr> <tr> <td>:accessed</td> <td>when was path last accessed</td> </tr> <tr> <td>:blocks</td> <td>number of filesystem blocks</td> </tr> <tr> <td>:created</td> <td>when was path created</td> </tr> <tr> <td>:deny</td> <td>given an IO::Path, is path NOT acceptable</td> </tr> <tr> <td>:device-number</td> <td>device number on which path is located</td> </tr> <tr> <td>:exec</td> <td>run program, include if successful</td> </tr> <tr> <td>:filesize</td> <td>size of the path in bytes</td> </tr> <tr> <td>:gid</td> <td>numeric gid of the path</td> </tr> <tr> <td>:hard-links</td> <td>number of hard-links to path on filesystem</td> </tr> <tr> <td>:has-setgid</td> <td>has SETGID bit set in attributes</td> </tr> <tr> <td>:has-setuid</td> <td>has SETUID bit set in attributes</td> </tr> <tr> <td>:inode</td> <td>inode of path on filesystem</td> </tr> <tr> <td>:is-empty</td> <td>is path empty (filesize == 0)</td> </tr> <tr> <td>:is-executable</td> <td>is path executable by current user</td> </tr> <tr> <td>:is-group-executable</td> <td>is path executable by group</td> </tr> <tr> <td>:is-group-readable</td> <td>is path readable by group</td> </tr> <tr> <td>:is-group-writable</td> <td>is path writable by group</td> </tr> <tr> <td>:is-moarvm</td> <td>is path a MoarVM bytecode file</td> </tr> <tr> <td>:is-owned-by-group</td> <td>is path owned by group of current user</td> </tr> <tr> <td>:is-owned-by-user</td> <td>is path owned by current user</td> </tr> <tr> <td>:is-owner-executable</td> <td>is path executable by owner</td> </tr> <tr> <td>:is-owner-readable</td> <td>is path readable by owner</td> </tr> <tr> <td>:is-owner-writable</td> <td>is path writable by owner</td> </tr> <tr> <td>:is-pdf</td> <td>is path a PDF file</td> </tr> <tr> <td>:is-readable</td> <td>is path readable by current user</td> </tr> <tr> <td>:is-sticky</td> <td>has STICKY bit set in attributes</td> </tr> <tr> <td>:is-symbolic-link</td> <td>is path a symbolic link</td> </tr> <tr> <td>:is-text</td> <td>does path contains text?</td> </tr> <tr> <td>:is-world-executable</td> <td>is path executable by any user</td> </tr> <tr> <td>:is-world-readable</td> <td>is path readable by any user</td> </tr> <tr> <td>:is-world-writable</td> <td>is path writable by any user</td> </tr> <tr> <td>:is-writable</td> <td>is path writable by current user</td> </tr> <tr> <td>:meta-modified</td> <td>when meta information of path was modified</td> </tr> <tr> <td>:mode</td> <td>the mode of the path</td> </tr> <tr> <td>:modified</td> <td>when path was last modified</td> </tr> <tr> <td>:shell</td> <td>run shell command, include if successful</td> </tr> <tr> <td>:uid</td> <td>numeric uid of path</td> </tr> </tbody> </table> The result of this step, is a (potentially lazy and hyperable) sequence of objects. ### 3. Produce items to search in (apply transformers) The third step is to create the logic for creating items to search in from the objects in step 2. If search is to be done per object, then `.slurp` is called on the object. Otherwise `.lines` is called on the object. Unless one provides their own logic for producing items to search in. Related named arguments are (in alphabetical order): <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:encoding</td> <td>encoding to be used when creating items</td> </tr> <tr> <td>:find</td> <td>map sequence of step 1 to item producer</td> </tr> <tr> <td>:produce-one</td> <td>produce one item per given source</td> </tr> <tr> <td>:produce-many</td> <td>produce zero or more items by given source</td> </tr> <tr> <td>:produce-many-pairs</td> <td>produce zero or more items by given source as pairs</td> </tr> <tr> <td>:omit-item-number</td> <td>do not store item numbers in result</td> </tr> <tr> <td>:with-line-ending</td> <td>produce lines with line endings</td> </tr> </tbody> </table> The result of this step, is a (potentially lazy and hyperable) sequence of objects. ### 4. Create logic for matching Take the logic of the pattern `Callable`, and create a `Callable` to do the actual matching with the items produced in step 3. Related named arguments are (in alphabetical order): <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:invert-match</td> <td>invert the logic of matching</td> </tr> <tr> <td>:old-new</td> <td>produce pairs of old/new state</td> </tr> <tr> <td>:quietly</td> <td>absorb any warnings produced by the matcher</td> </tr> <tr> <td>:silently</td> <td>absorb any output done by the matcher</td> </tr> <tr> <td>:stats</td> <td>produce results and full statistics</td> </tr> <tr> <td>:stats-only</td> <td>don&#39;t produce results, just statistics</td> </tr> </tbody> </table> ### 5. Create logic for running Take the matcher logic of the `Callable` of step 4 and create a runner `Callable` that will produce the items found and their possible context (such as extra items before or after). Assuming no context, the runner changes a return value of `False` from the matcher into `Empty`, a return value of `True` in the original item, and passes through any other value. Related named arguments are (in alphabetical order): <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:also-first</td> <td>initial items to show if there is a match</td> </tr> <tr> <td>:always-first</td> <td>initial items to show always</td> </tr> <tr> <td>:after-context</td> <td>number of items to show after a match</td> </tr> <tr> <td>:before-context</td> <td>number of items to show before a match</td> </tr> <tr> <td>:context</td> <td>number of items to show around a match</td> </tr> <tr> <td>:paragraph-context</td> <td>items around match until false item</td> </tr> <tr> <td>:passthru-context</td> <td>pass on *all* items if there is a match</td> </tr> <tr> <td>:max-matches-per-source</td> <td>max # of matches per source</td> </tr> <tr> <td>:passthru</td> <td>pass on *all* items always</td> </tr> </tbody> </table> Matching items are represented by `PairMatched` objects, and items that have been added because of the above context arguments, are represented by `PairContext` objects. Unless `:omit-item-number` has been specified with a trueish value, in which case items will always be just a string, whether they matched or not (if part of a context specification). ### 6. Run the sequence(s) The final step is to take the `Callable` of step 5 and run that repeatedly on the sequence of step 3. Make sure any phasers (`FIRST`, `NEXT` and `LAST`) are called at the appropriate time in a thread-safe manner. Inside the `Callable` of step 5, the dynamic variable `$*SOURCE` will be set to the source of the items being checked. Either produces a sequence in which the key is the source, and the value is a `Slip` of `Pair`s where the key is the item-number and the value is item with the match, or whatever the pattern matcher returned. Or, produces sequence of whatever a specified mapper returned and/or with uniqueifying enabled. Related named arguments are (in alphabetical order): <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>:categorize</td> <td>classify items according to zero or more keys</td> </tr> <tr> <td>:classify</td> <td>classify items according to a single key</td> </tr> <tr> <td>:eager</td> <td>produce all results before creating Rak object</td> </tr> <tr> <td>:frequencies</td> <td>produce items and their frequencies</td> </tr> <tr> <td>:map-all</td> <td>also call mapper if a source has no matches</td> </tr> <tr> <td>:mapper</td> <td>code to map results of a single source</td> </tr> <tr> <td>:progress</td> <td>code to show progress of running</td> </tr> <tr> <td>:sort</td> <td>sort the result of :unique</td> </tr> <tr> <td>:sort-sources</td> <td>sort the sources before processing</td> </tr> <tr> <td>:sources-only</td> <td>only produce the source of any match</td> </tr> <tr> <td>:sources-without-only</td> <td>produce the source without any match</td> </tr> <tr> <td>:unique</td> <td>only produce unique items</td> </tr> </tbody> </table> EXPORTED CLASSES ================ Rak --- The return value of a `rak` search. Contains the following attributes: ### completed A `Bool` indicating whether the search has already been completed. ### exception Any `Exception` object that was caught. ### nr-changes Number of items (that would have been) changed. ### nr-items Number of items inspected. ### nr-matches Number of items that matched. ### nr-passthrus Number of items that have passed through. ### nr-sources Number of sources seen. ### result A `Seq` with search results. This could be a lazy `Seq` or a `Seq` on a fully vivified `List`. ### stats A `Map` with any statistics collected (so far, in case an exception was thrown). If the `Map` is not empty, it contains the following keys: <table class="pod-table"> <thead><tr> <th>argument</th> <th>meaning</th> </tr></thead> <tbody> <tr> <td>nr-sources</td> <td>number of sources seen</td> </tr> <tr> <td>nr-items</td> <td>number of items inspected</td> </tr> <tr> <td>nr-matches</td> <td>number of items that matched</td> </tr> <tr> <td>nr-passthrus</td> <td>number of items that have passed through</td> </tr> <tr> <td>nr-changes</td> <td>number of items that would have been changed</td> </tr> </tbody> </table> If the `Map` is empty, then no statistics (other than `nr-sources`) have been collected. Note that if the result is lazy, then the statistics won't be complete until every result has been processed. PairContext ----------- A subclass of `Pair` of which both the `matched` **and** `changed` method return `False`. Used for non-matching items when item-numbers are required to be returned and a certain item context was requested. PairMatched ----------- A subclass of `PairContext` of which the `matched` method returns `True`, but the `changed` method returns `False`. Used for matching items when item-numbers are required to be returned. PairChanged ----------- A subclass of `PairMatched` of which the `matched` **and** `changed` method return `True`. Used for changed items when item-numbers are required to be returned. Progress -------- Passed to the `:progress` `Callable` 5 times per second while searching is taking place. It provides several methods that allow a search application to show what is going on. ### nr-changes Number of items (that would have been) changed. Continuously updated if the search has not been completed yet. ### nr-items Number of items inspected. Continuously updated if the search has not been completed yet. ### nr-matches Number of items that matched. Continuously updated if the search has not been completed yet. ### nr-passthrus Number of items that have passed through. Continuously updated if the search has not been completed yet. ### nr-sources Number of sources seen. Continuously updated if the search has not been completed yet. EXPORTED SUBROUTINES ==================== rak --- The `rak` subroutine takes a `Callable` (or `Regex`) pattern as the only positional argument and quite a number of named arguments. Or it takes a `Callable` (or `Regex`) as the first positional argument for the pattern, and a hash with named arguments as the second positional argument. In the latter case, the hash will have the arguments removed that the `rak` subroutine needed for its configuration and execution. ### Return value A `Rak` object (see above) is always returned. The object provides three attributes: `result` (with the result `Iterable`), `completed` (a Bool indicating whether all searching has been done already), and `exception` (any `Exception` object or `Nil`). Additionally it provides five methods that allow you to monitor progress and/or provide statistics at the end of a search. They are: `nr-sources`, `nr-items`, `nr-matches`, `nr-changes`, `nr-passthrus`. #### Result Iterable If the `:unique` argument was specified with a trueish value, then the result `Iterable` will just produce the unique values that were either explicitely returned by the matcher, or the unique items that matched. Otherwise the value is an `Iterable` of `Pair`s which contain the source object as key (by default the absolute path of the file in which the pattern was found). If there was only one item produced per source, then the value will be that value, or whatever was produced by the matching logic. Otherwise the value will be a `Slip`. If no item numbers were requested, each element contains the result of matching. If item-numbers were requested, each element is a `Pair`, of which the key is the item-number where the pattern was found, and the value is the product of the search (which, by default, is the item in which the pattern was found). In a graph: rak(...) |- Rak |- exception: Exception object or Nil |- nr-sources: number of sources seen |- nr-items: number of items seen |- nr-matches: number of matches seen |- nr-changes: number of changes (that could be) done |- nr-passthrus: number of passthrus done |- completed: Bool whether all searching done already |- result: Iterable |- Pair | |- key: source object | |- value: | |- Slip | | |- PairMatched|PairContext | | | |- key: item-number | | | \- value: match result | | or | | \- match result | or | \- single item match result or \- unique match result ### Named Arguments The following named arguments can be specified (in alphabetical order): #### :accept(&filter) If specified, indicates a `Callable` filter that will be given an `IO::Path` of the path. It should return `True` if the path is acceptable. #### :accessed(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **access** time of the path. The `Callable` is passed a `Num` value of the access time (number of seconds since epoch) and is expected to return a trueish value to have the path be considered for further selection. #### :after-context(N) Indicate the number of items that should also be returned **after** an item with a pattern match. Defaults to **0**. #### :also-first(N) Indicate the number of initial items to be produced **if** there is an item with a pattern match. Defaults to **0**. If specified as a flag, will assume **1**. #### :always-first(N) Indicate the number of initial items to be **always** be produced regardless whether there is an item with a pattern match or not. Defaults to **0**. If specified as a flag, will assume **1**. #### :batch(N) When hypering over multiple cores, indicate how many items should be processed per thread at a time. Defaults to whatever the system thinks is best (which **may** be sub-optimal). #### :before-context(N) Indicate the number of items that should also be returned **before** an item with a pattern match. Defaults to **0**. #### :blocks(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **number of blocks** used by the path on the filesystem on which the path is located. The `Callable` is passed the number of blocks of a path and is expected to return a trueish value to have the path be considered for further selection. #### :categorize(&categorizer) If specified, indicates the `Callable` that should return zero or more keys for a given item to have it categorized. This effectively replaces the source if an item by any of its key in the result. The result will contain the key/item(s) pairs ordered by most to least number of items per key. #### :classify(&classifier) If specified, indicates the `Callable` that should return a key for a given item to have it classified. This effectively replaces the source if an item by its key in the result. The result will contain the key/item(s) pairs ordered by most to least number of items per key. #### :context(N) Indicate the number of items that should also be returned around an item with a pattern match. Defaults to **0**. #### :created(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **creation** time of the path. The `Callable` is passed a `Num` value of the creation time (number of seconds since epoch) and is expected to return a trueish value to have the path be considered for further selection. #### :degree(N) When hypering over multiple cores, indicate the maximum number of threads that should be used. Defaults to whatever the system thinks is best (which **may** be sub-optimal). #### :deny(&filter) If specified, indicates a `Callable` filter that will be given an `IO::Path` of the path. It should return `True` if the path is **NOT** acceptable. #### :device-number(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **device number** of the path. The `Callable` is passed the device number of the device on which the path is located and is expected to return a trueish value to have the path be considered for further selection. #### :dir(&dir-matcher) If specified, indicates the matcher that should be used to select acceptable directories with the `paths` utility. Defaults to `True` indicating **all** directories should be recursed into. Applicable for any situation where `paths` is used to create the list of files to check. #### :dont-catch Flag. If specified with a trueish value, will **not** catch any error during processing, but will throw any error again. Defaults to `False`, making sure that errors **will** be caught. #### :eager Flag. If specified with a trueish value, will **always** produce **all** results before returning the `Rak` object. Defaults to `False`, making result production lazy if possible. #### :encoding("utf8-c8") When specified with a string, indicates the name of the encoding to be used to produce items to check (typically by calling `lines` or `slurp`). Defaults to `utf8-c8`, the UTF-8 encoding that is permissive of encoding issues. #### :exec($invocation) If specified, indicates the name of a program and its arguments to be executed. Any `$_` in the invocation string will be replaced by the file being checked. The file will be included if the program runs to a successful conclusion. #### :file(&file-matcher) If specified, indicates the matcher that should be used to select acceptable files with the `paths` utility. Defaults to `True` indicating **all** files should be checked. Applicable for any situation where `paths` is used to create the list of files to check. If the boolean value `False` is specified, then only directory paths will be produced. This only makes sense if `:find` is also specified. #### :filesize(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **number of bytes** of the path. The `Callable` is passed the number of bytes of a path and is expected to return a trueish value to have the path be considered for further selection. #### :files-from($filename) If specified, indicates the name of the file from which a list of files to be used as sources will be read. #### :find Flag. If specified, maps the sources of items into items to search. #### :frequencies Flag. If specified, produces key/value `Pair`s in which the key is the item, and the value is the frequency with which the item was seen. #### :gid(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **gid** of the path. The `Callable` is passed the numeric gid of a path and is expected to return a trueish value to have the path be considered for further selection. See also `owner` and `group` filters. #### :hard-links(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **number of hard-links** of the path. The `Callable` is passed the number of hard-links of a path and is expected to return a trueish value to have the path be considered for further selection. #### :has-setgid Flag. If specified, indicates paths that have the SETGID bit set in their attributes, are (not) acceptable for further selection. Usually only makes sense when uses together with `:find`. #### :has-setuid Flag. If specified, indicates paths that have the SETUID bit set in their attributes, are (not) acceptable for further selection. Usually only makes sense when uses together with `:find`. #### :inode(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **inode** of the path. The `Callable` is passed the inode of a path and is expected to return a trueish value to have the path be considered for further selection. #### :invert-match Flag. If specified with a trueish value, will negate the return value of the pattern if a `Bool` was returned. Defaults to `False`. #### :ioify(&coercer) If specified, indicates the `Callable` that will be called with a path and which should return an object on which `.lines` and `.slurp` can be called. Defaults to `*.IO`, creating an `IO::Path` object by default. #### :is-empty Flag. If specified, indicates paths, that are empty (aka: have a filesize of 0 bytes), are (not) acceptable for further selection. Usually only makes sense when uses together with `:find`. #### :is-executable Flag. If specified, indicates paths, that are **executable** by the current **user**, are (not) acceptable for further selection. #### :is-group-executable Flag. If specified, indicates paths, that are **executable** by the current **group**, are (not) acceptable for further selection. #### :is-group-readable Flag. If specified, indicates paths, that are **readable** by the current **group**, are (not) acceptable for further selection. #### :is-group-writable Flag. If specified, indicates paths, that are **writable** by the current **group**, are (not) acceptable for further selection. #### :is-moarvm Flag. If specified, indicates only paths that are `MoarVM` bytecode files are (not) acceptable for further selection. #### :is-owned-by-group Flag. If specified, indicates only paths that are **owned** by the **group** of the current user, are (not) acceptable for further selection. #### :is-owned-by-user Flag. If specified, indicates only paths that are **owned** by the current **user**, are (not) acceptable for further selection. #### :is-owner-executable Flag. If specified, indicates paths, that are **executable** by the owner, are (not) acceptable for further selection. #### :is-owner-readable Flag. If specified, indicates paths, that are **readable** by the owner, are (not) acceptable for further selection. #### :is-owner-writable Flag. If specified, indicates paths, that are **writable** by the owner, are (not) acceptable for further selection. #### :is-pdf Flag. If specified, indicates only paths that are `PDF` files are (not) acceptable for further selection. #### :is-readable Flag. If specified, indicates paths, that are **readable** by the current **user**, are (not) acceptable for further selection. #### :is-sticky Flag. If specified, indicates paths that have the STICKY bit set in their attributes, are (not) acceptable for further selection. Usually only makes sense when uses together with `:find`. #### :is-symbolic-link Flag. If specified, indicates only paths that are symbolic links, are (not) acceptable for further selection. #### :is-text Flag. If specified, indicates only paths that contain text are (not) acceptable for further selection. #### :is-world-executable Flag. If specified, indicates paths, that are **executable** by any user or group, are (not) acceptable for further selection. #### :is-world-readable Flag. If specified, indicates paths, that are **readable** by any user or group, are (not) acceptable for further selection. #### :is-world-writeable Flag. If specified, indicates paths, that are **writable** by any user or group, are (not) acceptable for further selection. #### :is-writable Flag. If specified, indicates paths, that are **writable** by the current **user**, are (not) acceptable for further selection. #### :mapper(&mapper) If specified, indicates the `Callable` that will be called (in a thread-safe manner) for each source, with the matches of that source. The `Callable` is passed the source object, and a list of matches, if there were any matches. If you want the `Callable` to be called for every source, then you must also specify `:map-all`. Whatever the mapper `Callable` returns, will become the result of the call to the `rak` subroutine. If you don't want any result to be returned, you can return `Empty` from the mapper `Callable`. #### :map-all Flag. If specified with a trueish value, will call the mapper logic, as specified with `:mapper`, even if a source has no matches. Defaults to `False`. #### :max-matches-per-source(N) Indicate the maximum number of items that may be produce per source. Defaults to **all** (which can also be specified by a falsish value). #### :meta-modified(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **modification** time of the path. The `Callable` is passed a `Num` value of the modification time (number of seconds since epoch) and is expected to return a trueish value to have the path be considered for further selection. #### :mode(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **mode** of the path. The `Callable` is passed the mode of a path and is expected to return a trueish value to have the path be considered for further selection. This is really for advanced types of tests: it's probably easier to use any of the `readable`, `writeable` and `executable` filters. #### :modified(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **modification** time of the path. The `Callable` is passed a `Num` value of the modification time (number of seconds since epoch) and is expected to return a trueish value to have the path be considered for further selection. #### :old-new Flag. If specified with a trueish value, will produce `Pair`s of the current value being investigated, and whatever was returned by the `Callable` pattern for that value (if what was returned was **not** a `Bool`, `Empty` or `Nil`) **if** that value was different from the original value. Defaults to `False`, meaning to just produce according to what was returned. #### :omit-item-number Flag. If specified with a trueish value, won't produce any `PairMatched` or `PairContext` objects in the result, but will just produce the result of the match. Defaults to `False`, meaning to include item numbers. #### :paragraph-context Flag. If specified with a trueish value, produce items **around** the empty with a pattern match until a falsish item is encountered. #### :passthru Flag. If specified with a trueish value, produces **all** items always. #### :passthru-context Flag. If specified with a trueish value, produces **all** items if there is at least one match. #### :paths-from($filename) If specified, indicates the name of the file from which a list of paths to be used as the base of the production of filename with a `paths` search. #### :paths(@paths) If specified, indicates a list of paths that should be used as the base of the production of filename with a `paths` search. If there is no other sources specification (from either the `:files-from`, `:paths-from` or `:sources`) then the current directory (aka ".") will be assumed. If that directory appears to be the top directory in a git repository, then `:under-version-control` will be assumed, only producing files that are under version control under that directory. #### :produce-many(&producer) If specified, indicates a `Callable` that will be called given a source, and is expected to produce zero or more items to be inspected. Defaults to a producer that calles the `lines` method on a given source, with the `:encoding` and `:with-line-ending` arguments. The `Callable` should return `Empty` if for some reason nothing could be produced. #### :produce-many-pairs(&producer) If specified, indicates a `Callable` that will be called given a source, and is expected to produce zero or more `PairContext` objects to be inspected, in which the key represents the item number. This option will set the `:omit-item-number` option to `False`. The `Callable` should return `Empty` if for some reason nothing could be produced. #### :produce-one(&producer) If specified, indicates a `Callable` that will be called given a source, and is expected to produce one items to be inspected. The `Callable` should return `Nil` if
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: README.md ### ---------------------------------------------------- ### -- Chunk 2 of 2 for some reason nothing could be produced). #### :progress(&announcer) If specified, indicates a `Callable` that will be called 5 times per second to indicate how the search action is progressing. It will either be called with a `Progress` object (while the search action is still progressing) or **without** any arguments to indicate that search has completed. #### :recurse-symlinked-dir Flag. If specified with a trueish value, will recurse into directories that are actually symbolic links. The default is `False`: do **not** recurse into symlinked directories. #### :recurse-unmatched-dir Flag. If specified with a trueish value, will recurse into directories that did **not** pass the :<dir>. No files will ever be produced from such directories, but further recursion will be done if directories are encountered. The default is `False`: do **not** recurse into directories that didn't match the `:dir` specification. #### :quietly Flag. If specified with a trueish value, will absorb any warnings that may occur when looking for the pattern. #### :shell($invocation) If specified, indicates the command(s) to be executed in a shell. Any `$_` in the invocation string will be replaced by the file being checked. The file will be included if the shell command(s) run to a successful conclusion. #### :silently("out,err") When specified with `True`, will absorb any output on STDOUT and STDERR. Optionally can only absorb STDOUT ("out"), STDERR ("err") and both STDOUT and STDERR ("out,err"). #### :sort(&logic) When specified with `True`, will sort the result alphabetically (using foldcase logic). Can also be specified with a `Callable`, which should contain the logic sorting (just as the argument to the `.sort` method). Only supported with `:unique` at this time. #### :sort-sources(&logic) When specified with `True`, will sort the sources alphabetically (using foldcase logic). Can also be specified with a `Callable`, which should contain the logic sorting (just as the argument to the `.sort` method). #### :sources(@objects) If specified, indicates a list of objects that should be used as a source for the production of items. Which generally means they cannot be just strings. #### :sources-only Flag. If specified with a trueish value, will only produce the source of a match once per source. Defaults to `False`. #### :sources-without-only Flag. If specified with a trueish value, will only produce the source of a match if there is **not** a single match. Defaults to `False`. #### :stats Flag. If specified with a trueish value, will keep stats on number number of items seen, number of matches, number of changes and number of passthrus. Stats on number of sources seen, will always be kept. Note that on lazy results, the statistics won't be complete until all results have been processed. #### :stats-only Flag. If specified with a trueish value, will perform all searching, but only update counters and not produce any result. The statistics will be available in `nr-xxx` methods, and the `result` attribute will be `Empty`. Note that this causes eager evaluation. #### :uid(&filter) If specified, indicates the `Callable` filter that should be used to select acceptable paths by the **uid** of the path. The `Callable` is passed the numeric uid of a path and is expected to return a trueish value to have the path be considered for further selection. See also `owner` and `group` filters. #### :under-version-control($name = 'git') If specified, indicates that any path specification that is a directory, should be considered as the root of a directory structure under some form of version control. If specified as `True`, will assume `git`. If such a path is under version control, then only files that are actually controlled, will be produced for further inspection. If it is **not** under version control, **no** files will be produced. Currently, only `git` is supported. #### :unique Flag. If specified, indicates that only unique matches will be returned, instead of the normal sequence of source => result pairs. #### :with-line-ending Flag. If specified, indicates line endings are to be kept when producing items to check. Defaults to `False`, meaning that line endings are removed from items to check. Only applicable with line-based checking. PATTERN RETURN VALUES --------------------- The return value of the pattern `Callable` match is interpreted in the following way: ### True If the `Bool`ean True value is returned, assume the pattern is found. Produce the item unless `:invert-match` was specified. ### False If the `Bool`ean False value is returned, assume the pattern is **not** found. Do **not** produce the item unless `:invert-match` was specified. ### Nil If `Nil` is returned, assume the pattern is **not** found. This can typically happen when a `try` is used in a pattern, and an execution error occurred. Do **not** produce the item unless `:invert-match` was specified. ### Empty If the empty `Slip` is returned, assume the pattern is **not** found. Do **not** produce the item unless `:invert-match` was specified. Shown in stats as a `passthru`. ### any other value Produce that value. PHASERS ------- Any `FIRST`, `NEXT` and `LAST` phaser that are specified in the pattern `Callable`, will be executed at the correct time. MATCHED ITEMS vs CONTEXT ITEMS ------------------------------ The `Pair`s that contain the search result within an object, have an additional method mixed in: `matched`. This returns `True` for items that matched, and `False` for items that have been added because of a context specification (`:context`, `:before-context`, `:after-context`, `paragraph-context` or `passthru-context`). These `Pair`s can also be recognized by their class: `PairMatched` versus `PairContext`, which are also exported. AUTHOR ====== Elizabeth Mattijsen <[email protected]> Source can be located at: https://github.com/lizmat/rak . Comments and Pull Requests are welcome. If you like this module, or what I’m doing more generally, committing to a [small sponsorship](https://github.com/sponsors/lizmat/) would mean a great deal to me! COPYRIGHT AND LICENSE ===================== Copyright 2022, 2023, 2024, 2025 Elizabeth Mattijsen This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: dist.ini ### ---------------------------------------------------- name = rak [ReadmeFromPod] ; enabled = false filename = doc/rak.rakudoc [UploadToZef] [PruneFiles] ; match = ^ 'xt/' [Badges] provider = github-actions/linux.yml provider = github-actions/macos.yml provider = github-actions/windows.yml
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: t/01-basic.rakutest ### ---------------------------------------------------- use Test; use rak; plan 1; ok MY::<&rak>, 'did rak get exported'; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/coverage.rakutest ### ---------------------------------------------------- use Test::Coverage; plan 2; todo "needs more tests"; coverage-at-least 75; todo "needs more tests"; uncovered-at-most 1; source-with-coverage; report; # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: xt/02-simple.rakutest ### ---------------------------------------------------- BEGIN %*ENV<RAKU_TEST_DIE_ON_FAIL> = 1; use Test; use rak; plan 58; my $dir := $*TMPDIR.add("rak"); my @targets := <zero one two three four five six seven eight nine>; my %name2path = @targets.map: { $_ => $dir.add($_).absolute } my %path2name = %name2path.kv.reverse; my $append := $dir.add("append"); my $append-path := $append.absolute; $dir.mkdir; for @targets.kv -> $n, $name { %name2path{$name}.IO.spurt: @targets[0..$n].join("\n") ~ "\n"; is %name2path{$name}.IO.slurp, @targets[0..$n].join("\n") ~ "\n", "is the file for $name ok?"; } LEAVE { .IO.unlink for %name2path.values; $append.unlink; $dir.rmdir } # Line locations and their contents for matches my \l0 = PairMatched.new: 1, "zero"; my \L0 = PairMatched.new: 1, "ZERO"; my \C0 = PairChanged.new: 1, "ZERO"; my \l1 = PairMatched.new: 2, "one"; my \l2 = PairMatched.new: 3, "two"; my \o2 = PairChanged.new: 3, "two" => "tvo"; my \L2 = PairMatched.new: 3, "TWO"; my \C2 = PairChanged.new: 3, "TWO"; my \l3 = PairMatched.new: 4, "three"; my \l4 = PairMatched.new: 5, "four"; my \l5 = PairMatched.new: 6, "five"; my \l6 = PairMatched.new: 7, "six"; my \l7 = PairMatched.new: 8, "seven"; my \l8 = PairMatched.new: 9, "eight"; my \l9 = PairMatched.new: 10, "nine"; my \L9 = PairMatched.new: 10, "NINE"; # Line locations and their contents for contexts my \c0 = PairContext.new: 1, "zero"; my \c1 = PairContext.new: 2, "one"; my \c2 = PairContext.new: 3, "two"; my \c3 = PairContext.new: 4, "three"; my \c4 = PairContext.new: 5, "four"; my \c5 = PairContext.new: 6, "five"; my \c6 = PairContext.new: 7, "six"; my \c7 = PairContext.new: 8, "seven"; my \c8 = PairContext.new: 9, "eight"; my \c9 = PairContext.new: 10, "nine"; my sub lookup( $pattern is copy, *@expected, *%additional ) is test-assertion { my $code; if Callable.ACCEPTS($pattern) { $code = $pattern; $pattern = %additional<name>:delete; } else { $code = try $pattern.EVAL; } my &needle := $code // *.contains($pattern); my %expected = @expected.map: { %name2path{.key} => .value } subtest "testing '$pattern'" => { plan 5; my %nameds = :degree(1), :dont-catch, |%additional; my $rak := rak &needle, %nameds; isa-ok $rak, Rak; is-deeply $rak.stats, Map.new, 'did we get an empty Map for stats'; my %got = $rak.result.map: { .key => .value.List if .value.elems } is %got.elems, %expected.elems, "did we get %expected.elems() results"; is-deeply %got, %expected, 'is the search result ok'; dd %nameds unless is %nameds.elems, 0, 'did all named arguments get removed'; } } lookup "nine", :paths($dir), "nine" => (l9,) ; lookup "eight", :paths(($dir,)), "eight" => (l8,), "nine" => (l8,), ; lookup "/ zero /", :paths($dir), "zero" => (l0,), "one" => (l0,), "two" => (l0,), "three" => (l0,), "four" => (l0,), "five" => (l0,), "six" => (l0,), "seven" => (l0,), "eight" => (l0,), "nine" => (l0,), ; lookup '*.ends-with("o")', :paths($dir), :is-text, "zero" => (l0,), "one" => (l0,), "two" => (l0, l2), "three" => (l0, l2), "four" => (l0, l2), "five" => (l0, l2), "six" => (l0, l2), "seven" => (l0, l2), "eight" => (l0, l2), "nine" => (l0, l2), ; lookup '-> $_ { .ends-with("o") && .uc }', :paths($dir), "zero" => (C0,), "one" => (C0,), "two" => (C0, C2), "three" => (C0, C2), "four" => (C0, C2), "five" => (C0, C2), "six" => (C0, C2), "seven" => (C0, C2), "eight" => (C0, C2), "nine" => (C0, C2), ; lookup "/ er /", :paths(%name2path<nine>), "nine" => (l0,), ; lookup "/ zer /", :paths(%name2path<eight nine>), "eight" => (l0,), "nine" => (l0,), ; lookup "four", :paths(%name2path<nine>), :context(2), "nine" => (c2, c3, l4, c5, c6), ; lookup "/ four /", :paths(%name2path<nine>), :before-context(2), "nine" => (c2, c3, l4), ; lookup "/ fou /", :paths(%name2path<nine>), :after-context(2), "nine" => (l4, c5, c6), ; lookup "/ our /", :paths(%name2path<nine>), :paragraph-context, "nine" => (c0, c1, c2, c3, l4, c5, c6, c7, c8, c9), ; lookup '*.ends-with("nine")', :paths($dir), :passthru-context, "nine" => (c0, c1, c2, c3, c4, c5, c6, c7, c8, l9), ; lookup 'zippo', :paths($dir), :passthru-context, (), ; lookup 'zippo', :paths(%name2path<nine>), :passthru, "nine" => (c0, c1, c2, c3, c4, c5, c6, c7, c8, c9), ; lookup 'o', :paths($dir), :filesize(*>45), "nine" => (l0,l1,l2,l4), ; lookup 'ine', :paths($dir), :is-writable, :is-readable, "nine" => (l9,), ; lookup 'in', :paths($dir), :is-owned-by-user, :!is-symbolic-link, "nine" => (l9,), ; lookup 'zero', :paths($dir), :!is-text, () ; lookup 'zero', :paths($dir), :!is-owned-by-user, () ; lookup '-> $_ { $_ eq "zero" }', :paths($dir), :with-line-endings, () ; lookup 'one', :paths($dir), :is-empty, () ; lookup 'NINE', :paths($dir), :produce-many(*.IO.lines.map: *.uc), "nine" => (L9,), ; lookup '/ i /', :paths($dir), :max-matches-per-source(3), :ioify(*.IO), "five" => (l5,), "six" => (l5,l6), "seven" => (l5,l6), "eight" => (l5,l6,l8), "nine" => (l5,l6,l8), ; lookup '/ t /', :paths($dir), :max-matches-per-source(2), :context(1), "two" => (c1,l2), "three" => (c1,l2,l3), "four" => (c1,l2,l3,c4), "five" => (c1,l2,l3,c4), "six" => (c1,l2,l3,c4), "seven" => (c1,l2,l3,c4), "eight" => (c1,l2,l3,c4), "nine" => (c1,l2,l3,c4), ; lookup '*.subst("w","v",:g)', :paths($dir), :old-new, "two" => (o2,), "three" => (o2,), "four" => (o2,), "five" => (o2,), "six" => (o2,), "seven" => (o2,), "eight" => (o2,), "nine" => (o2,), ; lookup "eight", :accept(*.slurp.contains("nine")), :paths($dir), "nine" => (l8,) ; lookup "eight", :deny(*.slurp.contains("nine")), :paths($dir), "eight" => (l8,) ; my %b is BagHash; my $FIRST-matcher-fired; my $LAST-matcher-fired; my $FIRST-mapper-fired; my $LAST-mapper-fired; my int $NEXT-matcher-count; my int $NEXT-mapper-count; lookup -> $ { FIRST $FIRST-matcher-fired = True; NEXT ++$NEXT-matcher-count; LAST $LAST-matcher-fired = True; True # accept all lines }, :name<bagtest>, :paths($dir), :mapper(-> $source, @lines { FIRST $FIRST-mapper-fired = True; NEXT ++$NEXT-mapper-count; LAST $LAST-mapper-fired = True; %b.add(@lines.map(*.value)); Empty }), () ; is-deeply %b, (:10zero, :9one, :8two, :7three, :6four, :5five, :4six, :3seven, :2eight, :1nine).BagHash, 'did the mapper create the correct bag'; ok $FIRST-matcher-fired, "FIRST phaser fired in matcher"; ok $LAST-matcher-fired, "LAST phaser fired in matcher"; ok $FIRST-mapper-fired, "FIRST phaser fired in mapper"; ok $LAST-mapper-fired, "LAST phaser fired in mapper"; is $NEXT-matcher-count, 10, 'was NEXT phaser in matcher fired ok'; is $NEXT-mapper-count, 10, 'was NEXT phaser in mapper fired ok'; my $rak := rak -> $ --> True { }, :paths($dir), :unique; is-deeply $rak.result.sort, @targets.sort, 'did we get all unique strings'; sub weird($_) { if $_ eq "five" { "seven" } elsif $_ eq "seven" { Empty } else { True } } $rak := rak(&weird, :paths($dir), :stats); .Str for $rak.result; # :stats is lazy, so need to process is-deeply $rak.stats, Map.new(( :nr-changes(5), :nr-items(55), :nr-matches(52), :nr-passthrus(3), :nr-sources(10) )), "did stats work out?"; $rak := rak(&weird, :paths($dir), :stats-only); is-deeply $rak.stats, Map.new(( :nr-changes(5), :nr-items(55), :nr-matches(52), :nr-passthrus(3), :nr-sources(10) )), "did stats-only work out for stats?"; is-deeply $rak.result, Empty, "did stats-only work out for result?"; $rak := rak &defined, :paths($dir), :find, :omit-item-number, :dont-catch; ok $rak.result.head.value>>.absolute (==) %path2name.keys, 'did a :find with &defined pattern work out'; $rak := rak &defined, :paths($dir), :find, :sort-sources, :omit-item-number; is-deeply $rak.result.head.value>>.absolute, %path2name.keys.sort, 'did a :find with &defined pattern work out sorted'; $rak := rak &defined, :paths($dir), :find, :omit-item-number, :sort-sources({ $^b cmp $^a}); is-deeply $rak.result.head.value>>.absolute, %path2name.keys.sort.reverse, 'did a :find with &defined pattern work out sorted reversed'; $rak := rak *.contains("seven"), :paths($dir), :sources-only, :dont-catch; ok $rak.result>>.absolute (==) %name2path<seven eight nine>, 'did a :sources-only only produce paths'; $rak := rak *.defined, :paths($dir), :frequencies, :dont-catch; is-deeply $rak.result, (:10zero, :9one, :8two, :7three, :6four, :5five, :4six, :3seven, :2eight, :1nine), 'did frequencies produce ok'; $rak := rak &defined, :paths($dir), :shell("echo \$_ >> $append-path"), :find, :omit-item-number, :dont-catch; ok $rak.result.head.value>>.absolute (==) %path2name.keys, 'did a :shell with :find with &defined pattern work out'; ok $append.lines (==) %path2name.keys, 'did we get all paths'; $rak := rak &defined, :paths(%name2path<eight nine>), :classify(*.substr(0,1)); is-deeply Map.new($rak.result), Map.new(( :e<eight eight>, :f<four five four five>, :s<six seven six seven>, :t<two three two three>, :n(("nine",)) :o<one one>, :z<zero zero>, )), 'classify on the first letter'; $rak := rak &defined, :paths(%name2path<eight nine>), :categorize(*.substr(0,2).comb); is-deeply Map.new($rak.result), Map.new(( :e<zero seven eight zero seven eight>, :f<four five four five>, :h<three three>, :i<five six eight five six eight nine>, :n<one one nine>, :o<one four one four>, :s<six seven six seven>, :t<two three two three>, :w<two two>, :z<zero zero>, )), 'categorize on the first two letters'; # vim: expandtab shiftwidth=3
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: lib/rak.rakumod ### ---------------------------------------------------- ### -- Chunk 1 of 2 # The modules that we need here, with their full identities use Git::Files:ver<0.0.8+>:auth<zef:lizmat>; # git-files use hyperize:ver<0.0.4+>:auth<zef:lizmat>; # hyperize racify use paths:ver<10.1+>:auth<zef:lizmat> 'paths'; # paths use path-utils:ver<0.0.21+>:auth<zef:lizmat>; # path-* use Trap:ver<0.0.2+>:auth<zef:lizmat>; # Trap # code to convert a path into an object that can do .lines and .slurp my &ioify = *.IO; # The classes for matching and not-matching items (that have been added # because of some context argument having been specified). my class PairContext is Pair is export { method changed(--> False) { } method matched(--> False) { } method Str(--> Str:D) { self.key ~ ':' ~ self.value } } my class PairMatched is PairContext is export { method matched(--> True) { } } # The special case for matches that resulted in a change my class PairChanged is PairMatched is export { method changed(--> True) { } } # Message for humans on STDERR my sub warn-if-human-on-stdin(--> Nil) { note "Reading from STDIN, please enter source and ^D when done:" if $*IN.t; } # Return a Seq with ~ paths substituted for actual home directory paths my sub paths-from-file($from) { my $home := $*HOME.absolute ~ '/'; warn-if-human-on-stdin if $from eq '-'; ($from eq '-' ?? $*IN.lines !! ioify($from.subst(/^ '~' '/'? /, $home)).lines ).map: *.subst(/^ '~' '/'? /, $home) } # Return a Map with named arguments for "paths" my sub paths-arguments(%_) { my $dir := %_<dir>:delete; my $file := %_<file>:delete; my $follow-symlinks := (%_<recurse-symlinked-dir>:delete) // False; my $recurse := (%_<recurse-unmatched-dir>:delete) // False; my $readable-files := (%_<is-readable>:delete) // True; Map.new: (:$dir, :$file, :$recurse, :$follow-symlinks, :$readable-files); } # Obtain paths for given revision control system and specs my sub uvc-paths($uvc, *@specs) { $uvc<> =:= True || $uvc eq 'git' ?? git-files @specs !! die "Don't know how to select files for '$uvc'"; } my @temp-files; END .unlink for @temp-files; # Check if argument looks like a URL, and if so, fetch it my sub fetch-if-url(Str:D $target) { if $target.contains(/^ \w+ '://' /) { my $proc := run 'curl', $target, :out, :err; if $proc.out.slurp(:close) -> $contents { my $io := $*TMPDIR.add('rak-' ~ $*PID ~ '-' ~ time); $io.spurt($contents); @temp-files.push: $io; $proc.err.slurp(:close); # Hide an IO object with the URL hidden in it inside # the absolute path of the object, so that all file # attribute tests, that require a string, will just # work without blowing up because they can't coerce # an IO::Path to a native string role HideIO { has IO::Path:D $.IO is required } $io.absolute but HideIO($io but $target) } else { $proc.err.slurp(:close); Empty } } } # Convert a given seq producing paths to a seq producing files my sub paths-to-files($iterable, $degree, %_) { if %_<under-version-control>:delete -> $uvc { uvc-paths($uvc, $iterable) } else { my %paths-arguments := paths-arguments(%_); $iterable.map: { path-exists($_) ?? path-is-regular-file($_) ?? $_ !! paths($_, |%paths-arguments).Slip !! fetch-if-url($_) } } } # Adapt a sources sequence to apply any property filters specified my sub make-property-filter($seq is copy, %_) { if %_<modified>:delete -> &modified { $seq = $seq.map: -> $path { modified(path-modified($path)) ?? $path !! Empty } } if %_<created>:delete -> &created { $seq = $seq.map: -> $path { created(path-created($path)) ?? $path !! Empty } } if %_<accessed>:delete -> &accessed { $seq = $seq.map: -> $path { accessed(path-accessed($path)) ?? $path !! Empty } } if %_<meta-modified>:delete -> &meta-modified { $seq = $seq.map: -> $path { meta-modified(path-meta-modified($path)) ?? $path !! Empty } } if %_<filesize>:delete -> &filesize { $seq = $seq.map: -> $path { filesize(path-filesize($path)) ?? $path !! Empty } } if %_<is-empty>:exists { $seq = $seq.map: (%_<is-empty>:delete) ?? -> $path { path-is-empty($path) ?? $path !! Empty } !! -> $path { path-is-empty($path) ?? Empty !! $path } } if %_<mode>:delete -> &mode { $seq = $seq.map: -> $path { mode(path-mode($path)) ?? $path !! Empty } } if %_<uid>:delete -> &uid { $seq = $seq.map: -> $path { uid(path-uid($path)) ?? $path !! Empty } } if %_<gid>:delete -> &gid { $seq = $seq.map: -> $path { gid(path-gid($path)) ?? $path !! Empty } } if %_<device-number>:delete -> &device-number { $seq = $seq.map: -> $path { device-number(path-device-number($path)) ?? $path !! Empty } } if %_<inode>:delete -> &inode { $seq = $seq.map: -> $path { inode(path-inode($path)) ?? $path !! Empty } } if %_<hard-links>:delete -> &hard-links { $seq = $seq.map: -> $path { hard-links(path-hard-links($path)) ?? $path !! Empty } } if %_<blocks>:delete -> &blocks { $seq = $seq.map: -> $path { blocks(path-blocks($path)) ?? $path !! Empty } } if %_<is-owned-by-user>:exists { $seq = $seq.map: (%_<is-owned-by-user>:delete) ?? -> $path { path-is-owned-by-user($path) ?? $path !! Empty } !! -> $path { path-is-owned-by-user($path) ?? Empty !! $path } } if %_<is-owned-by-group>:exists { $seq = $seq.map: (%_<is-owned-by-group>:delete) ?? -> $path { path-is-owned-by-group($path) ?? $path !! Empty } !! -> $path { path-is-owned-by-group($path) ?? Empty !! $path } } if %_<is-writable>:exists { $seq = $seq.map: (%_<is-writable>:delete) ?? -> $path { path-is-writable($path) ?? $path !! Empty } !! -> $path { path-is-writable($path) ?? Empty !! $path } } if %_<is-executable>:exists { $seq = $seq.map: (%_<is-executable>:delete) ?? -> $path { path-is-executable($path) ?? $path !! Empty } !! -> $path { path-is-executable($path) ?? Empty !! $path } } if %_<has-setuid>:exists { $seq = $seq.map: (%_<has-setuid>:delete) ?? -> $path { path-has-setuid($path) ?? $path !! Empty } !! -> $path { path-has-setuid($path) ?? Empty !! $path } } if %_<has-setgid>:exists { $seq = $seq.map: (%_<has-setgid>:delete) ?? -> $path { path-has-setgid($path) ?? $path !! Empty } !! -> $path { path-has-setgid($path) ?? Empty !! $path } } if %_<is-sticky>:exists { $seq = $seq.map: (%_<is-sticky>:delete) ?? -> $path { path-is-sticky($path) ?? $path !! Empty } !! -> $path { path-is-sticky($path) ?? Empty !! $path } } if %_<is-owner-readable>:exists { $seq = $seq.map: (%_<is-owner-readable>:delete) ?? -> $path { path-is-owner-readable($path) ?? $path !! Empty } !! -> $path { path-is-owner-readable($path) ?? Empty !! $path } } if %_<is-owner-writable>:exists { $seq = $seq.map: (%_<is-owner-writable>:delete) ?? -> $path { path-is-owner-writable($path) ?? $path !! Empty } !! -> $path { path-is-owner-writable($path) ?? Empty !! $path } } if %_<is-owner-executable>:exists { $seq = $seq.map: (%_<is-owner-executable>:delete) ?? -> $path { path-is-owner-executable($path) ?? $path !! Empty } !! -> $path { path-is-owner-executable($path) ?? Empty !! $path } } if %_<is-group-readable>:exists { $seq = $seq.map: (%_<is-group-readable>:delete) ?? -> $path { path-is-group-readable($path) ?? $path !! Empty } !! -> $path { path-is-group-readable($path) ?? Empty !! $path } } if %_<is-group-writable>:exists { $seq = $seq.map: (%_<is-group-writable>:delete) ?? -> $path { path-is-group-writable($path) ?? $path !! Empty } !! -> $path { path-is-group-writable($path) ?? Empty !! $path } } if %_<is-group-executable>:exists { $seq = $seq.map: (%_<is-group-executable>:delete) ?? -> $path { path-is-group-executable($path) ?? $path !! Empty } !! -> $path { path-is-group-executable($path) ?? Empty !! $path } } if %_<is-symbolic-link>:exists { $seq = $seq.map: (%_<is-symbolic-link>:delete) ?? -> $path { path-is-symbolic-link($path) ?? $path !! Empty } !! -> $path { path-is-symbolic-link($path) ?? Empty !! $path } } if %_<is-world-readable>:exists { $seq = $seq.map: (%_<is-world-readable>:delete) ?? -> $path { path-is-world-readable($path) ?? $path !! Empty } !! -> $path { path-is-world-readable($path) ?? Empty !! $path } } if %_<is-world-writable>:exists { $seq = $seq.map: (%_<is-world-writable>:delete) ?? -> $path { path-is-world-writable($path) ?? $path !! Empty } !! -> $path { path-is-world-writable($path) ?? Empty !! $path } } if %_<is-world-executable>:exists { $seq = $seq.map: (%_<is-world-executable>:delete) ?? -> $path { path-is-world-executable($path) ?? $path !! Empty } !! -> $path { path-is-world-executable($path) ?? Empty !! $path } } if %_<accept>:delete -> &code { $seq = $seq.map: -> $path { code(ioify $path) ?? $path !! Empty } } if %_<deny>:delete -> &code { $seq = $seq.map: -> $path { code(ioify $path) ?? Empty !! $path } } if %_<exec>:delete -> $command { $seq = $seq.map: -> $path { run($command.subst('$_', $path, :g)) ?? $path !! Empty } } if %_<shell>:delete -> $command { $seq = $seq.map: -> $path { shell($command.subst('$_', $path, :g)) ?? $path !! Empty } } if %_<is-text>:exists { $seq = $seq.map: (%_<is-text>:delete) ?? -> $path { path-is-text($path) ?? $path !! Empty } !! -> $path { path-is-text($path) ?? Empty !! $path } } if %_<is-moarvm>:exists { $seq = $seq.map: (%_<is-moarvm>:delete) ?? -> $path { path-is-moarvm($path) ?? $path !! Empty } !! -> $path { path-is-moarvm($path) ?? Empty !! $path } } if %_<is-pdf>:exists { $seq = $seq.map: (%_<is-pdf>:delete) ?? -> $path { path-is-pdf($path) ?? $path !! Empty } !! -> $path { path-is-pdf($path) ?? Empty !! $path } } $seq.map: &ioify } # Return a matcher Callable for a given pattern. my sub make-matcher(&pattern, %_) { my &matcher := %_<invert-match>:delete ?? -> $haystack { my $result := pattern($haystack); $result =:= True ?? False !! not-acceptable($result) ?? True !! $result } !! &pattern; my $silently := (%_<silently>:delete)<>; if %_<quietly>:delete { # the existence of a CONTROL block appears to disallow use of ternaries # 2022.07 if $silently { if $silently =:= True || $silently eq 'out,err' | 'err,out' { -> $haystack { CONTROL { .resume if CX::Warn.ACCEPTS($_) } Trap(my $*OUT, my $*ERR); matcher($haystack) } } elsif $silently eq 'out' { -> $haystack { CONTROL { .resume if CX::Warn.ACCEPTS($_) } Trap(my $*OUT); matcher($haystack) } } elsif $silently eq 'err' { -> $haystack { CONTROL { .resume if CX::Warn.ACCEPTS($_) } Trap(my $*ERR); matcher($haystack) } } else { die "Unexpected value for --silently: $silently" } } else { -> $haystack { CONTROL { .resume if CX::Warn.ACCEPTS($_) } matcher($haystack) } } } elsif $silently { # and not quietly $silently =:= True || $silently eq 'out,err' | 'err,out' ?? -> $haystack { Trap(my $*OUT, my $*ERR); matcher($haystack) } !! $silently eq 'out' ?? -> $haystack { Trap(my $*OUT); matcher($haystack) } !! $silently eq 'err' ?? -> $haystack { Trap(my $*ERR); matcher($haystack) } !! die "Unexpected value for --silently: $silently" } else { &matcher } } #- runners --------------------------------------------------------------------- # Not matching my sub not-acceptable($result is copy) { $result := $result<>; $result =:= False || $result =:= Empty || $result =:= Nil } my sub acceptable($item is raw, $result is raw) { $result =:= True || $result eqv $item.value ?? PairMatched.new($item.key, $item.value) !! PairChanged.new($item.key, $result) } # Return a runner Callable for passthru my sub make-passthru-runner($source, &matcher, $item-number) { $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); not-acceptable($result) ?? $item !! acceptable($item, $result) } !! -> $item { my $result := matcher($item); $result =:= True || not-acceptable($result) ?? $item !! $result } } # Return a runner Callable for "also first" context my sub make-also-first-runner($source, &matcher, $items, $item-number) { my int $todo = $items; my @first; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match @first.push($item) if $todo && $todo--; Empty } else { # match or something else was produced from match --$todo if $todo; @first.push(acceptable $item, $result).splice.Slip } } !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match @first.push($item) if $todo && $todo--; Empty } else { # match or something else was produced from match --$todo if $todo; @first.push( $result =:= True ?? $item !! $result ).splice.Slip } } } # Return a runner Callable for "always first" context my sub make-always-first-runner($source, &matcher, $items, $item-number) { my int $todo = $items; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match ($todo && $todo--) ?? $item !! Empty } else { # match or something else was produced from match --$todo if $todo; acceptable $item, $result } } !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match ($todo && $todo--) ?? $item !! Empty } else { # match or something else was produced from match --$todo if $todo; $result =:= True ?? $item !! $result } } } # Return a runner Callable for passthru context my sub make-passthru-context-runner($source, &matcher, $item-number) { my $after; my @before; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $after { $item } else { @before.push($item); Empty } } else { # match or something else was produced from match $after = True; @before.push(acceptable $item, $result).splice.Slip } } !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $after { $item } else { @before.push($item); Empty } } else { # match or something else was produced from match $after = True; @before.push( $result =:= True ?? $item !! $result ).splice.Slip } } } # Return a runner Callable for paragraph context around items my multi sub make-paragraph-context-runner( $source, &matcher, $item-number, uint $max-matches ) { my uint $matches-seen; my $after; my @before; $item-number ?? -> $item { my $value := $item.value; if $matches-seen == $max-matches { # enough matches seen $after ?? $value ?? $item !! (last) !! (last) } else { # must still try to match my $*SOURCE := $source; my $result := matcher($value); if not-acceptable($result) { # no match if $after { if $value { $item } else { $after = False; Empty } } else { $value ?? @before.push($item) !! @before.splice; Empty } } else { # match or something else was produced from match ++$matches-seen; $after = True; @before.push(acceptable $item, $result).splice.Slip } } } # no item numbers needed !! -> $item { if $matches-seen == $max-matches { # enough matches seen $after ?? $item ?? $item !! (last) !! (last) } else { # must still try to match my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $after { if $item { $item } else { $after = False; Empty } } else { $item ?? @before.push($item) !! @before.splice; Empty } } else { # match or something else was produced from match ++$matches-seen; $after = True; @before.push( $result =:= True ?? $item !! $result ).splice.Slip } } } } my multi sub make-paragraph-context-runner($source, &matcher, $item-number) { my $after; my @before; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $after { if $value { $item } else { $after = False; Empty } } else { $value ?? @before.push($item) !! @before.splice; Empty } } else { # match or something else was produced from match $after = True; @before.push(acceptable $item, $result).splice.Slip } } # no item numbers needed !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $after { if $item { $item } else { $after = False; Empty } } else { $item ?? @before.push($item) !! @before.splice; Empty } } else { # match or something else was produced from match $after = True; @before.push( $result =:= True ?? $item !! $result ).splice.Slip } } } # Return a runner Callable for numeric context around items my multi sub make-numeric-context-runner( $source, &matcher, $item-number, $before, $after, uint $max-matches ) { my uint $matches-seen; if $before { my $todo; my @before; $item-number ?? -> $item { if $matches-seen == $max-matches { # seen enough matches if $todo { --$todo; $item } else { last } } else { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { @before.shift if @before.elems == $before; @before.push: $item; Empty } } else { # match or something was produced from match ++$matches-seen; $todo = $after; @before.push(acceptable $item, $result).splice.Slip } } } # no item numbers needed !! -> $item { if $matches-seen == $max-matches { # seen enough matches if $todo { --$todo; $item } else { last } } else { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { @before.shift if @before.elems == $before; @before.push: $item; Empty } } else { # match or something was produced from match ++$matches-seen; $todo = $after; @before.push( $result =:= True ?? $item !! $result ).splice.Slip } } } } else { my $todo; $item-number ?? -> $item { if $matches-seen == $max-matches { # seen enough matches if $todo { --$todo; $item } else { last } } else { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { Empty } } else { # match or something was produced from match ++$matches-seen; $todo = $after; acceptable($item, $result) } } } # no item numbers needed !! -> $item { if $matches-seen == $max-matches { # seen enough matches if $todo { --$todo; $item } else { last } } else { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { Empty } } else { # match or something was produced from match ++$matches-seen; $todo = $after; $result =:= True ?? $item !! $result } } } } } my multi sub make-numeric-context-runner( $source, &matcher, $item-number, $before, $after ) { if $before { my $todo; my @before; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { @before.shift if @before.elems == $before; @before.push: $item; Empty } } else { # match or something was produced from match $todo = $after; @before.push(acceptable $item, $result).splice.Slip } } # no item numbers needed !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { @before.shift if @before.elems == $before; @before.push: $item; Empty } } else { # match or something was produced from match $todo = $after; @before.push( $result =:= True ?? $item !! $result ).splice.Slip } } } else { my $todo; $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { Empty } } else { # match or something was produced from match $todo = $after; acceptable($item, $result) } } # no item numbers needed !! -> $item { my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { # no match if $todo { --$todo; $item } else { Empty } } else { # match or something was produced from match $todo = $after; $result =:= True ?? $item !! $result } } } } # Base case of a runner from a matcher without any context my multi sub make-runner($source, &matcher, $item-number, uint $max-matches) { my uint $matches-seen; $item-number ?? -> $item { last if $matches-seen == $max-matches; my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); if not-acceptable($result) { Empty } else { ++$matches-seen; acceptable($item, $result) } } # no item numbers needed !! -> $item { last if $matches-seen == $max-matches; my $*SOURCE := $source; my $result := matcher($item); if not-acceptable($result) { Empty } else { ++$matches-seen; $result =:= True ?? $item !! $result } } } my multi sub make-runner($source, &matcher, $item-number) { $item-number ?? -> $item { my $*SOURCE := $source; my $value := $item.value; my $result := matcher($value); not-acceptable($result) ?? Empty !! acceptable($item, $result) } # no item numbers needed !! -> $item { my $*SOURCE := $source; my $result := matcher($item); not-acceptable($result) ?? Empty !! $result =:= True ?? $item !! $result } } #- rak ------------------------------------------------------------------------- # Stub the Rak class here our class Rak { ... } proto sub rak(|) is export {*} multi sub rak(&pattern, *%n) { rak &pattern, %n } multi sub rak(&pattern, %n) { # any execution error will be caught and become a return state my $CATCH := !(%n<dont-catch>:delete); CATCH { $CATCH ?? (return Rak.new: exception => $_) !! .rethrow; } # Determine how we make IO::Path-like objects &ioify = $_ with %n<ioify>:delete; # Some settings we always need my $batch := %n<batch>:delete; my $degree := %n<degree>:delete; my $enc := %n<encoding>:delete // 'utf8-c8'; # Get any of the context flags, and a flag to rule them all my $any-context := (my $passthru := %n<passthru>:delete) || (my $also-first-context := %n<also-first>:delete) || (my $always-first-context := %n<always-first>:delete) || (my $passthru-context := %n<passthru-context>:delete) || (my $context := %n<context>:delete) || (my $before-context := %n<before-context>:delete) || (my $after-context := %n<after-context>:delete) || (my $paragraph-context := %n<paragraph-context>:delete); my sub get-sources-seq() { my $seq := do if %n<files-from>:delete -> $files-from { paths-from-file($files-from).map: { path-exists($_) ?? $_ !! fetch-if-url($_) } } elsif %n<paths-from>:delete -> $paths-from { paths-to-files(paths-from-file($paths-from), $degree, %n) } elsif %n<paths>:delete -> $paths { my $home := $*HOME.absolute ~ '/'; paths-to-files( $paths.map(*.subst(/^ '~' '/'? /, $home)), $degree, %n ).&hyperize($batch, $degree) } elsif %n<under-version-control>:delete -> $uvc { uvc-paths($uvc) } elsif !($*IN.t) { return $*IN } else { paths(".", |paths-arguments(%n)).&hyperize($batch, $degree) } # Step 2. filtering on properties make-property-filter($seq, %n); } # Step 1: sources sequence my $sources-seq = %n<sources>:delete // get-sources-seq; # sort sources if we want them sorted if %n<sort-sources>:delete -> $sort { $sources-seq = Bool.ACCEPTS($sort) ?? $sources-seq.sort(*.fc) !! $sources-seq.sort($sort) } # Some flags that we need my $eager := %n<eager>:delete; my $sources-only; my $sources-without-only; my $unique; my $sort; my $frequencies; my $classify; my $categorize; my $item-number; my $max-matches-per-source; if %n<sources-only>:delete { $sources-only := True; $item-number := False; $max-matches-per-source := 1; } elsif %n<sources-without-only>:delete { $sources-without-only := $sources-only := True; $item-number := False; $max-matches-per-source := 1; } else { $max-matches-per-source := %n<max-matches-per-source>:delete; if %n<unique>:delete { $unique := $eager := True; $item-number := $max-matches-per-source := False; $sort := %n<sort>:delete;
### ---------------------------------------------------- ### -- rak ### -- Licenses: Artistic-2.0 ### -- Authors: Elizabeth Mattijsen ### -- File: lib/rak.rakumod ### ---------------------------------------------------- ### -- Chunk 2 of 2 } elsif %n<frequencies>:delete { $frequencies := $eager := True; $item-number := $max-matches-per-source := False; } elsif %n<classify>:delete -> &classifier { $classify := &classifier; $eager := True; $item-number := $max-matches-per-source := False; } elsif %n<categorize>:delete -> &categorizer { $categorize := &categorizer; $eager := True; $item-number := $max-matches-per-source := False; } elsif %n<produce-one>:exists { $item-number := False; } else { $item-number := !(%n<omit-item-number>:delete); } } # Step 3: producer Callable my &producer := do if (%n<produce-one>:delete) -> $produce-one { # no item numbers produced ever -> $source { (my $producer := $produce-one($source)) =:= Nil ?? () !! ($producer,) } } elsif (%n<produce-many-pairs>:delete)<> -> $produce-many-pairs { $item-number := True; $produce-many-pairs } elsif (%n<produce-many>:delete)<> -> $produce-many { $item-number ?? -> $source { my uint $line-number; $produce-many($source).map: { PairContext.new: ++$line-number, $_ } } # no item numbers produced !! $produce-many } elsif %n<find>:delete { my $seq := $sources-seq<>; $sources-seq = ("<find>",); my uint $line-number; $item-number ?? -> $ { $seq.map: { PairContext.new: ++$line-number, $_ } } !! -> $ { $seq } } else { my $chomp := !(%n<with-line-endings>:delete); my uint $ok-to-hyper = !$any-context; -> $source { my $is-IO := IO::Path.ACCEPTS($source); # It's a Path and it exists and is readable, or not a path if ($is-IO && $source.r) || !$is-IO { my $seq := $source.lines(:$chomp, :$enc); # Make sure we have item numbering if so requested my uint $line-number; $seq := $seq.map({ PairContext.new: ++$line-number, $_ }) if $item-number; $seq # Hyperize if it is a path # $is-IO && $ok-to-hyper # ?? $seq.&hyperize(2048, $degree) # !! $seq.Seq # XXX why??? } } } # Step 4: matching logic # The matcher Callable should take a haystack as the argument, and # call the pattern with that. And optionally do some massaging to make # sure we get the right thing. But in all other aspects, the matcher # has the same API as the pattern. my &matcher = &pattern =:= &defined ?? &defined !! make-matcher( Regex.ACCEPTS(&pattern) ?? *.contains(&pattern) !! &pattern, %n ); # Want to have pair of old/new if %n<old-new>:delete { my &old-matcher = &matcher; &matcher = -> $old { my $new := old-matcher($old); unless Bool.ACCEPTS($new) || $new =:= Empty || $new =:= Nil { Pair.new($old, $new) unless $new eqv $old; } } } # Stats keeping stuff: these lexical variables will be directly accessible # through the Rak object that is returned. This is ok to do, since each # call to the "rak" subroutine will result in a unique Rak object, so # there's no danger of these lexicals seeping into the wrong Rak object my $stats; my $stats-only; my atomicint $nr-sources; my atomicint $nr-items; my atomicint $nr-matches; my atomicint $nr-passthrus; my atomicint $nr-changes; # Progress monitoring class, to be passed on when :progress is specified my $progress := %n<progress>:delete; my $cancellation; class Progress { method nr-sources() { ⚛$nr-sources } method nr-items() { ⚛$nr-items } method nr-matches() { ⚛$nr-matches } method nr-passthrus() { ⚛$nr-passthrus } method nr-changes() { ⚛$nr-changes } } # The result class returned by the rak call class Rak { has $.result is built(:bind) = Empty; # search result has $.completed is built(:bind) = False; # True if done already has $.exception is built(:bind) = Nil; # What was thrown # Final stats access method stats() { $stats || $stats-only ?? Map.new(( :$nr-changes, :$nr-items, :$nr-matches, :$nr-passthrus, :$nr-sources )) !! BEGIN Map.new } # Final progress access method nr-sources() { ⚛$nr-sources } method nr-items() { ⚛$nr-items } method nr-matches() { ⚛$nr-matches } method nr-passthrus() { ⚛$nr-passthrus } method nr-changes() { ⚛$nr-changes } method stop-progress() { if $cancellation { $cancellation.cancel; $progress(); # indicate we're done to the progress logic } } } # Only interested in counts, so update counters and remove result if $stats-only := %n<stats-only>:delete { my &old-matcher = &matcher; &matcher = -> $_ { ++⚛$nr-items; my $result := old-matcher($_); if $result =:= Empty || $result eqv $_ { ++$nr-passthrus; } elsif Bool.ACCEPTS($result) { ++⚛$nr-matches if $result; } else { ++⚛$nr-matches; ++⚛$nr-changes; } Empty } } # Add any stats keeping if necessary elsif ($stats := %n<stats>:delete) || $progress { my &old-matcher = &matcher; &matcher = -> $_ { ++⚛$nr-items; my $result := old-matcher($_); if $result =:= Empty || $result eqv $_ { ++$nr-passthrus; } elsif Bool.ACCEPTS($result) { ++⚛$nr-matches if $result; } else { ++⚛$nr-matches; ++⚛$nr-changes; } $result } } # Step 5: contextualizing logic # The runner Callable should take a PairContext object as the argument, # and call the matcher with that. If the result is True, then it should # produce that line as a PairMatched object with the original value, and # any other items as as PairContext objects. If the result is False, it # should produce Empty. In any other case, it should produce a # PairMatched object with the original key, and the value returned by # the matcher as its value. To make sure each source gets its own # closure clone, the runner is actually a Callable returning the actual # runner code Callable. my &runner := do if $stats-only { $eager := True; # simplest runner for just counting -> $source { make-runner $source, &matcher, $item-number } } # We have some context specification elsif $any-context { # Special passthru contexts if $passthru { -> $source { make-passthru-runner $source, &matcher, $item-number } } elsif $also-first-context -> $items { -> $source { make-also-first-runner $source, &matcher, $items, $item-number } } elsif $always-first-context -> $items { -> $source { make-always-first-runner $source, &matcher, $items, $item-number } } elsif $passthru-context { -> $source { make-passthru-context-runner $source, &matcher, $item-number } } # Limit on number of matches elsif $max-matches-per-source -> uint $max { if $context { -> $source { make-numeric-context-runner $source, &matcher, $item-number, $context, $context, $max } } elsif $before-context { $after-context := %n<after-context>:delete; -> $source { make-numeric-context-runner $source, &matcher, $item-number, $before-context, $after-context, $max } } elsif $after-context { -> $source { make-numeric-context-runner $source, &matcher, $item-number, Any, $after-context, $max } } elsif $paragraph-context { -> $source { make-paragraph-context-runner $source, &matcher, $item-number, $max } } else { -> $source { make-runner $source, &matcher, $item-number, $max } } } # No limit on number of matches elsif $context { -> $source { make-numeric-context-runner $source, &matcher, $item-number, $context, $context } } elsif $before-context { $after-context := %n<after-context>:delete; -> $source { make-numeric-context-runner $source, &matcher, $item-number, $before-context, $after-context } } elsif $after-context { -> $source { make-numeric-context-runner $source, &matcher, $item-number, Any, $after-context } } elsif $paragraph-context { -> $source { make-paragraph-context-runner $source, &matcher, $item-number } } } else { -> $source { make-runner $source, &matcher, $item-number } } # Step 6: run the sequences my &first-phaser; my &next-phaser; my &last-phaser; if &pattern.has-loop-phasers { &first-phaser = &pattern.callable_for_phaser('FIRST'); &next-phaser = &pattern.callable_for_phaser('NEXT'); &last-phaser = &pattern.callable_for_phaser('LAST'); } # Set up any mapper if not just counting my &mapper; my $map-all; my &next-mapper-phaser; my &last-mapper-phaser; if !$stats-only && (%n<mapper>:exists) { $map-all := %n<map-all>:delete; &mapper = %n<mapper>:delete; if &mapper.has-loop-phasers { $_() with &mapper.callable_for_phaser('FIRST'); &next-mapper-phaser = $_ with &mapper.callable_for_phaser('NEXT'); &last-mapper-phaser = $_ with &mapper.callable_for_phaser('LAST'); } } # Set up result sequence first-phaser() if &first-phaser; # A mapper was specified my $result-seq := do if &mapper { my $lock := Lock.new; $sources-seq.map: $sources-without-only ?? -> $source { ++⚛$nr-sources; if producer($source) .map(runner($source)).iterator.pull-one =:= IterationEnd { # thread-safely run mapper and associated phasers $lock.protect: { my \result := mapper($source); next-phaser() if &next-phaser; next-mapper-phaser() if &next-mapper-phaser; result } } } !! $sources-only ?? -> $source { ++⚛$nr-sources; unless producer($source) .map(runner($source)).iterator.pull-one =:= IterationEnd { # thread-safely run mapper and associated phasers $lock.protect: { my \result := mapper($source); next-phaser() if &next-phaser; next-mapper-phaser() if &next-mapper-phaser; result } } } !! -> $source { ++⚛$nr-sources; producer($source).map(runner($source)).iterator.push-all( my $buffer := IterationBuffer.new ); if $map-all || $buffer.elems { # thread-safely run mapper and associated phasers $lock.protect: { my \result := mapper($source, $buffer.List); next-phaser() if &next-phaser; next-mapper-phaser() if &next-mapper-phaser; result } } } } # Only want sources elsif $sources-only { my $lock := Lock.new if &next-phaser; $sources-seq.map: -> $source { ++⚛$nr-sources; my \result := producer($source).map(runner($source)).iterator.pull-one; $lock.protect(&next-phaser) if $lock; if $sources-without-only { $source if result =:= IterationEnd } else { $source unless result =:= IterationEnd } } } # Want results else { my Lock $lock := Lock.new if &next-phaser; my uint $head = (!$any-context && $max-matches-per-source) // 0; $sources-seq.map: -> $source { ++⚛$nr-sources; my $seq := producer($source).List.map: runner($source); $seq := $seq.head($head) if $head; my $result := Pair.new: $source, $seq; $lock.protect(&next-phaser) if $lock; $result } } # Set up any progress reporting and associated cancellation $cancellation := $*SCHEDULER.cue(-> { $progress(Progress) }, :every(.2)) if $progress; # Just counting, make sure all results are produced/discarded if $stats-only { for $result-seq { my $*SOURCE := $_; (Pair.ACCEPTS($_) ?? .value !! $_).iterator.sink-all; } $result-seq := (); } # Not just counting else { my $lock := Lock.new; # all of these need race protection # Only want unique matches if $unique { my %seen; $result-seq := $result-seq.map: { my $outer := Pair.ACCEPTS($_) ?? .value !! $_; if Iterable.ACCEPTS($outer) { $outer.map({ my $inner := Pair.ACCEPTS($_) ?? .value !! $_; $inner unless $lock.protect: -> { %seen{$inner.WHICH}++ } }).Slip } else { $outer unless $lock.protect: -> { %seen{$outer.WHICH}++ } } } if $sort { $result-seq := Bool.ACCEPTS($sort) ?? $result-seq.sort(*.fc) !! $result-seq.sort($sort) } } # Want classification elsif $classify -> &classifier { my %classified{Any}; my sub store(\key, $value) { $lock.protect: { (%classified{key} // (%classified{key} := IterationBuffer.new) ).push: $value; } } for $result-seq { my $outer := Pair.ACCEPTS($_) ?? .value !! $_; if Iterable.ACCEPTS($outer) { for $outer { my $value := Pair.ACCEPTS($_) ?? .value !! $_; store classifier($value), $value; } } else { store classifier($outer), $outer; my $key := classifier($outer); $lock.protect: { (%classified{$key} // (%classified{$key} := [])) .push: $outer; } } } $result-seq := %classified.sort(-*.value.elems).map: { Pair.new: .key, .value.List } } # Want categorization elsif $categorize -> &categorizer { my %categorized{Any}; my sub store(\keys, $value) { $lock.protect: { for keys -> $key { (%categorized{$key} // (%categorized{$key} := IterationBuffer.new) ).push: $value; } } } for $result-seq { my $outer := Pair.ACCEPTS($_) ?? .value !! $_; if Iterable.ACCEPTS($outer) { for $outer { my $value := Pair.ACCEPTS($_) ?? .value !! $_; store categorizer($value), $value; } } else { store categorizer($outer), $outer; } } $result-seq := %categorized.sort(-*.value.elems).map: { Pair.new: .key, .value.List } } } # Need to run all searches before returning my %args; if $eager || $stats # XXX this should really be lazy || &last-mapper-phaser || &last-phaser { my $buffer := IterationBuffer.new; # Convert to frequency map if so requested if $frequencies { my %bh is Bag = $result-seq.map: *.value.Slip; %bh.sort({ $^b.value cmp $^a.value || $^a.key cmp $^b.key }).iterator.push-all: $buffer; } # Normal collection else { $result-seq.iterator.push-all: $buffer; } # Run the phasers if any last-phaser() if &last-phaser; last-mapper-phaser() if &last-mapper-phaser; $stats-only ?? Rak.new(:completed) !! Rak.new(:completed, :result($buffer.List)) } # We can be lazy else { Rak.new: result => $result-seq<> } } # vim: expandtab shiftwidth=4
### ---------------------------------------------------- ### -- raku-RandomColor ### -- Licenses: ### -- Authors: [email protected] ### -- File: META6.json ### ---------------------------------------------------- { "depends": [], "description": "A port of the randomColor Javascript library for generating attractive random colors", "version": "v0.11", "meta-version": "0", "license": "", "source-url": "https://github.com/Xliff/raku-RandomColor.git", "provides": { "RandomColor": "lib/RandomColor.pm6" }, "name": "raku-RandomColor", "perl": "6.c", "test-depends": ["Test::META"], "build-depends": [], "support": {"source": null}, "authors": ["[email protected]"], "tags": [ "color" ] }
### ---------------------------------------------------- ### -- raku-RandomColor ### -- Licenses: ### -- Authors: [email protected] ### -- File: README.md ### ---------------------------------------------------- # raku-RandomColor A port of the RandomColor JavaScript library for Raku. # [Random Color](https://randomcolor.lllllllllllllllll.com) A tiny script for generating attractive random colors. ## Options You can pass an options object to influence the type of color it produces. The options object accepts the following properties: `hue` – Controls the hue of the generated color. You can pass a string representing a color name: `red`, `orange`, `yellow`, `green`, `blue`, `purple`, `pink` and `monochrome` are currently supported. If you pass a hexidecimal color string such as `#00FFFF`, randomColor will extract its hue value and use that to generate colors. `luminosity` – Controls the luminosity of the generated color. You can specify a string containing `bright`, `light` or `dark`. `count` – An integer which specifies the number of colors to generate. `seed` - An integer or string which when passed will cause randomColor to return the same color each time. `format` – A string which specifies the format of the generated color. Possible values are `rgb`, `rgba`, `rgbArray`, `hsl`, `hsla`, `hslArray` and `hex` (default). `alpha` – A decimal between 0 and 1. Only relevant when using a format with an alpha channel (`rgba` and `hsla`). Defaults to a random value. ## Examples ```raku # Returns a hex code for an attractive color RandomColor.new.list; # Returns an array of ten green colors RandomColor.new( count => 10, hue => 'green' }).list; # Returns a hex code for a light blue RandomColor.new( luminosity => 'light', hue => 'blue' ).list; # Returns a hex code for a 'truly random' color RandomColor( luminosity => 'random', hue => 'random' ).list; # Returns a bright color in RGB RandomColor.new( luminosity => 'bright', format => 'rgb' # e.g. 'rgb(225,200,20)' ).list; # Returns a dark RGB color with random alpha RandomColor.new( luminosity => 'dark', format => 'rgba' # e.g. 'rgba(9, 1, 107, 0.6482447960879654)' }); # Returns a dark RGB color with specified alpha RandomColor.new( luminosity => 'dark', format => 'rgba', alpha => 0.5 # e.g. 'rgba(9, 1, 107, 0.5)', ); # Returns a light HSL color with random alpha RandomColor.new( luminosity => 'light', format => 'hsla' # e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' ); ``` For more information, see the [homepage](https://randomcolor.lllllllllllllllll.com/)
### ---------------------------------------------------- ### -- raku-RandomColor ### -- Licenses: ### -- Authors: [email protected] ### -- File: .travis.yml ### ---------------------------------------------------- language: perl6 perl6: - latest - 2018.11 install: - rakudobrew build-zef - zef --deps-only install . branches: only: - master
### ---------------------------------------------------- ### -- raku-RandomColor ### -- Licenses: ### -- Authors: [email protected] ### -- File: t/01-basic.t ### ---------------------------------------------------- use v6.c; use Test; plan 46; my token fp { (\d+) [ '.' (\d+) ]? } # Can use RandomColor use-ok 'RandomColor', 'Can use the RandomColor module'; # Can get a random color use RandomColor; ok RandomColor.new, 'Can get a random color'; # Test all formatting options my $rc; for <hslarray hsvarray> { $rc = RandomColor.new( format => $_ ).list[0]; ok $rc.elems == 3, "'$_' format output produces a list with 3 elements"; ok 0 <= $rc[0] <= 360, 'Hue value is within range'; my @sv-or-sl = $_ eq 'hslarray' ?? <Saturation Light> !! <Saturation Value>; for @sv-or-sl.kv -> $k, $v { ok 0 <= $rc[$k + 1] <= 100, "{ $v } is within range"; } } $rc = RandomColor.new( format => 'rgbarray' ).list[0]; ok $rc.elems == 3, "'rgbarray' format value produces a list with 3 elements"; for <Red Green Blue>.kv -> $k, $v { ok 0 <= $rc[$k] <= 255, "'{$v} value is within range"; } for <hsv hsl> { $rc = RandomColor.new( format => 'hsl' ).list[0]; ok $rc ~~ /'hsl(' (\d+) ',' \s* <fp> ** 2 %% [',' \s*] ')'/, "'hsl' format pases parse test"; ok 0 <= $/[0] <= 360, 'Hue value is within range'; my @sv-or-sl = $_ eq 'hsl' ?? <Saturation Light> !! <Saturation Value>; for @sv-or-sl.kv -> $k, $v { ok 0 <= $/<fp>[$k] <= 100, "{$v} value is within range"; } } $rc = RandomColor.new( format => 'hsla' ).list[0]; ok $rc ~~ /'hsla(' (\d+) ',' \s* <fp> ** 3 %% [',' \s*] ')'/, "'hsla' format passes parse test"; ok 0 <= $/[0] <= 360, 'Hue value is within range'; ok 0 <= $/<fp>[0] <= 100, 'Saturation value is within range'; ok 0 <= $/<fp>[1] <= 100, 'Light value is within range'; ok 0 <= $/<fp>[2] <= 1, 'Alpha value is within range'; $rc = RandomColor.new( format => 'rgb' ).list[0]; ok $rc ~~ /'rgb(' (\d+) ** 3 %% [',' \s*] ')'/, "'rgb' format passes parse test"; for <Red Green Blue>.kv -> $k, $v { ok 0 <= $/[0][$k] <= 255, "{$v} value is within range"; } $rc = RandomColor.new( format => 'rgba' ).list[0]; ok $rc ~~ /'rgba(' (\d+) ** 3 %% [',' \s*] <fp> \s* ')'/, "'rgba' format passes parse test"; for <Red Green Blue>.kv -> $k, $v { ok 0 <= $/[0][$k] <= 255, "{$v} value is within range"; } ok 0 <= $/<fp> <= 1, 'Alpha value is within range'; $rc = RandomColor.new.list[0]; ok $rc ~~ / '#' <xdigit> ** 6 /, 'Default format passes parse test'; # Test if color output using same seed produces same output $rc = RandomColor.new( seed => 1 ).list[0]; ok $rc eq '#7ed65e', 'Random color(hex) with seeded value gives expected result.'; $rc = RandomColor.new( seed => 1, format => 'rgb' ).list[0]; ok $rc eq 'rgb(126, 214, 94)', 'Random color(rgb) with seeded value gives expected result.'; $rc = RandomColor.new( seed => 1, format => 'hsl').list[0]; ok $rc eq 'hsl(104, 59.51, 60.48)', 'Random color(hsl) with seeded value gives expected result.'; # Test for hue predominately among R, G, B for ( ['red', 0], ['green', 1], ['blue', 2] ) -> $ct { $rc = RandomColor.new( hue => $ct[0], count => 5, format => 'rgbarray' ); skip 'Will not test color predominance due to bug in upstream code', 1; # ok # $rc.map( *[ $ct[1] ] ).sum == $rc.map( *.max ).sum, # "Using hue of '{ $ct[0] }', color list is predominately { $ct[0] }"; } # Test bright skip 'Will not test brightness due to bug in upstream code.', 1; # $rc = RandomColor.new( # luminosity => 'bright', count => 5, format => 'hslarray' # ).list; # ok # $rc.map( *[1] ).grep( * < 55 ).elems == 0, # 'Setting luminosity to bright results in bright colors'; # Test dark $rc = RandomColor.new( luminosity => 'dark', count => 5, format => 'hsvarray' ).list; ok $rc.map( *[1] ).grep( * != 10 ).elems == 0, 'Setting luminosity to dark results in dark colors'; # Optional test for color support try require ::('Color'); if ::('Color') !~~ Failure { $rc = RandomColor.new( format => 'color', count => 5 ).list; ok $rc.all ~~ ::('Color'), 'Color object support is functioning properly'; } else { pass 'Color object tests skipped!' }
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: META6.json ### ---------------------------------------------------- { "name": "raku-pod-extraction", "description": "GUI to generate md and html from POD6 in a pm6 file", "version": "0.3.0", "perl": "6.d", "authors": [ "Richard Hainsworth, aka finanalyst" ], "auth": "zef:finanalyst", "depends": [ "GTK::Simple", "Raku::Pod::Render:ver<4.0.0+>", "Pod::Load" ], "build-depends": [], "test-depends": [ "Test" ], "provides": { "PodExtraction": "lib/PodExtraction.rakumod", "RakuDocRender": "lib/RakuDocRender.rakumod" }, "resources": [], "license": "Artistic-2.0", "source-url": "git://github.com/finanalyst/raku-pod-extraction.git", "bin": [ "bin/Extractor", "bin/RakuRender" ], "source-type": "git" }
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: CHANGELOG.md ### ---------------------------------------------------- # Raku Pod Extraction >Change log ## Table of Contents [2021-01-18 Transfer from Raku::Pod::Render](#2021-01-18-transfer-from-rakupodrender) [2021-02-03](#2021-02-03) [2022-01-01](#2022-01-01) [2022-02-18 v0.2.0](#2022-02-18-v020) [2022-02-20 v0.2.1](#2022-02-20-v021) [2022-10-30 v0.3.0](#2022-10-30-v030) ---- # 2021-01-18 Transfer from Raku::Pod::Render * create module, rewrite Extractor.raku utility into module and Entrypoint * no other changes # 2021-02-03 * fixup for change in Raku::Pod::Render # 2022-01-01 * remove no precompilation # 2022-02-18 v0.2.0 * add github badge functionality * do not call HTML or MD methods on empty arrays # 2022-02-20 v0.2.1 * change CI setup to minimise actions * add placeholder to GTK # 2022-10-30 v0.3.0 * make consistent with new Render::Pod ---- Rendered from CHANGELOG at 2022-10-30T09:37:26Z
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: README.md ### ---------------------------------------------------- ![github-tests-passing-badge](https://github.com/finanalyst/raku-pod-extraction/actions/workflows/test.yaml/badge.svg) # Extractor GUI >Mainly used to generate a README.md from <Modulename>.pm6, which contain POD6 ## Table of Contents [Dependencies](#dependencies) ---- Run `Extractor` in the directory where the transformed files are needed. Select POD6 files (`.pod6`, `.pm6`, `.rakudoc`) by clicking on the FileChooser button at the top of the panel. The Output file name by default is the same as the basename of the input file, but can be changed. Select the output formats. Select `add github badge` to add a github badge at the beginning of the md file (typically README.md). The name of the module and the source url is taken from the META6.json file. An exception is generated if there is no META6.json file. Will also generate HTML files from POD6 using HTML2 (see ProcessPod documentation for information). HTML2 leaves css and favicon files in the directory with the html file. If a file was selected by mistake, uncheck the 'convert' box on the far left and it will not be processed. When the list is complete, click on **Convert**. The converted files will be shown, or the failure message. This tool is fairly primitive and it may not handle all error conditions. The tool is intended for generating md and html files in an adhoc manner. # Dependencies `Extractor` requires GTK::Simple. It is known that this is difficult to install on Windows. However, if the GTK library has already been installed on Windows, then GTK::Simple will load with no problem. Look at the GTK website for information about Windows installations of GTK. ---- Rendered from README at 2022-10-30T09:24:27Z
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: t/00-sanity.rakutest ### ---------------------------------------------------- use PodExtraction; use Test; require Test::META <&meta-ok>; meta-ok(:relaxed-name); use-ok 'PodExtraction'; use-ok 'RakuDocRender'; done-testing;
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: lib/PodExtraction.rakumod ### ---------------------------------------------------- use v6.*; use Pod::Load; use Pod::To::HTML2:auth<zef:finanalyst>; use Pod::To::MarkDown2:auth<zef:finanalyst>; use GTK::Simple::App; use GTK::Simple::FileChooserButton; use GTK::Simple::MarkUpLabel; use GTK::Simple::VBox; use GTK::Simple::HBox; use GTK::Simple::CheckButton; use GTK::Simple::Entry; use GTK::Simple::Button; use GTK::Simple::TextView; use GTK::Simple::Grid; unit module PodExtraction; sub Extractor is export { my @files; my $cancel; my $action; my Str $badge-path; my $app = GTK::Simple::App.new(:title("Pod Extractor Utility")); $app.border-width = 5; my $file-chooser-button = GTK::Simple::FileChooserButton.new; # =HTML Processing ================================================== my $html-options = GTK::Simple::Grid.new( [0, 0, 1, 1] => GTK::Simple::MarkUpLabel.new( text => '<span foreground="green">HTML options</span>' ), [0, 1, 1, 1] => my $hilite = GTK::Simple::CheckButton.new(:label('')), [1, 1, 1, 1] => GTK::Simple::MarkUpLabel.new(text => 'highlight'), [0, 2, 1, 1] => my $no-css = GTK::Simple::CheckButton.new(:label('')), [1, 2, 1, 1] => GTK::Simple::MarkUpLabel.new(text => 'minimise css, camelia image, and favicon'), [0, 3, 1, 1] => GTK::Simple::MarkUpLabel.new( text => '<span foreground="green">Markdown options</span>' ), [0, 4 , 1, 1] => my $badge = GTK::Simple::CheckButton.new(:label('')), [1, 4, 1, 1] => GTK::Simple::MarkUpLabel.new(text => 'Add github badge'), [0, 5, 1, 1] => GTK::Simple::MarkUpLabel.new( text => 'Github badge path <span foreground="blue">[module name]</span>'), [1, 6, 1, 1] => my $b-path-entry = GTK::Simple::Entry.new( placeholder-text => 'Using default calculated path' ), ); my Bool $highlight-code = $hilite.status = False; my Bool $min-top = $no-css.status = False; my Bool $md-badge = $badge.status = False; $hilite.toggled.tap: -> $b { $highlight-code = !$highlight-code } $no-css.toggled.tap: -> $b { $min-top = !$min-top } $badge.toggled.tap: -> $b { $md-badge = !$md-badge } $b-path-entry.changed.tap: -> $b { $badge-path = $b-path-entry.text } $html-options.column-spacing = 10; # ==================================================================== # =FILE BOX ========================================================== my $files-box = GTK::Simple::Grid.new( [0, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(text => 'convert'), [1, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(text => '<span foreground="blue">path</span>/<span foreground="green" >input filename</span>'), [2, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(text => 'output filename'), [3, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(text => '.md'), [4, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(text => '.html'), ); $files-box.column-spacing = 10; # =========================================================== # =Bottom buttons ============================================ my $buttons = GTK::Simple::HBox.new([ $cancel = GTK::Simple::Button.new(:label<Cancel>), $action = GTK::Simple::Button.new(:label<Convert>) ]); # =============================================================== my $report = GTK::Simple::MarkUpLabel.new; # == Main Contain =============================================== my $convert = GTK::Simple::VBox.new([ { :widget(GTK::Simple::HBox.new([ { :widget(GTK::Simple::MarkUpLabel.new(text => "Select files with POD6 by clicking on the button")) , :padding(15)}, $file-chooser-button])), :!expand }, $html-options, $files-box, { :widget($report), :!expand }, { :widget($buttons), :!expand } ]); # =============================================================== # ==Action when a file is added ================================= # defined here so its in lexical scope and no need to pass lots of params. sub add-to-files($fn, $highlight-code) { state $grid-line = 0; my $io = $fn.IO; my $oname = $io.basename.substr(0,*-(+$io.extension.chars+1)); my %record = convert => True, path => $io.dirname, name => $io.basename, md => ! $highlight-code, html => $highlight-code, :$oname; $files-box.attach( [0, ++ $grid-line , 1, 1] => my $cnv = GTK::Simple::CheckButton.new(:label('')), [1, $grid-line , 1, 1] => GTK::Simple::MarkUpLabel.new( text => '<span foreground="blue" >' ~ %record<path> ~ '</span>/' ~ '<span foreground="green">' ~ %record<name> ~ '</span>' ), [2, $grid-line , 1, 1] => my $txt = GTK::Simple::Entry.new(text => %record<oname>), [3, $grid-line , 1, 1] => my $md = GTK::Simple::CheckButton.new(:label('')), [4, $grid-line , 1, 1] => my $html = GTK::Simple::CheckButton.new(:label('')), ); # ======= defaults that are on, undefined is off =========================== $md.status = 1; $cnv.status = 1; # ========================================================================== # == Defined click actions for each file =================================== $md.toggled.tap: -> $b { %record<md> = !%record<md> } $html.toggled.tap: -> $b { %record<html> = !%record<html> } $cnv.toggled.tap: -> $b { %record<convert> = !%record<convert> } $txt.changed.tap: -> $b { %record<oname> = $txt.text } # ========================================================================== @files.push: %record; } $file-chooser-button.file-set.tap: { $action.sensitive = True; add-to-files($file-chooser-button.file-name, $highlight-code); } $cancel.clicked.tap: -> $b { $app.exit }; $action.sensitive = False; $action.clicked.tap: -> $b { $cancel.label = 'Finish'; my @md = @files.grep({ .<md> and .<convert> }); my @html = @files.grep({ .<html> and .<convert> }); HTML(@html, $report, $highlight-code, $min-top) if ?@html; MarkDown(@md, $report, $md-badge, $badge-path) if ?@md; }; $app.set-content($convert); $app.show; $app.run; } sub HTML(@fn, $report, $highlight-code, $min-top) { # when there is no highlighting, the code needs escaping my Pod::To::HTML2 $pr .= new(:$min-top,:$highlight-code); process(@fn, $report, $pr, 'html') } sub MarkDown(@fn, $report, $github-badge, $badge-path) { my Pod::To::MarkDown2 $pr .= new(:$github-badge,:$badge-path); process(@fn, $report, $pr, 'md') } sub process(@fn, $report, $pr, $ext) { for @fn -> $fn { $pr.pod-file.path = $pr.pod-file.name = $pr.pod-file.title = $fn<oname>; my $pod = load($fn<path> ~ '/' ~ $fn<name>); $pr.render-tree($pod); $pr.file-wrap; $pr.emit-and-renew-processed-state; $report.text ~= "「{ $fn<path> }/{ $fn<name> }」" ~ " converted and written to 「{ $fn<oname> }.$ext」\n"; CATCH { default { my $msg = .message; $msg = $msg.substr(0, 150) ~ "\n{ '... (' ~ $msg.chars - 150 ~ ' more chars)' if $msg.chars > 150 }"; $report.text ~= "「{ $fn<path> }/{ $fn<name> }」" ~ " to .$ext " ~ ' encountered error: ' ~ .message ~ "\n"; .continue; } } } }
### ---------------------------------------------------- ### -- raku-pod-extraction ### -- Licenses: Artistic-2.0 ### -- Authors: Richard Hainsworth, aka finanalyst ### -- File: lib/RakuDocRender.rakumod ### ---------------------------------------------------- use v6.d; use Pod::To::HTML2:auth<zef:finanalyst>; use Pod::To::MarkDown2:auth<zef:finanalyst>; use ExtractPod; use GTK::Simple::App; use GTK::Simple::FileChooserButton; use GTK::Simple::MarkUpLabel; use GTK::Simple::VBox; use GTK::Simple::HBox; use GTK::Simple::CheckButton; use GTK::Simple::Entry; use GTK::Simple::Button; use GTK::Simple::TextView; use GTK::Simple::Grid; unit module RakuDocRender; #| adds a line to the grid. Needs @files to fix the line sub add-line(GTK::Simple::Grid $grid, @files) { my $grid-line = @files.elems + 1; my $col = 0; my %cnf = %( :path(''), :file(''), :oname(''), :convert, :md, :md-badge, :html, :html-hl ); $grid.attach( [$col++, $grid-line, 1, 1] => my $path = GTK::Simple::MarkUpLabel.new(:label('')), [$col++, $grid-line, 1, 1] => my $fc = GTK::Simple::FileChooserButton.new(:label('New file')), [$col++, $grid-line, 1, 1] => my $convert = GTK::Simple::CheckButton.new(:label('')), [$col++, $grid-line, 1, 1] => my $oname = GTK::Simple::Entry.new(text => %cnf<oname>), [$col++, $grid-line, 1, 1] => my $md = GTK::Simple::CheckButton.new(:label('')), [$col++, $grid-line, 1, 1] => my $md-badge = GTK::Simple::CheckButton.new(:label('')), [$col++, $grid-line, 1, 1] => my $html = GTK::Simple::CheckButton.new(:label('')), [$col++, $grid-line, 1, 1] => my $html-hl = GTK::Simple::CheckButton.new(:label('')), ); $md.status = $convert.status = $md.sensitive = $md-badge.sensitive = $html.sensitive = $convert.sensitive = False; # == Defined click actions for each file =================================== $md.toggled.tap: -> $b { %cnf<md> = !%cnf<md>; $md-badge.sensitive = %cnf<md>; $md-badge.status = False unless %cnf<md>; } $md-badge.toggled.tap: -> $b { %cnf<md-badge> = !%cnf<md-badge>; } $html.toggled.tap: -> $b { %cnf<html> = !%cnf<html>; $html-hl.sensitive = %cnf<html>; $html-hl.status = False unless %cnf<html>; } $html-hl.toggled.tap: -> $b { %cnf<html-hl> = !%cnf<html-hl>; } $convert.toggled.tap: -> $b { %cnf<convert> = !%cnf<convert> } $oname.changed.tap: -> $b { %cnf<oname> = $oname.text } # All option buttons off until a file is chosen $md.sensitive = $md-badge.sensitive = $html.sensitive = $html-hl.sensitive = $convert.sensitive = $oname.sensitive = $convert.status = $md.status = $md-badge.status = $html.status = $html-hl.status = False; %cnf{$_} = False for <md html md-badge html-hl convert>; $fc.file-set.tap: { my Bool $add = not %cnf<path>; my $fn = $fc.file-name; %cnf<file> = $fn; %cnf<path> = $fn.IO.relative.IO.dirname; $path.text = '<span foreground="darkgreen">' ~ %cnf<path> ~ '/</span>'; %cnf<oname> = $fn.IO.basename.IO.extension('').Str; $oname.text = %cnf<oname>; $md.sensitive = $html.sensitive = $convert.sensitive = $oname.sensitive = True; if $add { add-line($grid, @files) } else { # new file chosen, so reset status / options $convert.status = $md.status = $md-badge.status = $html.status = $html-hl.status = False; %cnf{$_} = False for <md html md-badge html-hl convert> } } @files.push: %cnf } sub MAIN is export { my @files; # App initiation ============================ my $app = GTK::Simple::App.new(:title("Rakudoc Extractor Utility")); $app.border-width = 5; # =============================================================== # File box my $col = 0; my $file-grid = GTK::Simple::Grid.new( [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="darkgreen">input file path</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('{' ~ '-' x 12 ~ '<span foreground="green">input file</span>' ~ '-' x 12 ~ '}')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="blue">Convert?</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="green">output file in CWD</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="blue">.md?</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="violet">badge?</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="blue">.html?</span>')), [$col++, 0, 1, 1] => GTK::Simple::MarkUpLabel.new(:text('<span foreground="violet">hilite?</span>')), ); $file-grid.column-spacing = 10; add-line($file-grid, @files); # Report pane =============================================================== my $report = GTK::Simple::TextView.new; $report.alignment = LEFT; # =Bottom buttons ============================================ my $cancel; my $action; my $button-row = GTK::Simple::HBox.new([ $cancel = GTK::Simple::Button.new(:label<Cancel>), $action = GTK::Simple::Button.new(:label<Convert>) ]); $cancel.clicked.tap: -> $b { $app.exit }; $action.clicked.tap: -> $b { if +@files > 1 { $cancel.label = 'Finish'; my @md = @files.grep({ .<file> and .<md> and .<convert> }); my @html = @files.grep({ .<file> and .<html> and .<convert> }); HTML(@html, $report) if ?@html; MarkDown(@md, $report) if ?@md; unless ?@html or ?@md { $report.text ~= "No files with .md or .html selected\n" } } else { $report.text ~= "Select a file and add conversion option\n" } }; #============================= # App setup and run $app.set-content(GTK::Simple::VBox.new([ { :widget($file-grid), :!expand }, { :widget($button-row), :!expand }, { :widget($report), :!expand } ])); $app.show; $app.run } sub HTML(@fn, $report) { # when there is no highlighting, the code needs escaping my Pod::To::HTML2 $pr .= new; process(@fn, $report, $pr, 'html') } sub MarkDown(@fn, $report) { my Pod::To::MarkDown2 $pr .= new; process(@fn, $report, $pr, 'md') } sub process(@fn, $report, $pr, $ext) { for @fn -> $fn { $pr.pod-file.path = $pr.pod-file.name = $pr.pod-file.title = $fn<oname>; $pr.github-badge = $fn<md-badge> if $fn<md>; $pr.highlight = $fn<html-hl> if $fn<html>; my $pod = load($fn<path> ~ '/' ~ $fn<name>); $pr.render-tree($pod); $pr.file-wrap; $pr.emit-and-renew-processed-state; $report.text ~= "「{ $fn<path> }/{ $fn<name> }」" ~ " converted and written to 「{ $fn<oname> }.$ext」\n"; CATCH { default { exit note( .message ~ .backtrace); # my $msg = .message; # $msg = $msg.substr(0, 150) ~ "\n{ '... (' ~ $msg.chars - 150 ~ ' more chars)' if $msg.chars > 150 }"; # $report.text ~= "「{ $fn<path> }/{ $fn<name> }」" # ~ " to .$ext " # ~ ' encountered error: ' # ~ .message ~ "\n"; # .resume } } } }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: META6.json ### ---------------------------------------------------- { "api": "1", "auth": "zef:coke", "authors": [ "Joel D. S. <@noisegul>", "Tim Siegel <github:softmoth>", "Will Coleda" ], "build-depends": [ ], "depends": [ { "name": "Pod::Utils", "version": "0.0.2+" } ], "description": "A tool for reading Raku documentation", "license": "Artistic-2.0", "name": "rakudoc", "perl": "6.d", "provides": { "Rakudoc": "lib/Rakudoc.rakumod", "Rakudoc::CMD": "lib/Rakudoc/CMD.rakumod", "Rakudoc::Documentable": "lib/Rakudoc/Documentable.rakumod", "Rakudoc::Pod::Cache": "lib/Rakudoc/Pod/Cache.rakumod" }, "raku": "6.d", "resources": [ "doc/bin/rakudoc.rakudoc" ], "source-url": "https://github.com/Raku/rakudoc.git", "support": { "bugtracker": "https://github.com/Raku/rakudoc/issues" }, "tags": [ ], "test-depends": [ { "name": "IO::MiddleMan", "version": "1.001003+" }, { "name": "File::Directory::Tree" }, { "name": "File::Temp", "version": "0.0.8+" } ], "version": "0.2.6" }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: LICENSE ### ---------------------------------------------------- The Artistic License 2.0 Copyright (c) 2000-2006, The Perl Foundation. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble This license establishes the terms under which a given free software Package may be copied, modified, distributed, and/or redistributed. The intent is that the Copyright Holder maintains some artistic control over the development of that Package while still keeping the Package available as open source and free software. You are always permitted to make arrangements wholly outside of this license directly with the Copyright Holder of a given Package. If the terms of this license do not permit the full use that you propose to make of the Package, you should contact the Copyright Holder and seek a different licensing arrangement. Definitions "Copyright Holder" means the individual(s) or organization(s) named in the copyright notice for the entire Package. "Contributor" means any party that has contributed code or other material to the Package, in accordance with the Copyright Holder's procedures. "You" and "your" means any person who would like to copy, distribute, or modify the Package. "Package" means the collection of files distributed by the Copyright Holder, and derivatives of that collection and/or of those files. A given Package may consist of either the Standard Version, or a Modified Version. "Distribute" means providing a copy of the Package or making it accessible to anyone else, or in the case of a company or organization, to others outside of your company or organization. "Distributor Fee" means any fee that you charge for Distributing this Package or providing support for this Package to another party. It does not mean licensing fees. "Standard Version" refers to the Package if it has not been modified, or has been modified only in ways explicitly requested by the Copyright Holder. "Modified Version" means the Package, if it has been changed, and such changes were not explicitly requested by the Copyright Holder. "Original License" means this Artistic License as Distributed with the Standard Version of the Package, in its current version or as it may be modified by The Perl Foundation in the future. "Source" form means the source code, documentation source, and configuration files for the Package. "Compiled" form means the compiled bytecode, object code, binary, or any other form resulting from mechanical transformation or translation of the Source form. Permission for Use and Modification Without Distribution (1) You are permitted to use the Standard Version and create and use Modified Versions for any purpose without restriction, provided that you do not Distribute the Modified Version. Permissions for Redistribution of the Standard Version (2) You may Distribute verbatim copies of the Source form of the Standard Version of this Package in any medium without restriction, either gratis or for a Distributor Fee, provided that you duplicate all of the original copyright notices and associated disclaimers. At your discretion, such verbatim copies may or may not include a Compiled form of the Package. (3) You may apply any bug fixes, portability changes, and other modifications made available from the Copyright Holder. The resulting Package will still be considered the Standard Version, and as such will be subject to the Original License. Distribution of Modified Versions of the Package as Source (4) You may Distribute your Modified Version as Source (either gratis or for a Distributor Fee, and with or without a Compiled form of the Modified Version) provided that you clearly document how it differs from the Standard Version, including, but not limited to, documenting any non-standard features, executables, or modules, and provided that you do at least ONE of the following: (a) make the Modified Version available to the Copyright Holder of the Standard Version, under the Original License, so that the Copyright Holder may include your modifications in the Standard Version. (b) ensure that installation of your Modified Version does not prevent the user installing or running the Standard Version. In addition, the Modified Version must bear a name that is different from the name of the Standard Version. (c) allow anyone who receives a copy of the Modified Version to make the Source form of the Modified Version available to others under (i) the Original License or (ii) a license that permits the licensee to freely copy, modify and redistribute the Modified Version using the same licensing terms that apply to the copy that the licensee received, and requires that the Source form of the Modified Version, and of any works derived from it, be made freely available in that license fees are prohibited but Distributor Fees are allowed. Distribution of Compiled Forms of the Standard Version or Modified Versions without the Source (5) You may Distribute Compiled forms of the Standard Version without the Source, provided that you include complete instructions on how to get the Source of the Standard Version. Such instructions must be valid at the time of your distribution. If these instructions, at any time while you are carrying out such distribution, become invalid, you must provide new instructions on demand or cease further distribution. If you provide valid instructions or cease distribution within thirty days after you become aware that the instructions are invalid, then you do not forfeit any of your rights under this license. (6) You may Distribute a Modified Version in Compiled form without the Source, provided that you comply with Section 4 with respect to the Source of the Modified Version. Aggregating or Linking the Package (7) You may aggregate the Package (either the Standard Version or Modified Version) with other packages and Distribute the resulting aggregation provided that you do not charge a licensing fee for the Package. Distributor Fees are permitted, and licensing fees for other components in the aggregation are permitted. The terms of this license apply to the use and Distribution of the Standard or Modified Versions as included in the aggregation. (8) You are permitted to link Modified and Standard Versions with other works, to embed the Package in a larger work of your own, or to build stand-alone binary or bytecode versions of applications that include the Package, and Distribute the result without restriction, provided the result does not expose a direct interface to the Package. Items That are Not Considered Part of a Modified Version (9) Works (including, but not limited to, modules and scripts) that merely extend or make use of the Package, do not, by themselves, cause the Package to be a Modified Version. In addition, such works are not considered parts of the Package itself, and are not subject to the terms of this license. General Provisions (10) Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license. (11) If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license. (12) This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder. (13) This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed. (14) Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: README.md ### ---------------------------------------------------- [![Build Status](https://travis-ci.com/Raku/rakudoc.svg?branch=master)](https://travis-ci.com/Raku/rakudoc) NAME ==== rakudoc - A tool for reading Raku documentation SYNOPSIS ======== rakudoc [-d|--doc-sources=<Directories>] [-D|--no-default-docs] <query> rakudoc -b|--build-index [-d|--doc-sources=<Directories>] [-D|--no-default-docs] rakudoc -V|--version rakudoc -h|--help <ARGUMENTS> <query> Example: 'Map', 'IO::Path.add', '.add' -d|--doc-sources=<Directories> Additional directories to search for documentation -D|--no-default-docs Use only directories in --doc / $RAKUDOC -b|--build-index Index all documents found in doc source directories DESCRIPTION =========== The `rakudoc` command displays Raku documentation for language features and installed modules. ENVIRONMENT =========== * `RAKUDOC` — Comma-separated list of doc directories (e.g., `../doc/doc,./t/test-doc`); ignored if `--doc-sources` option is given * `RAKUDOC_DATA` — Path to directory where Rakudoc stores cache and index data * `RAKUDOC_PAGER` — Pager program (default: `$PAGER`) LICENSE ======= Rakudoc is Copyright (C) 2019–2021, by Joel Schüller, Tim Siegel and others. It is free software; you can redistribute it and/or modify it under the terms of the [Artistic License 2.0](https://www.perlfoundation.org/artistic-license-20.html).
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: .travis.yml ### ---------------------------------------------------- services: - docker install: - docker pull jjmerelo/perl6-doccer - docker images script: - docker run -t -v $TRAVIS_BUILD_DIR:/test --entrypoint=/bin/sh jjmerelo/perl6-doccer ./.travis/docker-entrypoint.sh
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: dist.ini ### ---------------------------------------------------- ; App::Mi6 configuration name = rakudoc [UploadToZef] [ReadmeFromPod] filename=resources/doc/bin/rakudoc.rakudoc [Badges] provider = travis-ci.com [PruneFiles] filename = dist.ini match = ^ '.git' match = ^ '.travis' match = ^ 'xt/'
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/02-cache.t ### ---------------------------------------------------- use Test; use File::Temp; use Rakudoc::Pod::Cache; plan 6; my $test-doc = 't/test-doc/Type/Map.rakudoc'; my $cache-path = tempdir.IO.add('cache'); my $pc = Rakudoc::Pod::Cache.new: :$cache-path; isa-ok $pc, Rakudoc::Pod::Cache, "Create cache object"; is $cache-path.e, False, "Cache dir is not created until needed"; like $pc.pod($test-doc).?first.^name, /^ 'Pod::'/, "pod('relative/path.ext') returns a Pod"; is $cache-path.d, True, "Cache dir is created when needed"; like $pc.pod($test-doc.IO).?first.^name, /^ 'Pod::'/, "pod('relative/path.ext'.IO) returns a Pod"; throws-like { $pc.pod('nonexistent') }, X::Multi::NoMatch, "pod('nonexistent') dies";
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/00-load.t ### ---------------------------------------------------- use Test; plan 2; use-ok('Rakudoc'); use-ok('Rakudoc::CMD');
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/01-cmd.t ### ---------------------------------------------------- use Test; %*ENV<RAKUDOC_TEST> = '1'; %*ENV<RAKUDOC> = 't/test-doc'; my @tests = \('test-no-match'), [ False, / ^ $ /, / No .* 'test-no-match' / ], \(:help), [ True, / ^ Usage /, / ^ $ /], \('Map'), [ True, / 'class Map' \N+ 'does Associative' / ], \('X::IO'), [ True, / 'role X::IO does X::OS' / ], \('Hash.classify-list'), [ True, / 'method classify-list' / ], ; plan +@tests / 2; # The following is a way to test `MAIN`s from Rakudoc::CMD directly without # triggering usage. The C<use Rakudoc::CMD> must be in a new lexical scope, # where its MAIN will be harmlessly installed but not jumped to. BEGIN sub MAIN(|) { }; for @tests -> $args, $like { subtest "MAIN {$args.gist}" => { my ($result-is, $out-like, $err-like) = @$like; plan $err-like.defined ?? 3 !! 2; my ($result, $out, $err) = run-test $args; is $result, $result-is, "returns $result-is"; like $out, $out-like, "output like {$out-like.gist}"; like $err, $_, "output like {.gist}" with $err-like; } } sub run-test($args) { use IO::MiddleMan; use Rakudoc::CMD; my $result; my $*USAGE = "Usage:\n Mock USAGE for testing\n"; my ($out, $err) = map { IO::MiddleMan.hijack: $_ }, $*OUT, $*ERR; try $result = Rakudoc::CMD::MAIN(|$args); for $err, $out { .mode = 'normal' } die $! if $!; ($result, ~$out, ~$err); }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/03-documentable.t ### ---------------------------------------------------- use Test; use Rakudoc; %*ENV<RAKUDOC_TEST> = '1'; %*ENV<RAKUDOC> = 't/test-doc'; plan 2; my $rakudoc = Rakudoc.new; subtest "language" => { plan 3; my $doc = Doc::Documentable.new: :$rakudoc, :doc-source(%*ENV<RAKUDOC>.IO), :filename('Language'.IO.add('operators.rakudoc')); isa-ok $doc, Rakudoc::Doc::Documentable, "Doc repr for Language/operators"; like $doc.gist, rx/operators/, "Gist looks okay"; like $rakudoc.render($doc), rx/Operators/, "Render looks okay"; } subtest "type" => { plan 4; my $doc = Doc::Documentable.new: :$rakudoc, :doc-source(%*ENV<RAKUDOC>.IO), :filename('Type'.IO.add('Any.rakudoc')); like $rakudoc.render($doc), rx:s/class Any/, "Render looks okay"; $doc = Doc::Documentable.new: :$rakudoc, :doc-source(%*ENV<RAKUDOC>.IO), :filename('Type'.IO.add('Any.rakudoc')), :def<root>; like $rakudoc.render($doc), rx:s/Subparsing/, "def = 'root' shows root portion"; unlike $rakudoc.render($doc), rx:s/class Any/, "def = 'root' doesn't show parent content"; $doc = Doc::Documentable.new: :$rakudoc, :doc-source(%*ENV<RAKUDOC>.IO), :filename('Type'.IO.add('Any.rakudoc')), :def<notfound>; like $rakudoc.render($doc), rx:s/class Any/, "def = 'notfound' shows full doc"; }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/05-index.t ### ---------------------------------------------------- use Test; use Rakudoc; use Pod::To::Text; use File::Directory::Tree; %*ENV<RAKUDOC_TEST> = '1'; %*ENV<RAKUDOC> = 't/test-doc'; plan 12; my $data-dir = 't/test-cache'.IO; rmtree $data-dir; nok $data-dir.e, "Test data-dir removed at start"; my $rakudoc = Rakudoc.new: :no-default-docs, :$data-dir; nok $data-dir.e, "Rakudoc.new does not create data dir"; my $index = $rakudoc.index; ok $data-dir.d, "Rakudoc.index creates data dir"; nok $index.index-dir.e, "Rakudoc.index does not create index dir"; is $rakudoc.warnings.elems, 0, "No warnings issued before lookup"; is $index.def('mro'), (), "Lookup in empty index returns empty"; diag "($_)" for $rakudoc.warnings; ok $rakudoc.warnings.elems > 0, "Warnings issued for non-indexed source"; $rakudoc.warnings = Empty; nok $index.index-dir.e, "Lookup does not create index dir"; $index.build; ok $index.index-dir.d, "Rakudoc.index creates index dir"; diag "($_)" for $rakudoc.warnings; is $rakudoc.warnings.elems, 2, "Test docs contain 2 non-Documentable docs"; $rakudoc.warnings = Empty; subtest 'Validate every indexed source', { my $names = set $index.defs.values.map(*.values».list).flat; plan 1 + $names.elems; ok $names.elems > 5, "At least 5 test docs contain defs (sanity)"; for $names.keys -> $name { my @docs = $rakudoc.search: $rakudoc.request: $name; is +@docs, 1, "Doc found for name '$name'"; } } subtest 'Validate lookup of every def', { my $defs = set $index.defs.values.map(*.keys».list).flat; plan 1 + $defs.elems * 2; ok $defs.elems > 5, "Test docs contain at least 5 distinct defs (sanity)"; for $defs.keys.sort -> $def { my @entries = $index.def($def); ok +@entries > 0, "Look up entries for '$def' (found {+@entries})"; my @texts = @entries.map: { my $doc = Doc::Documentable.new: :$rakudoc, :filename(.key), :doc-source(.value), :$def; pod2text($doc.pod) }; next if is +@entries, [email protected](*.contains($def)), "All entries for '$def' can be displayed"; diag "{.key.raku}\n{.value.raku}\n" for @entries Z=> @texts; } }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: t/test-doc/type-graph.txt ### ---------------------------------------------------- [basic] class pod1 class pod2 class Cool role Associative class Hash class Cancellation class Array class Map role X::IO class int
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: xt/00-meta.t ### ---------------------------------------------------- use Test; use Test::META; plan 1; meta-ok;
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: lib/Rakudoc.rakumod ### ---------------------------------------------------- use Rakudoc::Documentable; use Pod::To::Text; use Rakudoc::Pod::Cache; my class X::Rakudoc is Exception { has $.message; } my class X::Rakudoc::BadQuery is X::Rakudoc {} my class X::Rakudoc::BadDocument is X::Rakudoc { has $.doc; has $.message; method message { "Error processing document {$!doc.gist}: $!message"; } } class Rakudoc:auth<zef:coke>:api<1>:ver<0.2.6> { has @.doc-sources; has $.data-dir; has $!cache; has $!index; has @!extensions = <pod6 rakudoc>; has @.warnings; submethod TWEAK( :$doc-sources is copy, :$no-default-docs, :$data-dir, ) { $doc-sources = self.doc-sources-from-str($doc-sources) if $doc-sources and $doc-sources ~~ Stringy; $doc-sources = grep *.defined, $doc-sources<>; $doc-sources ||= self.doc-sources-from-str(%*ENV<RAKUDOC>); $doc-sources = [$doc-sources<>.grep(*.chars)]; unless $no-default-docs { $doc-sources.append: $*REPO.repo-chain.map({.?abspath.IO // Empty})».add('doc'); } @!doc-sources = map *.resolve, grep *.d, map *.IO, @$doc-sources; $!data-dir = self!resolve-data-dir($data-dir // %*ENV<RAKUDOC_DATA>); } role Request { has $.rakudoc; } role Doc { has $.rakudoc; has $.origin; has $.def; method source { ... } method pod { ... } method gist { ... } } class Doc::Documentable does Doc { has $.doc-source; has $.filename; has $!documentable; submethod TWEAK( :$doc-source!, :$filename! is copy, ) { $!doc-source = $doc-source.IO; $!origin = $!doc-source.add($filename); if $!origin.e { $!filename = $filename.IO; } else { with $!rakudoc.search-doc-sources($filename, @$!doc-source) { $!filename = .first.key; $!origin = $!doc-source.add($!filename); } else { $!filename = $filename; X::Documentable::BadDocument.new( :doc(self), :message("'$!origin' does not exist") ).throw; } } } method source { state $ //= $!origin.slurp } method pod { my @pod; @pod = $.documentable.defs.grep({.name eq $!def}).map(*.pod) if $!def; @pod || $.documentable.pod; } method gist { "Doc {$!origin.absolute}" } method filename { # Drop the extension my $f = $!filename.IO.extension('', :parts(1)); # Drop the first directory (Documentable Kind dir, e.g. "Type") $f.SPEC.catdir($f.SPEC.splitdir($f).tail(*-1)) } method documentable { return $_ with $!documentable; my $pod = $!rakudoc.cache.pod($!origin.absolute); { # Documentable is strict about Pod contents currently, and will # probably throw (X::Adhoc) for anything that isn't in the main # doc repo. CATCH { default { fail X::Rakudoc::BadDocument.new: :doc(self), :message(~$_) } } $!documentable = Documentable::Primary.new: :pod($pod.first), :$.filename, :source-path($!origin.absolute); } } } class Doc::Handle does Doc { method source { state $ //= $!origin.slurp } method pod { # TODO Parsing Pod # TODO Handle $.def '' } method gist { "Doc {$!origin.?path // $!origin.gist}" } } class Doc::CompUnit does Doc { method source { my $prefix = $!origin.repo.prefix; my $source = $!origin.distribution.meta<source>; if $prefix && $source && "$prefix/sources/$source".IO.e { state $ //= "$prefix/sources/$source".IO.slurp } else { $!rakudoc.warn: "Module exists, but no source file for {self}"; '' } } method pod { $!rakudoc.cache.pod($!origin.handle) # TODO Handle $.def } method gist { "Doc {$!origin.repo.prefix} {$!origin}" } method filename { ~ $!origin } } class Request::Name does Request { has $.name; has $.def; method Str { "'{$.name}{'.' ~ $.def if $.def}'" } } class Request::Def does Request { has $.def; method Str { "'.{$.def}'" } } class Request::Path does Request { has $.path; method Str { "'{$.path}'" } } grammar Request::Grammar { token TOP { <module> <definition>? | <definition> } token module { <-[\s.]> + } token definition { '.' <( <-[\s.]> + )> } } method request(Str $query) { return Request::Path.new: :path($query) if $query.IO.e; Request::Grammar.new.parse($query) or die X::Rakudoc::BadQuery.new: :message("unrecognized query: $query"); if $/<module> { Request::Name.new: :name($/<module>), :def($/<definition>) } else { Request::Def.new: :def($/<definition>) } } method search(Request $req) { given $req { when Request::Name { # Names can match either a doc file or an installed module flat self.search-doc-sources($req.name, self.doc-sources) .map({ Doc::Documentable.new: :rakudoc(self), :filename(.key), :doc-source(.value), :def($req.def) }), self.search-repos(~$req.name).map({ Doc::Handle.new: :rakudoc(self), :origin($_), :def($req.def) }), self!locate-curli-module(~$req.name).map({ Doc::CompUnit.new: :rakudoc(self), :origin($_), :def($req.def) }), } when Request::Def { self.index.def($req.def).map: { Doc::Documentable.new: :rakudoc(self), :filename(.key), :doc-source(.value), :def($req.def); } } when Request::Path { Doc::Handle.new: :rakudoc(self), :origin(.path.IO) } } } method search-repos($str) { my $fragment = IO::Spec::Unix.catdir: $str.split('::'); map -> $dist { | $dist.meta.<files>.keys.grep(/ '/' $fragment '.' /).map({ $dist.content($_) }) }, grep *.defined, flat $*REPO.repo-chain.map({ .?candidates($str).?head }) } method search-doc-sources($str, @doc-sources) { my $fragment = reduce { $^a.add($^b) }, '.'.IO, | $str.split('::'); # Add extension unless it already has one my @fragments = $fragment.extension(:parts(1)) ?? $fragment !! @!extensions.map({ $fragment.extension($_, :parts(0)) }); gather for @doc-sources.map(*.IO) -> $doc-source { for @fragments -> $fragment { if $doc-source.add($fragment).e { take $fragment => $doc-source } else { for $doc-source.dir(:test(*.starts-with('.').not)) .grep(*.d) { with .basename.IO.add($fragment) { take $_ => $doc-source if $doc-source.add($_).e } } } } } } method render(Doc $doc) { my $text = join "\n\n", grep / \w /, map { pod2text($_).trim ~ "\n" }, $doc.pod; # Should pod2text come up empty, present the raw document source $text ||= $doc.source; $text } method cache { return $!cache if $!cache; $!data-dir.mkdir unless $!data-dir.d; $!cache = Rakudoc::Pod::Cache.new: :cache-path($!data-dir.add('cache')); } class Index { has $.rakudoc; has $.index-dir; has $!defs; method def($needle) { grep { state %seen; not %seen{$_}++ }, $!rakudoc.doc-sources.map: -> $doc-source { | .map({ $_ => $doc-source }) with $.defs{ $doc-source }{ $needle } } } method defs { self!load unless $!defs.defined; $!defs } method build { $!index-dir.mkdir unless $!index-dir.d; for $!rakudoc.doc-sources -> $doc-source { my %defs; my $index = self!source-index($doc-source); my $docs = $!rakudoc.enumerate-docs-dir($doc-source); note "Indexing {+$docs} docs", " from '$doc-source' in '$!index-dir'"; for @$docs { my $dd = Doc::Documentable.new: :$!rakudoc, :$doc-source, :filename(.IO.relative($doc-source)); with $dd.documentable -> $doc { for $doc.defs -> $def { %defs{$def.name}.push($doc.filename) } } else { when Failure { $!rakudoc.warn: .exception.message } default { .throw } } } $index.spurt: join '', map { ($_, |%defs{$_}).join("\t") ~ "\n" }, %defs.keys.sort; $!defs{$doc-source} = %defs; } $!defs } method !load { for $!rakudoc.doc-sources -> $doc-source { my $index = self!source-index($doc-source); $!defs{$doc-source} = do if $index.e { hash $index.lines».split("\t").map: -> ($def, *@names) { $def => @names } } else { $++ or $!rakudoc.warn: "Run 'rakudoc -b' to build index:"; $!rakudoc.warn: "- no index built for '$doc-source'"; hash Empty } ; } } method !source-index($source) { use nqp; $!index-dir.add: nqp::sha1($source.absolute) } } method index { return $!index if $!index; $!data-dir.mkdir unless $!data-dir.d; $!index = Index.new: :rakudoc(self), :index-dir($!data-dir.add('index')); } method warn($warning) { @!warnings.push: $warning; } method !resolve-data-dir($data-dir) { # A major limitation is that currently there can only be a single # Pod::Cache instance in a program (due to precompilation guts?) # See https://github.com/finanalyst/raku-pod-from-cache/blob/master/t/50-multiple-instance.t # # This precludes having a read-only system-wide cache and a # user-writable fallback. So for now, each user must build & update # their own cache. return $data-dir.IO.resolve(:completely) if $data-dir; # By default, this will be ~/.cache/raku/rakudoc-data on most Unix # distributions, and ~\.raku\rakudoc-data on Windows and others my IO::Path @candidates = map *.add('rakudoc-data'), # Here is one way to get a system-wide cache: if all raku users are # able to write to the raku installation, then this would probably # work; of course, this will also require file locking to prevent # users racing against each other while updating the cache / indexes #$*REPO.repo-chain.map({.?prefix.?IO // Empty}) # .grep({ $_ ~~ :d & :w }) # .first(not *.absolute.starts-with($*HOME.absolute)), %*ENV<XDG_CACHE_HOME>.?IO.?add('raku') // Empty, %*ENV<XDG_CACHE_HOME>.?IO // Empty, $*HOME.add('.raku'), $*HOME.add('.perl6'), $*CWD; ; @candidates.first(*.f) // @candidates.first; } method !locate-curli-module($short-name) { # TODO This is only the first one; keep on searching somehow? my $cu = try $*REPO.need(CompUnit::DependencySpecification.new: :$short-name); $cu // Empty } method enumerate-docs-dir($doc) { $doc.dir.map: { unless .basename.starts-with('.') { if .d { | self.enumerate-docs-dir($_) } else { $_ if .extension eq any(@!extensions) } } } } method doc-sources-from-str($str) { ($str // '').split(',')».trim } }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: lib/Rakudoc/Documentable.rakumod ### ---------------------------------------------------- use Pod::Utils; use Pod::Utils::Build; #| Enum to classify all "kinds" of Documentable enum Kind is export (Type => "type" , Language => "language", Programs => "programs" , Syntax => "syntax" , Reference => "reference", Routine => "routine" ); #| List of the subdirectories that contain indexable pods by default constant DOCUMENTABLE-DIRS is export = ["Language", "Type", "Programs", "Native"]; class X::Documentable::TitleNotFound is Exception { has $.filename; method message() { "=TITLE element not found in $.filename pod file." } } class X::Documentable::SubtitleNotFound is Exception { has $.filename; method message() { "=SUBTITLE element not found in $.filename pod file." } } class X::Documentable::MissingMetadata is Exception { has $.filename; has $.metadata; method message() { "$.metadata not found in $.filename pod file config. \n" ~ "The first line of the pod should contain: \n" ~ "=begin pod :kind('<value>') :subkind('<value>') :category('<value>') \n" } } grammar Documentable::Heading::Grammar { token operator { infix | prefix | postfix | circumfix | postcircumfix | listop } token routine { sub | method | term | routine | submethod | trait } token syntax { twigil | constant | variable | quote | declarator } token subkind { <routine> | <syntax> | <operator> } token name { .* } # is rw token single-name { \S* } # infix rule the-foo-infix {^\s*[T|t]'he' <single-name> <subkind>\s*$} rule infix-foo {^\s*<subkind> <name>\s*$} rule TOP { <the-foo-infix> | <infix-foo> } } class Documentable::Heading::Actions { has Str $.dname = ''; has $.dkind ; has Str $.dsubkind = ''; has Str $.dcategory = ''; method name($/) { $!dname = $/.Str; } method single-name($/) { $!dname = $/.Str; } method subkind($/) { $!dsubkind = $/.Str.trim; } method operator($/) { $!dkind = Kind::Routine; $!dcategory = "operator"; } method routine($/) { $!dkind = Kind::Routine; $!dcategory = $/.Str; } method syntax($/) { $!dkind = Kind::Syntax; $!dcategory = $/.Str; } } #| Converts Lists of Pod::Blocks to String multi textify-pod (Any:U , $?) is export { '' } multi textify-pod (Str:D \v, $?) is export { v } multi textify-pod (List:D \v, $separator = ' ') is export { v».&textify-pod.join($separator) } multi textify-pod (Pod::Block \v, $?) is export { # core module use Pod::To::Text; pod2text v; } #| Everything documented inherits from this class class Documentable { has Str $.name; has $.pod is required("Needs an actual document"); has Kind $.kind is required("Is essential metadata"); has @.subkinds = []; has @.categories = []; submethod BUILD ( :$!name, :$!kind!, :@!subkinds, :@!categories, :$!pod!, ) {} method english-list () { return '' unless @!subkinds.elems; @!subkinds > 1 ?? @!subkinds[0..*-2].join(", ") ~ " and @!subkinds[*-1]" !! @!subkinds[0] } method human-kind() { $!kind eq Kind::Language ?? 'language documentation' !! @!categories eq 'operator' ?? "@!subkinds[] operator" !! self.english-list // $!kind; } method categories() { return @!categories if @!categories; return @!subkinds; } } #| Every type of page generated, must implement this role role Documentable::DocPage { method render (| --> Hash) { ... } } # these chars cannot appear in a unix filesystem path sub good-name($name is copy --> Str) { # / => $SOLIDUS # % => $PERCENT_SIGN # ^ => $CIRCUMFLEX_ACCENT # # => $NUMBER_SIGN my @badchars = ["/", "^", "%"]; my @goodchars = @badchars .map({ '$' ~ .uniname }) .map({ .subst(' ', '_', :g)}); $name = $name.subst(@badchars[0], @goodchars[0], :g); $name = $name.subst(@badchars[1], @goodchars[1], :g); # if it contains escaped sequences (like %20) we do not # escape % if ( ! ($name ~~ /\%<xdigit>**2/) ) { $name = $name.subst(@badchars[2], @goodchars[2], :g); } return $name; } sub rewrite-url($s, $prefix?) { given $s { when {.starts-with: 'http' or .starts-with: '#' or .starts-with: 'irc' } { $s } default { my @parts = $s.split: '/'; my $name = good-name(@parts[*-1]); my $new-url = @parts[0..*-2].join('/') ~ "/$name"; if ($new-url ~~ /\.$/) { $new-url = "{$new-url}.html" } return "/{$prefix}{$new-url}" if $prefix; return $new-url; } } } class Documentable::Index is Documentable { has $.origin; has @.meta; method new( :$pod!, :$meta!, :$origin! ) { my $name; if $meta.elems > 1 { my $last = textify-pod $meta[*-1]; my $rest = $meta[0..*-2]; $name = "$last ($rest)"; } else { $name = textify-pod $meta; } nextwith( kind => Kind::Reference, subkinds => ['reference'], name => $name.trim, :$pod, :$origin, :$meta ); } method url() { my $index-text = recurse-until-str($.pod).join; my @indices = $.pod.meta; my $fragment = qq[index-entry{@indices ?? '-' !! ''}{@indices.join('-')}{$index-text ?? '-' !! ''}$index-text] .subst('_', '__', :g).subst(' ', '_', :g); return $.origin.url ~ "#" ~ good-name($fragment); } } class Documentable::Secondary is Documentable { has $.origin; has Str $.url; has Str $.url-in-origin; method new( :$kind!, :$name!, :@subkinds, :@categories, :$pod!, :$origin ) { my $url = "/{$kind.Str.lc}/{good-name($name)}"; my $url-in-origin = $origin.url ~ "#" ~textify-pod($pod[0]).trim.subst(/\s+/, '_', :g); # normalize the pod my $title = "($origin.name()) @subkinds[] $name"; my $new-head = Pod::Heading.new( level => 2, contents => [ pod-link($title, $url-in-origin) ] ); my @chunk = flat $new-head, $pod[1..*-1]; @chunk = pod-lower-headings( @chunk, :to(2) ); nextwith( :$kind, :$name, :@subkinds, :@categories, :pod(@chunk), :$origin, :$url, :$url-in-origin ); } } class Documentable::Primary is Documentable { has Str $.summary; has Str $.url; has Str $.filename; has Str $.source-path; #| Definitions indexed in this pod has @.defs; #| References indexed in this pod has @.refs; method new ( Str :$filename!, Str :$source-path!, :$pod! ) { self.check-pod($pod, $filename); my $kind = Kind( $pod.config<kind>.lc ); # proper name from =TITLE my $title = $pod.contents[0]; my $name = recurse-until-str($title); $name = $name.split(/\s+/)[*-1] if $kind eq Kind::Type; # summary from =SUBTITLE my $subtitle = $pod.contents[1]; my $summary = recurse-until-str($subtitle); my $url = do given $kind { when Kind::Type {"/{$kind.Str}/$name" } default {"/{$kind.Str}/$filename"} } # use metadata in pod config my @subkinds = $pod.config<subkind>.List; my @categories = $pod.config<category>.List; nextwith( :$pod, :$kind, :$name, :$summary, :$url :@subkinds, :@categories, :$filename, :$source-path ); } submethod TWEAK(:$pod) { self.find-definitions(:$pod); self.find-references(:$pod); } method check-pod($pod, $filename?) { # check title my $title = $pod.contents[0]; die X::Documentable::TitleNotFound.new(:$filename) unless ($title ~~ Pod::Block::Named and $title.name eq "TITLE"); # check subtitle my $subtitle = $pod.contents[1]; die X::Documentable::SubtitleNotFound.new(:$filename) unless ($subtitle ~~ Pod::Block::Named and $subtitle.name eq "SUBTITLE"); # check metadata my $correct-metadata = $pod.config<kind> and $pod.config<subkind> and $pod.config<category>; die X::Documentable::MissingMetadata.new(:$filename, metadata => "kind") unless $correct-metadata; } method parse-definition-header(Pod::Heading :$heading --> Hash) { my @header; try { @header := $heading.contents[0].contents; CATCH { return %(); } } my %attr; if ( @header[0] ~~ Pod::FormattingCode and +@header eq 1 # avoid =headn X<> and X<> ) { my $fc = @header.first; return %() if $fc.type ne "X"; my @meta = $fc.meta[0]:v.flat.cache; my $name = (@meta > 1) ?? @meta[1] !! textify-pod($fc.contents[0], ''); %attr = name => $name.trim, kind => Kind::Syntax, subkinds => @meta || (), categories => @meta || (); } else { my $g = Documentable::Heading::Grammar.parse( textify-pod(@header, '').trim, :actions(Documentable::Heading::Actions.new) ).actions; # no match, no valid definition return %attr unless $g; %attr = name => $g.dname, kind => $g.dkind, subkinds => $g.dsubkind.List, categories => $g.dcategory.List; } return %attr; } method find-definitions( :$pod, Int :$min-level = -1, --> Int ) { my @pod-section = $pod ~~ Positional ?? @$pod !! $pod.contents; my int $i = 0; my int $len = +@pod-section; while $i < $len { NEXT {$i = $i + 1} my $pod-element := @pod-section[$i]; # only headers are possible definitions next unless $pod-element ~~ Pod::Heading; # if we have found a heading with a lower level, then the subparse # has been finished return $i if $pod-element.level <= $min-level; my %attr = self.parse-definition-header(:heading($pod-element)); next unless %attr; # Perform sub-parse, checking for definitions elsewhere in the pod # And updating $i to be after the places we've already searched my $new-i = $i + self.find-definitions( :pod(@pod-section[$i+1..*]), :min-level(@pod-section[$i].level), ); # At this point we have a valid definition my $created = Documentable::Secondary.new( origin => self, pod => @pod-section[$i .. $new-i], |%attr ); @!defs.push: $created; $i = $new-i + 1; } return $i; } method find-references(:$pod) { if $pod ~~ Pod::FormattingCode && $pod.type eq 'X' { if ($pod.meta) { for @( $pod.meta ) -> $meta { @!refs.push: Documentable::Index.new( pod => $pod, meta => $meta, origin => self ) } } else { @!refs.push: Documentable::Index.new( pod => $pod, meta => $pod.contents[0], origin => self ) } } elsif $pod.?contents { for $pod.contents -> $sub-pod { self.find-references(:pod($sub-pod)) if $sub-pod ~~ Pod::Block; } } } }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: lib/Rakudoc/CMD.rakumod ### ---------------------------------------------------- unit module Rakudoc::CMD; use Rakudoc; our proto MAIN(|) is export { {*} CATCH { when X::Rakudoc { $*ERR.put: $_; if %*ENV<RAKUDOC_TEST> { # Meaningless except to t/01-cmd.t return False; } exit 2; } } # Meaningless except to t/01-cmd.t True; } sub display($rakudoc, *@docs) { my $text = ''; my $fh; my $pager = $*OUT.t && [//] |%*ENV<RAKUDOC_PAGER PAGER>, 'more'; if $pager { # TODO Use Shell::WordSplit or whatever is out there; for now this # makes a simple 'less -Fr' work $pager = run :in, |$pager.comb(/\S+/); $fh = $pager.in; } else { $fh = $*OUT; } for @docs { $fh.print: "\n" if $++; $fh.print: "# {.gist}\n\n"; my $text = $rakudoc.render($_); $fh.put: $text; } if $rakudoc.warnings { $fh.put: "* WARNING\n" ~ $rakudoc.warnings.map({"* $_\n"}).join; $rakudoc.warnings = Empty; } $fh.close; } subset Directories of Str; # Positional handling is buggy, rejects specifying just one time #subset Directory of Positional where { all($_) ~~ Str }; multi MAIN( #| Example: 'Map', 'IO::Path.add', '.add' $query, #| Additional directories to search for documentation Directories :d(:$doc-sources), #| Use only directories in --doc-sources / $RAKUDOC Bool :D(:$no-default-docs), ) { my $rakudoc = Rakudoc.new: :$doc-sources, :$no-default-docs, ; my $request = $rakudoc.request: $query; my @docs = $rakudoc.search: $request or die X::Rakudoc.new: :message("No results for $request"); display $rakudoc, @docs; } multi sub MAIN( #| Index all documents found in doc source directories Bool :b(:$build-index)!, Directories :d(:$doc-sources), Bool :D(:$no-default-docs), ) { my $rakudoc = Rakudoc.new: :$doc-sources, :$no-default-docs, ; $rakudoc.index.build; } multi sub MAIN( Bool :V(:$version)!, ) { put "$*PROGRAM :auth<{Rakudoc.^auth}>:api<{Rakudoc.^api}>:ver<{Rakudoc.^ver}>"; } multi MAIN(Bool :h(:$help)!, |ARGUMENTS) { put $*USAGE; }
### ---------------------------------------------------- ### -- rakudoc ### -- Licenses: Artistic-2.0 ### -- Authors: Joel D. S. <@noisegul>, Tim Siegel <github:softmoth>, Will Coleda ### -- File: lib/Rakudoc/Pod/Cache.rakumod ### ---------------------------------------------------- unit class Rakudoc::Pod::Cache; has %.sources is SetHash; has IO::Path $!cache-path; has $!precomp-repo; has %!errors; has %!ids; submethod BUILD( :$cache-path = 'rakudoc_cache', ) { my $class = ::("CompUnit::PrecompilationStore::FileSystem"); if $class ~~ Failure { $class = ::("CompUnit::PrecompilationStore::File"); } $!cache-path = $cache-path.IO.resolve(:completely); $!precomp-repo = CompUnit::PrecompilationRepository::Default.new( :store($class.new(:prefix($!cache-path))), ); } method !compunit-handle($pod-file-path) { my $t = $pod-file-path.IO.modified; my $id = CompUnit::PrecompilationId.new-from-string($pod-file-path); %!ids{$pod-file-path} = $id; my ($handle, $) = $!precomp-repo.load( $id, :src($pod-file-path), :since($t) ); unless $handle { #note "Caching '$pod-file-path' to '$!cache-path'"; $handle = $!precomp-repo.try-load( CompUnit::PrecompilationDependency::File.new( :src($pod-file-path), :$id, :spec(CompUnit::DependencySpecification.new(:short-name($pod-file-path))), ) ); #note " - Survived with handle {$handle // 'NULL'}"; } ++%!sources{$pod-file-path}; return $handle; } #| pod(Str $pod-file-path) returns the pod tree in the pod file multi method pod(CompUnit::Handle $handle) { use nqp; nqp::atkey($handle.unit, '$=pod') } multi method pod(IO::Path $pod-file-path) { my $handle; # Canonical form for lookup consistency my $src = $pod-file-path.resolve(:completely).absolute; if %!ids{$src}:exists { $handle = $!precomp-repo.try-load( CompUnit::PrecompilationDependency::File.new( :$src, :id(%!ids{$src}) ), ); } else { $handle = self!compunit-handle($src); } self.pod: $handle; } multi method pod(Str $pod-file-path) { self.pod: $pod-file-path.IO; }