home *** CD-ROM | disk | FTP | other *** search
/ PC World 2003 March / PCWorld_2003-03_cd.bin / Software / Topware / activeperl / ActivePerl / Perl / bin / ppm3-bin < prev    next >
Encoding:
Text File  |  2002-12-01  |  141.4 KB  |  4,828 lines

  1. #!perl 
  2.  
  3. require 5.006;    # require 5.6.0
  4. use strict;
  5.  
  6. # A command-line shell implementation. The code which invokes it is at the
  7. # bottom of this file.
  8. package PPMShell;
  9. use base qw(PPM::Term::Shell);
  10.  
  11. use Data::Dumper;
  12. use Text::Autoformat qw(autoformat form);
  13. use Getopt::Long;
  14.  
  15. # These must come _after_ the options parsing.
  16. require PPM::UI;
  17. require PPM::Trace;
  18. PPM::Trace->import(qw(trace));
  19.  
  20. my $NAME    = q{PPM - Programmer's Package Manager};
  21. my $SHORT_NAME    = q{PPM};
  22. my $VERSION    = '3.0.1';
  23.  
  24. sub dictsort(@);
  25.  
  26. #=============================================================================
  27. # Output Methods
  28. #
  29. # PPM behaves differently under different calling circumstances. Here are the
  30. # various classes of messages it prints out:
  31. # 1. error/warning    - an error or "bad thing" has occurred
  32. # 2. informational    - required information like search results
  33. # 3. verbose        - verbose that's only needed in interactive mode
  34. #
  35. # Here are the cases:
  36. # 1. PPM is in interactive mode: everything gets printed.
  37. # 2. PPM is in batch mode: everything minus 'verbose' gets printed.
  38. #=============================================================================
  39. sub error {
  40.     my $o = shift;
  41.     return 1 unless $o->{SHELL}{output}{error};
  42.     CORE::print STDERR @_;
  43. }
  44. sub errorf {
  45.     my $o = shift;
  46.     return 1 unless $o->{SHELL}{output}{error};
  47.     CORE::printf STDERR @_;
  48. }
  49. sub warn { goto &error }
  50. sub warnf { goto &errorf }
  51. sub inform {
  52.     my $o = shift;
  53.     return 1 unless $o->{SHELL}{output}{inform};
  54.     CORE::print @_;
  55. }
  56. sub informf {
  57.     my $o = shift;
  58.     return 1 unless $o->{SHELL}{output}{inform};
  59.     CORE::printf @_;
  60. }
  61. sub verbose {
  62.     my $o = shift;
  63.     return 1 unless $o->{SHELL}{output}{verbose};
  64.     CORE::print @_;
  65. }
  66. sub verbosef {
  67.     my $o = shift;
  68.     return 1 unless $o->{SHELL}{output}{verbose};
  69.     CORE::printf @_;
  70. }
  71. sub assertw {
  72.     my $o = shift;
  73.     my $cond = shift;
  74.     my $msg = shift;
  75.     $o->warn("Warning: $msg\n") unless $cond;
  76.     return $cond;
  77. }
  78. sub assert {
  79.     my $o = shift;
  80.     my $cond = shift;
  81.     my $msg = shift;
  82.     $o->error("Error: $msg\n") unless $cond;
  83.     return $cond;
  84. }
  85.  
  86. sub mode {
  87.     my $o = shift;
  88.     $o->{SHELL}{mode};
  89. }
  90. sub setmode {
  91.     my $o = shift;
  92.     my $newmode = shift || '';
  93.     my $oldmode = $o->{SHELL}{mode};
  94.     if ($newmode eq 'SHELL') {
  95.     $o->{SHELL}{output}{error}   = 1;
  96.     $o->{SHELL}{output}{inform}  = 1;
  97.     $o->{SHELL}{output}{verbose} = 1;
  98.     }
  99.     elsif ($newmode eq 'BATCH') {
  100.     $o->{SHELL}{output}{error}   = 1;
  101.     $o->{SHELL}{output}{inform}  = 1;
  102.     $o->{SHELL}{output}{verbose} = 0;
  103.     }
  104.     elsif ($newmode eq 'SCRIPT') {
  105.     $o->{SHELL}{output}{error}   = 1;
  106.     $o->{SHELL}{output}{inform}  = 1;
  107.     $o->{SHELL}{output}{verbose} = 0;
  108.     }
  109.     elsif ($newmode eq 'SILENT') {
  110.     $o->{SHELL}{output}{error}   = 1;
  111.     $o->{SHELL}{output}{inform}  = 0;
  112.     $o->{SHELL}{output}{verbose} = 0;
  113.     }
  114.     $o->{SHELL}{mode} = $newmode;
  115.     return $oldmode;
  116. }
  117.  
  118. # Older versions of PPM3 had one "Active" repository. This code reads
  119. # $o->conf('repository') if it exists, and moves it into
  120. # $o->conf('active_reps'), which is a list. The old one is deleted -- old PPMs
  121. # will reset it if needed, but it will be ignored if 'active_reps' exists.
  122. sub init_active_reps {
  123.     my $o = shift;
  124.  
  125.     if ($o->conf('repository') and not $o->conf('active_reps')) {
  126.     my @active = $o->conf('repository');
  127.     delete $o->{SHELL}{conf}{DATA}{repository};
  128.     $o->conf('active_reps', \@active);
  129.     }
  130.     elsif (not defined $o->conf('active_reps')) {
  131.     my @active = $o->reps_all; # enable all repositories
  132.     $o->conf('active_reps', \@active);
  133.     }
  134. }
  135.  
  136. sub init {
  137.     my $o = shift;
  138.     $o->cache_clear('query');
  139.     $o->cache_clear('search');
  140.     $o->{API}{case_ignore} = 1;
  141.  
  142.     # Load the configuration;
  143.     $o->{SHELL}{conf} = PPM::Config::load_config_file('cmdline');
  144.     $o->init_active_reps;
  145.  
  146.     # check whether there's a target in the parent's perl that hasn't been
  147.     # installed in the "targets" file:
  148.     my $ppmsitelib = $ENV{PPM3_PERL_SITELIB};
  149.     if ($ppmsitelib and opendir(PPMDIR, "$ppmsitelib/ppm-conf")) {
  150.         my @files = map  { "$ppmsitelib/ppm-conf/$_" }
  151.                 grep { /^ppminst/i && !/(~|\.bak)\z/ } readdir PPMDIR;
  152.     closedir PPMDIR;
  153.     my $found = 0;
  154.     if (@files == 1) {
  155.         my @targets = PPM::UI::target_list()->result_l;
  156.         for my $target (@targets) {
  157.         my $info = PPM::UI::target_raw_info($target);
  158.         next unless $info and $info->is_success;
  159.         ++$found and last
  160.             if path_under($info->result->{path}, $files[0]);
  161.         }
  162.         unless ($found) {
  163.         # We're going to add a new target:
  164.         # 1. if we can find ppm3-bin.cfg, use that
  165.         # 2. if not, guess lots of stuff
  166.         my $ppm3_bin_cfg = "$ENV{PPM3_PERL_PREFIX}/bin/ppm3-bin.cfg";
  167.         my $r = PPM::UI::target_add(undef, From => $ppm3_bin_cfg)
  168.             if -f $ppm3_bin_cfg;
  169.         unless ($r and $r->is_success) {
  170.             PPM::UI::target_add(
  171.             'TEMP',
  172.             type => 'Local',
  173.             path => $files[0],
  174.             );
  175.         }
  176.         }
  177.     }
  178.     }
  179.  
  180.     # set the initial target:
  181.     if (defined $o->{API}{args}{target}) {
  182.     my $t = $o->{API}{args}{target};
  183.     my $prefix = $ENV{PPM3_PERL_PREFIX};
  184.     if ($t ne 'auto') {
  185.         # A full name or number given:
  186.         $o->run('target', 'select', $o->{API}{args}{target});
  187.     }
  188.     elsif ($prefix) {
  189.         # Auto-select target, based on where we came from:
  190.         my @l = $o->conf('target');
  191.         push @l, PPM::UI::target_list()->result_l;
  192.         for my $target (@l) {
  193.         next unless $target;
  194.         my $info = PPM::UI::target_raw_info($target);
  195.         next unless $info and $info->is_success;
  196.         next unless path_under($info->result->{path}, "$prefix/");
  197.         my $mode = $o->setmode('SILENT');
  198.         $o->run('target', 'select', $target);
  199.         $o->setmode($mode);
  200.         last;
  201.         }
  202.     }
  203.     }
  204. }
  205.  
  206. sub preloop {
  207.     my $o = shift;
  208.  
  209.     if ($o->conf('verbose-startup') and $o->mode eq 'SHELL') {
  210.     my $profile_track = $o->conf('profile-track');
  211.     chomp (my $startup = <<END);
  212. $NAME version $VERSION.
  213. Copyright (c) 2001 ActiveState SRL. All Rights Reserved.
  214.  
  215. Entering interactive shell.
  216. END
  217.     my $profile_tracking_warning = $profile_track ? '' : <<'END';
  218.  
  219. Profile tracking is not enabled. If you save and restore profiles manually,
  220. your profile may be out of sync with your computer. See 'help profile' for
  221. more information.
  222. END
  223.     $o->inform($startup);
  224.     $o->inform(<<END);
  225.  Using $o->{API}{readline} as readline library.
  226. $profile_tracking_warning
  227. Type 'help' to get started.
  228.  
  229. END
  230.     }
  231.     else {
  232.     $o->inform("$NAME ($VERSION). Type 'help' to get started.\n");
  233.     }
  234.  
  235.     $o->term->SetHistory(@{$o->conf('history') || []})
  236.     if $o->term->Features->{setHistory};
  237. }
  238.  
  239. sub postloop {
  240.     my $o = shift;
  241.     trace(1, "PPM: exiting...\n");
  242.     if ($o->mode eq 'SHELL' and $o->term->Features->{getHistory}) {
  243.     my @h = $o->term->GetHistory;
  244.     my $max_history = $o->conf('max_history') || 100;
  245.     splice @h, 0, (@h - $max_history)
  246.         if @h > $max_history;
  247.     my $old = $o->setmode('SILENT');
  248.     $o->conf('history', \@h);
  249.     $o->setmode($old);
  250.     }
  251. }
  252.  
  253. #============================================================================
  254. # Cache of search and query results
  255. #============================================================================
  256. sub cache_set_current {
  257.     my $o = shift;
  258.     my $type = shift;
  259.     my $set = shift;
  260.     $set = $o->{SHELL}{CACHE}{$type}{current} unless defined $set;
  261.     $o->{SHELL}{CACHE}{$type}{current} = $set;
  262.     return $o->{SHELL}{CACHE}{$type}{current};
  263. }
  264.  
  265. sub cache_set_index {
  266.     my $o = shift;
  267.     my $type = shift;
  268.     my $index = shift;
  269.     $index = $o->{SHELL}{CACHE}{$type}{index} unless defined $index;
  270.     $o->{SHELL}{CACHE}{$type}{index} = $index;
  271.     return $o->{SHELL}{CACHE}{$type}{index};
  272. }
  273.  
  274. sub cache_set_add {
  275.     my $o = shift;
  276.     my $type = shift;
  277.     my $query = shift;
  278.     my $entries = shift;
  279.     my $sort_field = $o->conf('sort-field');
  280.     my @sorted = $o->sort_pkgs($sort_field, @$entries);
  281.     my $set = {
  282.           query => $query,
  283.           raw => $entries,
  284.           $sort_field => \@sorted,
  285.         };
  286.     push @{$o->{SHELL}{CACHE}{$type}{sets}}, $set;
  287. }
  288.  
  289. sub cache_entry {
  290.     my $o = shift;
  291.     my $type = shift;        # 'query' or 'cache';
  292.     my $index = shift;        # defaults to currently selected index
  293.     my $set = shift;        # defaults to currently selected set
  294.  
  295.     $index = $o->{SHELL}{CACHE}{$type}{index} unless defined $index;
  296.  
  297.     my $src = $o->cache_set($type, $set);
  298.     return undef unless $src and bounded(0, $index, $#$src);
  299.  
  300.     # Make sure we display only valid entries:
  301.     my $tar = $o->conf('target');
  302.     $src->[$index]->make_complete($tar);
  303.     return $src->[$index];
  304. }
  305.  
  306. sub cache_set {
  307.     my $o = shift;
  308.     my $type = shift;        # 'query' or 'cache'
  309.     my $set = shift;        # defaults to currently selected set
  310.     my $entry = shift;        # defaults to 'results';
  311.  
  312.     $entry = $o->conf('sort-field') unless defined $entry;
  313.     return undef unless grep { lc($entry) eq $_ } (sort_fields(), 'query');
  314.  
  315.     $set = $o->{SHELL}{CACHE}{$type}{current} unless defined $set;
  316.     my $src = $o->{SHELL}{CACHE}{$type}{sets};
  317.  
  318.     return undef unless defined $set;
  319.     return undef unless bounded(0, $set, $#$src);
  320.  
  321.     # We've changed sort-field at some point -- make sure the sorted data
  322.     # exists, or else build it:
  323.     unless (defined $src->[$set]{$entry}) {
  324.     my $raw = $src->[$set]{raw};
  325.     my @sorted = $o->sort_pkgs($entry, @$raw);
  326.     $src->[$set]{$entry} = \@sorted;
  327.     }
  328.     
  329.     return wantarray ? @{$src->[$set]{$entry}} : $src->[$set]{$entry};
  330. }
  331.  
  332. sub cache_clear {
  333.     my $o = shift;
  334.     my $type = shift;        # 'query' or 'cache'
  335.     $o->{SHELL}{CACHE}{$type}{sets} = [];
  336.     $o->{SHELL}{CACHE}{$type}{current} = -1;
  337.     $o->{SHELL}{CACHE}{$type}{index} = -1;
  338. }
  339.  
  340. sub cache_sets {
  341.     my $o = shift;
  342.     my $type = shift;
  343.     @{$o->{SHELL}{CACHE}{$type}{sets}};
  344. }
  345.  
  346. # This sub searches for an entry in the cache whose name matches that thing
  347. # passed in. It searches in the current cache first. If the name isn't found,
  348. # it searches in all caches. If the name still isn't found, it returns undef.
  349. sub cache_find {
  350.     my $o = shift;
  351.     my $type = shift;
  352.     my $name = shift;
  353.  
  354.     my $ncaches = $o->cache_sets($type);
  355.     my $current = $o->cache_set_current($type);
  356.  
  357.     # First, search the current set:
  358.     my @pkgs = map { $_ ? $_->name : '' } $o->cache_set($type);
  359.     my $ind  = find_index($name, 0, @pkgs);
  360.     return ($current, $ind) if $ind >= 0;
  361.  
  362.     # Now try to find in all the sets:
  363.     for my $s (0 .. $ncaches - 1) {
  364.     next if $s == $current;
  365.     @pkgs = map { $_ ? $_->name : '' } $o->cache_set($type, $s);
  366.     $ind  = find_index($name, 0, @pkgs);
  367.     return ($s, $ind) if $ind >= 0;
  368.     }
  369.     return (-1, -1);
  370. }
  371.  
  372. # A pretty separator to print between logically separate items:
  373. my $SEP;
  374. BEGIN {
  375.     $SEP = '=' x 20;
  376. }
  377.  
  378. # Useful functions:
  379. sub max (&@) {
  380.     my $code = shift;
  381.     my $max;
  382.     local $_;
  383.     for (@_) {
  384.     my $res = $code->($_);
  385.     $max = $res if not defined $max or $max < $res;
  386.     }
  387.     $max || 0;
  388. }
  389.  
  390. sub min (&@) {
  391.     my $code = shift;
  392.     my $min;
  393.     local $_;
  394.     for (@_) {
  395.     my $res = $code->($_);
  396.     $min = $res if not defined $min or $min > $res;
  397.     }
  398.     $min || 0;
  399. }
  400.  
  401. sub sum (&@) {
  402.     my $code = shift;
  403.     my $sum = 0;
  404.     local $_;
  405.     for (@_) {
  406.     my $res = $code->($_);
  407.     $sum += $res if defined $res;
  408.     }
  409.     $sum || 0;
  410. }
  411.  
  412. #============================================================================
  413. # Repository:
  414. # rep            # displays repositories
  415. # rep add http://...    # adds a new repository
  416. # rep del <\d+>        # deletes the specified repository
  417. # rep [set] 1        # sets the specified repository active
  418. #============================================================================
  419. sub smry_repository { "adds, removes, or sets repositories" }
  420. sub help_repository { <<'END' }
  421. repository -- Repository Control
  422.   Synopsis
  423.      rep                        Displays all repositories
  424.      rep add [name] <location>  Adds a new repository; makes it active
  425.      rep delete <name or num>   Deletes specified repository
  426.      rep describe <name or num> Displays information about the specified
  427.                                 repository
  428.      rep rename <name or num> <name>
  429.                                 Renames the specified repository to
  430.                                 the given name
  431.      rep on <name>              Activates the specified repository
  432.      rep off <name or num>      Removes the repository from the active list
  433.      rep up <name or num>       Moves the specified repository up one
  434.      rep down <name or num>     Moves the specified repository down one
  435.  
  436.   Description
  437.     The *repository* (or *rep*) command controls two lists or repositories:
  438.  
  439.     1   The list of "active" repositories. This is the list of repositories
  440.         used by *search*, *install*, *upgrade*, and *verify*.
  441.  
  442.     2   The list of all known repositories. You can designate a repository
  443.         "inactive", which means PPM will not use it in any commands.
  444.  
  445.     If no arguments are given, the rep command will list the active
  446.     repositories defined in the PPM settings. The order is significant: when
  447.     installing a package, PPM will try the first repository, then the
  448.     second, and so on, until it find the package you asked for. When
  449.     searching, PPM merges the results of all the repositories together, so
  450.     the order is less important (see the *search* command).
  451.  
  452.     For example, when you enter:
  453.  
  454.         rep
  455.  
  456.     PPM3 will return something resembling this:
  457.  
  458.         Repositories:
  459.         [1] ActiveCD
  460.         [2] ActiveState Package Repository
  461.         [ ] An inactive repository
  462.  
  463.     In the example above, entering 'rep off 2' will disable the second
  464.     repository (the ActiveStat Package Repository). To add another
  465.     repository:
  466.  
  467.         rep add [options] <NAME> <LOCATION>
  468.  
  469.     The following options are available for the 'add' command:
  470.  
  471.     *   -username
  472.  
  473.     *   -password
  474.  
  475.     These options allow you to specify a username and password to be used
  476.     when logging into a repository. Currently, these are only used for FTP
  477.     and WWW repositories.
  478.  
  479.     For example:
  480.  
  481.         rep add "EZE" http://ppm.ActiveState.com/PPMPackages/5.8plus
  482.  
  483.     with "EZE" being the name of the repository (for easy reference) and the
  484.     location noted by the http location. If you were to enter the rep
  485.     command again, you would see:
  486.  
  487.         ppm> rep
  488.         Repositories:
  489.         [1] ActiveCD
  490.         [2] ActiveState Package Repository
  491.         [3] EZE
  492.         [ ] An inactive repository
  493.  
  494.     To move the new repository to the top of the Active list, you would
  495.     type:
  496.  
  497.         ppm> rep up EZE
  498.         Repositories:
  499.         [1] ActiveCD
  500.         [2] EZE
  501.         [3] ActiveState Package Repository
  502.         [ ] An inactive repository
  503.         ppm> rep up EZE
  504.         Repositories:
  505.         [1] EZE
  506.         [2] ActiveCD
  507.         [3] ActiveState Package Repository
  508.         [ ] An inactive repository
  509.  
  510.     To disable the ActiveCD repository temporarily, enter the following:
  511.  
  512.         ppm> rep off ActiveCD
  513.         Repositories:
  514.         [1] EZE
  515.         [2] ActiveState Package Repository
  516.         [ ] ActiveCD
  517.         [ ] An inactive repository
  518.  
  519.     To describe a repository, refer to it either by name, or by the number
  520.     displayed next to the repository in the Active Repositories list. You
  521.     must refer to inactive repositories by their full name.
  522.  
  523.         ppm> rep describe 2
  524.         Describing Active Repository 2:
  525.             Name: ActiveState Package Repository
  526.         Location: http://ppm.ActiveState.com/cgibin/PPM/...
  527.             Type: PPMServer 2.00
  528.         ppm> rep describe ActiveCD
  529.         Describing Inactive Repository:
  530.             Name: ActiveCD
  531.         Location: F:\PPMPackages\5.8plus
  532.             Type: Local Directory
  533.  
  534.     To re-activate the ActiveCD repository, use the *rep on* command. You
  535.     must refer to inactive repositories by name, not number.
  536.  
  537.         ppm> rep on ActiveCD
  538.         Active Repositories:
  539.         [1] EZE
  540.         [2] ActiveState Package Repository
  541.         [3] ActiveCD
  542.         [ ] An inactive repository
  543.  
  544.   Repository Types
  545.     PPM3 supports several types of package repositories:
  546.  
  547.     1.  PPM Server 3.0
  548.  
  549.         ActiveState's SOAP-driven package server. Because all searches are
  550.         done server-side, the server can deliver much richer information
  551.         about packages than other repositories.
  552.  
  553.     2.  PPM Server 2.0
  554.  
  555.         The SOAP server designed for PPM version 2. PPM3 ships with the PPM2
  556.         repository as well as the PPM3 repository, so you can use either.
  557.         Simple searches are performed server-side. If your search is too
  558.         complicated for the server, PPM3 will download the package summary
  559.         and search by itself.
  560.  
  561.     3.  Web Repositories
  562.  
  563.         Older versions of PPM used non-SOAP repositories (directories full
  564.         of PPD files accessible using a web browser). Over the history of
  565.         PPM, there have been several different ways of organising the files
  566.         so that PPM can search for packages properly. PPM3 tries to download
  567.         a summary file first -- if that fails, it gets the directory index.
  568.         It parses the summary or the index, and caches it. Searches are done
  569.         from the cache.
  570.  
  571.     4.  FTP Repositories
  572.  
  573.         FTP is another way of exposing a directory full of PPD files. PPM3
  574.         consideres FTP repositories a subset of Web repositories. Treat them
  575.         as identical: PPM3 downloads the summary or the "index" (file
  576.         listing in this case), parses it, and then searches from it.
  577.  
  578.     5.  Local Repositories
  579.  
  580.         To support installing packages from the ActiveCD, a local directory
  581.         can be a repository. PPM3 searches the files in the directory. All
  582.         valid path formats are supported, including UNC paths.
  583. END
  584. sub comp_repository {
  585.     my $o = shift;
  586.     my ($word, $line, $start) = @_;
  587.     my @words = $o->line_parsed($line);
  588.     my $words = scalar @words;
  589.     my @reps = PPM::UI::repository_list()->result_l;
  590.     my $reps = @reps;
  591.     my @compls = qw(add delete describe rename set select);
  592.     push @compls, ($reps ? (1 .. $reps) : ()); 
  593.  
  594.     if ($words == 1 or $words == 2 and $start != length($line)) {
  595.     return $o->completions($word, \@compls);
  596.     }
  597.     if ($words == 2 or $words == 3 and $start != length($line)) {
  598.     return (readline::rl_filename_list($word))
  599.       if $words[1] eq 'add';
  600.     return $o->completions($word, [1 .. $reps])
  601.       if $o->completions($words[1], [qw(delete describe rename set select)]) == 1;
  602.     }
  603.     ();
  604. }
  605. sub reps_all {
  606.     my $o = shift;
  607.     my $l = PPM::UI::repository_list();
  608.     unless ($l->is_success) {
  609.     $o->warn($l->msg);
  610.     return () unless $l->ok;
  611.     }
  612.     $l->result_l;
  613. }
  614. sub reps_on {
  615.     my $o = shift;
  616.     return @{$o->conf('active_reps')};
  617. }
  618. sub reps_off {
  619.     my $o = shift;
  620.     my @reps = $o->reps_all;
  621.     my @reps_on = $o->reps_on;
  622.     my @off;
  623.     for my $r (@reps) {
  624.     push @off, $r unless grep { $_ eq $r } @reps_on;
  625.     }
  626.     @off;
  627. }
  628. sub rep_on {
  629.     my $o = shift;
  630.     my $rep = shift;
  631.     my @reps = ($o->reps_on, $rep);
  632.     my $m = $o->setmode('SILENT');
  633.     $o->conf('active_reps', \@reps);
  634.     $o->setmode($m);
  635. }
  636. sub rep_off {
  637.     my $o = shift;
  638.     my $rep = shift;
  639.     my @reps = grep { $_ ne $rep } $o->reps_on;
  640.     my $m = $o->setmode('SILENT');
  641.     $o->conf('active_reps', \@reps);
  642.     $o->setmode($m);
  643. }
  644. sub rep_ison {
  645.     my $o = shift;
  646.     my $rep = shift;
  647.     scalar grep { $_ eq $rep } $o->reps_on;
  648. }
  649. sub rep_isoff {
  650.     my $o = shift;
  651.     my $rep = shift;
  652.     scalar grep { $_ eq $rep } $o->reps_off;
  653. }
  654. sub rep_exists {
  655.     my $o = shift;
  656.     my $rep = shift;
  657.     scalar grep { $_ eq $rep } $o->reps_all;
  658. }
  659. sub rep_uniq {
  660.     my $o = shift;
  661.     my $rep = shift;
  662.     unless ($o->rep_exists($rep) or $rep =~ /^\d+$/) {
  663.     /\Q$rep\E/i and return $_ for $o->reps_all;
  664.     }
  665.     $rep;
  666. }
  667. sub rep_up {
  668.     my $o = shift;
  669.     my $rep = shift;
  670.     my @reps = $o->reps_on;
  671.     my $ind = find_index($rep, 0, @reps);
  672.     if (bounded(1, $ind, $#reps)) {
  673.     @reps = (
  674.         @reps[0 .. $ind - 2],
  675.         $rep,
  676.         $reps[$ind - 1],
  677.         @reps[$ind + 1 .. $#reps]
  678.     );
  679.     }
  680.     my $m = $o->setmode('SILENT');
  681.     $o->conf('active_reps', \@reps);
  682.     $o->setmode($m);
  683. }
  684. sub rep_down {
  685.     my $o = shift;
  686.     my $rep = shift;
  687.     my @reps = $o->reps_on;
  688.     my $ind = find_index($rep, 0, @reps);
  689.     if (bounded(0, $ind, $#reps - 1)) {
  690.     @reps = (
  691.         @reps[0 .. $ind - 1],
  692.         $reps[$ind + 1],
  693.         $rep,
  694.         @reps[$ind + 2 .. $#reps]
  695.     );
  696.     }
  697.     my $m = $o->setmode('SILENT');
  698.     $o->conf('active_reps', \@reps);
  699.     $o->setmode($m);
  700. }
  701. sub run_repository {
  702.     my $o = shift;
  703.     my @args = @_;
  704.     my (@reps, @reps_off, @reps_on);
  705.     my $refresh = sub {
  706.     @reps = $o->reps_all;
  707.     @reps_off = $o->reps_off;
  708.     @reps_on = $o->reps_on;
  709.     };
  710.     &$refresh;
  711.     trace(1, "PPM: repository @args\n");
  712.  
  713.     if (@args) {
  714.     my ($cmd, @args) = @args;
  715.     #=====================================================================
  716.     # add, delete, describe, rename commands:
  717.     #=====================================================================
  718.     if (matches($cmd, "add")) {
  719.         # Support for usernames and passwords.
  720.         my ($user, $pass);
  721.         {
  722.         local *ARGV;
  723.         @ARGV = @args;
  724.         GetOptions(
  725.             "username=s"    => \$user,
  726.             "password=s"    => \$pass,
  727.         );
  728.         @args = @ARGV;
  729.         }
  730.         $o->warn(<<END) and return unless (@args == 1 or @args == 2);
  731. repository: invalid 'add' command arguments. See 'help repository'.
  732. END
  733.         my $name = $args[0];
  734.         my $url  = $args[1];
  735.         if (@args == 1) {    # rep add http://...
  736.         $url = $name;
  737.         $name = 'Autonamed';
  738.         for (my $i=1; $i<=@reps; $i++) {
  739.             my $tmp = "$name $i";
  740.             $name = $tmp and last
  741.               unless (grep { $tmp eq $_ } @reps);
  742.         }
  743.         }
  744.         my $ok = PPM::UI::repository_add($name, $url, $user, $pass);
  745.         unless ($ok->is_success) {
  746.         $o->warn($ok->msg);
  747.         return unless $ok->ok;
  748.         }
  749.         $o->rep_on($name);
  750.     }
  751.     elsif (matches($cmd, "del|ete")) {
  752.         my $arg = $args[0];
  753.         my $gonner = $arg;
  754.         if ($arg =~ /^\d+$/) {
  755.         return unless $o->assert(
  756.             bounded(1, $arg, scalar @reps_on),
  757.             "no such active repository $arg"
  758.         );
  759.         $gonner = $reps_on[$arg - 1];
  760.         }
  761.         else {
  762.         $gonner = $o->rep_uniq($gonner);
  763.         return unless $o->assert(
  764.             $o->rep_exists($gonner),
  765.             "no such repository '$gonner'"
  766.         );
  767.         }
  768.         my $ok = PPM::UI::repository_del($gonner);
  769.         unless ($ok->is_success) {
  770.         $o->warn($ok->msg);
  771.         return unless $ok->ok;
  772.         }
  773.         $o->rep_off($gonner);
  774.     }
  775.     elsif (matches($cmd, "des|cribe")) {
  776.         my $arg = $args[0] || '1';
  777.         my $rep = $arg;
  778.         if ($arg =~ /^\d+$/) {
  779.         return unless $o->assert(
  780.             bounded(1, $arg, scalar @reps_on),
  781.             "no such active repository $arg"
  782.         );
  783.         $rep = $reps_on[$arg - 1];
  784.         }
  785.         else {
  786.         $rep = $o->rep_uniq($rep);
  787.         return unless $o->assert(
  788.             $o->rep_exists($rep),
  789.             "no such repository '$rep'"
  790.         );
  791.         }
  792.         my $info = PPM::UI::repository_info($rep);
  793.         unless ($info->is_success) {
  794.         $o->warn($info->msg);
  795.         return unless $info->ok;
  796.         }
  797.         my $type = $o->rep_ison($rep) ? "Active" : "Inactive";
  798.         my $num  = (
  799.         $o->rep_ison($rep)
  800.         ? " " . find_index($rep, 1, @reps_on)
  801.         : ""
  802.         );
  803.         my @info = $info->result_l;
  804.         my @keys = qw(Name Location Type);
  805.         push @keys, qw(Username) if @info >= 4;
  806.         push @keys, qw(Password) if @info >= 5;
  807.         $o->inform("Describing $type Repository$num:\n");
  808.         $o->print_pairs(\@keys, \@info);
  809.         return 1;
  810.     }
  811.     elsif (matches($cmd, 'r|ename')) {
  812.         my $arg = $args[0];
  813.         my $name = $args[1];
  814.         my $rep = $arg;
  815.         if ($arg =~ /^\d+$/) {
  816.         return unless $o->assert(
  817.             bounded(1, $arg, scalar @reps_on),
  818.             "no such active repository $arg"
  819.         );
  820.         $rep = $reps_on[$arg - 1];
  821.         }
  822.         else {
  823.         $rep = $o->rep_uniq($rep);
  824.         return unless $o->assert(
  825.             $o->rep_exists($rep),
  826.             "no such repository '$rep'"
  827.         );
  828.         }
  829.         my $ok = PPM::UI::repository_rename($rep, $name);
  830.         unless ($ok->is_success) {
  831.         $o->warn($ok->msg);
  832.         return unless $ok->ok;
  833.         }
  834.         $o->rep_on($name) if $o->rep_ison($rep);
  835.         $o->rep_off($rep);
  836.     }
  837.  
  838.     #=====================================================================
  839.     # On, off, up, and down commands:
  840.     #=====================================================================
  841.     elsif (matches($cmd, 'on')) {
  842.         my $rep = $o->rep_uniq($args[0]);
  843.         return unless $o->assert(
  844.         $o->rep_isoff($rep),
  845.         "no such inactive repository '$rep'"
  846.         );
  847.         $o->rep_on($rep);
  848.         $o->cache_clear('search');
  849.     }
  850.     elsif (matches($cmd, 'of|f')) {
  851.         my $arg = $args[0];
  852.         my $rep = $arg;
  853.         if ($arg =~ /^\d+$/) {
  854.         return unless $o->assert(
  855.             bounded(1, $arg, scalar @reps_on),
  856.             "no such active repository $arg"
  857.         );
  858.         $rep = $reps_on[$arg - 1];
  859.         }
  860.         else {
  861.         $rep = $o->rep_uniq($rep);
  862.         return unless $o->assert(
  863.             $o->rep_exists($rep),
  864.             "no such repository '$rep'"
  865.         );
  866.         }
  867.         $o->rep_off($rep);
  868.         $o->cache_clear('search');
  869.     }
  870.     elsif (matches($cmd, 'up')) {
  871.         my $arg = $args[0];
  872.         my $rep = $arg;
  873.         if ($arg =~ /^\d+$/) {
  874.         return unless $o->assert(
  875.             bounded(1, $arg, scalar @reps_on),
  876.             "no such active repository $arg"
  877.         );
  878.         $rep = $reps_on[$arg - 1];
  879.         }
  880.         else {
  881.         return unless $o->assert(
  882.             $o->rep_exists($rep),
  883.             "no such repository '$rep'"
  884.         );
  885.         }
  886.         $o->rep_up($rep);
  887.     }
  888.     elsif (matches($cmd, 'do|wn')) {
  889.         my $arg = $args[0];
  890.         my $rep = $arg;
  891.         if ($arg =~ /^\d+$/) {
  892.         return unless $o->assert(
  893.             bounded(1, $arg, scalar @reps_on),
  894.             "no such active repository $arg"
  895.         );
  896.         $rep = $reps_on[$arg - 1];
  897.         }
  898.         else {
  899.         return unless $o->assert(
  900.             $o->rep_exists($rep),
  901.             "no such repository '$rep'"
  902.         );
  903.         }
  904.         $o->rep_down($rep);
  905.     }
  906.  
  907.     else {
  908.         $o->warn(<<END) and return;
  909. No such repository command '$cmd'; see 'help repository'.
  910. END
  911.     }
  912.     }
  913.     &$refresh;
  914.     unless(@reps) {
  915.     $o->warn("No repositories. Use 'rep add' to add a repository.\n");
  916.     }
  917.     else {
  918.     my $i = 0;
  919.     my $count = @reps_on;
  920.     my $l = length($count);
  921.     $o->inform("Repositories:\n");
  922.     for my $r (@reps_on) {
  923.         my $n = sprintf("%${l}d", $i + 1);
  924.         $o->inform("[$n] $r\n");
  925.         $i++;
  926.     }
  927.     for my $r ($o->dictsort(@reps_off)) {
  928.         my $s = ' ' x $l;
  929.         $o->inform("[$s] $r\n");
  930.     }
  931.     }
  932.     1;
  933. }
  934.  
  935. #============================================================================
  936. # Search:
  937. # search        # displays previous searches
  938. # search <\d+>        # displays results of previous search
  939. # search <terms>    # executes a new search on the current repository
  940. #============================================================================
  941. sub smry_search { "searches for packages in a repository" }
  942. sub help_search { <<'END' }
  943. search -- Search for Packages
  944.   Synopsis
  945.      search                Displays list of previous searches
  946.      search <number>       Displays results of search <number>
  947.      search <glob pattern> Performs a new search
  948.      search <field>=<glob> Searches for all packages matching the field.
  949.      search *              Displays all packages in the current repository
  950.  
  951.     The available fields are 'ABSTRACT', 'NAME', 'TITLE', 'AUTHOR', and
  952.     'VERSION'. 'NAME' is used when you do not specify a field.
  953.  
  954.   Description
  955.     Use the search command to look through the repository for packages. PPM
  956.     version 3.0 provides powerful search functionality. For example:
  957.  
  958.     1.  Search for 'CGI' anywhere in the name:
  959.  
  960.           search CGI
  961.  
  962.         Example results:
  963.  
  964.           Apache-CGI
  965.           CGI-Application
  966.           CGI-ArgChecker
  967.  
  968.     2.  Search for 'CGI' at the beginning of the name:
  969.  
  970.           search CGI*
  971.  
  972.         Example results:
  973.  
  974.           CGI-ArgChecker
  975.           CGI-Application
  976.  
  977.     3.  Search for all modules authored by someone with 'smith' in their
  978.         name or email:
  979.  
  980.           search AUTHOR=smith 
  981.  
  982.         Example results:
  983.  
  984.           Apache-ProxyPass
  985.           Business-ISBN
  986.  
  987.     4.  Search for 'compress' anywhere in the abstract:
  988.  
  989.           search ABSTRACT=compress
  990.  
  991.         Example results:
  992.  
  993.           Apache-GzipChain
  994.           IO-Zlib
  995.  
  996.     5.  Search for 'CGI' in the name, or 'web' in the abstract:
  997.  
  998.           search CGI or ABSTRACT=web
  999.  
  1000.         Example results:
  1001.  
  1002.           CGI-XMLForm
  1003.           HTML-Clean
  1004.  
  1005.     6.  Search for 'XML' in the name and either 'parser' in the name or
  1006.         'pars' in the abstract, but not with 'XPath' in the name:
  1007.  
  1008.           search XML and (parser or ABSTRACT=pars) and not XPath
  1009.  
  1010.         Example results:
  1011.  
  1012.           XML-Node
  1013.           XML-Parser-EasyTree
  1014.  
  1015.     7.  PPM Server 3.0 repositories only: search by module name, even if
  1016.         unrelated to the containing package:
  1017.  
  1018.           search Data::Grove
  1019.                                 
  1020.         Example results:
  1021.  
  1022.           libxml-perl
  1023.  
  1024.     8.  Browse all packages in the repository:
  1025.  
  1026.           search *
  1027.  
  1028.         Example results:
  1029.  
  1030.           Affix-Infix2Postfix
  1031.           AI-Fuzzy
  1032.           [many more...]
  1033.  
  1034.     Recall previous searches using the 'search <number>' command. PPM3
  1035.     stores searches for each session until you exit PPM.
  1036.  
  1037.     Some package names or versions are too long to be displayed in the
  1038.     search results. If a name is too long, you will see a '~' (tilde) as the
  1039.     last visible character in the column. You can use *describe* to view
  1040.     detailed information about such packages.
  1041.  
  1042.   Search Results
  1043.     When you type a command like "search XML", PPM searches in each of the
  1044.     Active Repositories (see the *repository* command) for your package. The
  1045.     results are merged into one list, and duplicates (packages found in more
  1046.     than one repository) are hidden.
  1047.  
  1048.     You can control what fields PPM shows for each package. The fields each
  1049.     have a built-in weight, which is used to calculate how wide to make each
  1050.     field based on the width of your screen. Information that doesn't fit
  1051.     into a field is truncated, and a tilde ("~") character is displayed in
  1052.     the last column of the field.
  1053.  
  1054.     Let's get down to an example:
  1055.  
  1056.         ppm> search XML
  1057.         Searching in Active Repositories
  1058.             1. CGI-XMLForm           [0.10] Extension to CGI.pm which
  1059.             2. Data-DumpXML          [1.01] Dump arbitrary data structures
  1060.             3. DBIx-XML_RDB          [0.05] Perl extension for creating XML
  1061.             4. DBIx-XMLMessage       [0.03] XML Message exchange between DBI
  1062.             5. GoXML-XQI            [1.1.4] Perl extension for the XML Query
  1063.             6. Language-DATR-DATR2~ [0.901] manipulate DATR .dtr, XML, HTML,
  1064.             7. libxml-perl           [0.07] support for deeply nested
  1065.             8. Mail-FilterXML         [0.1] Undetermined
  1066.             9. Mail-XML              [0.03] Adds a toXML() method to
  1067.            10. Pod-XML               [0.93] Module to convert POD to XML
  1068.  
  1069.     As you can see, the three fields being displayed are:
  1070.  
  1071.     1   NAME
  1072.  
  1073.         The package name
  1074.  
  1075.     2   VERSION
  1076.  
  1077.         The package version
  1078.  
  1079.     3   ABSTRACT
  1080.  
  1081.         The package abstract
  1082.  
  1083.     You can customize the view somewhat. If you want to view the authors,
  1084.     but not the abstract, you can run the same *search* command after using
  1085.     *set* to change the fields:
  1086.  
  1087.         ppm> set fields="NAME VERSION AUTHOR"
  1088.         Setting 'fields' set to 'name version author'.
  1089.         ppm> search XML
  1090.         Using cached search result set 1.
  1091.             1. CGI-XMLForm         [0.10] Matt Sergeant (matt@sergeant.org)
  1092.             2. Data-DumpXML        [1.01] Gisle Aas (gisle@aas.no)
  1093.             3. DBIx-XML_RDB        [0.05] Matt Sergeant (matt@sergeant.org)
  1094.             4. DBIx-XMLMessage     [0.03] Andrei Nossov (andrein@andrein.com)
  1095.             5. GoXML-XQI          [1.1.4] Matthew MacKenzie (matt@goxml.com)
  1096.             6. Language-DATR-DAT~ [0.901] Lee Goddard (lgoddard@cpan.org)
  1097.             7. libxml-perl         [0.07] Ken MacLeod (ken@bitsko.slc.ut.us)
  1098.             8. Mail-FilterXML       [0.1] Matthew MacKenzie (matt@goxml.com)
  1099.             9. Mail-XML            [0.03] Matthew MacKenzie (matt@goxml.com)
  1100.            10. Pod-XML             [0.93] Matt Sergeant (matt@sergeant.org)
  1101.  
  1102.     You can change the order in which the results are sorted, and what
  1103.     columns are displayed. The settings *fields* and *sort-field* changes
  1104.     this. You can sort by any valid field name (even fields which are not
  1105.     displayed). See the *settings* command for the valid field names.
  1106.  
  1107.     PPM always hides "duplicate" results. It decides whether a result is
  1108.     duplicated based on the fields being displayed. If the same package is
  1109.     found in more than one repository, but you don't have the REPOSITORY
  1110.     field showing, PPM will only list the package once.
  1111. END
  1112. sub comp_search {()}
  1113. sub run_search {
  1114.     my $o = shift;
  1115.     my @args = @_;
  1116.     my $query = $o->raw_args || join ' ', @args;
  1117.     trace(1, "PPM: search @args\n\tquery='$query'\n");
  1118.     return unless $o->assert(
  1119.     scalar $o->reps_on,
  1120.     "you must activate a repository before searching."
  1121.     );
  1122.  
  1123.     # No args: show cached result sets
  1124.     unless (@args) {
  1125.     my @search_results = $o->cache_sets('search');
  1126.     my $search_result_current = $o->cache_set_current('search');
  1127.     if (@search_results) {
  1128.         $o->inform("Search Result Sets:\n");
  1129.         my $i = 0;
  1130.         for (@search_results) {
  1131.         $o->informf("%s%2d",
  1132.                $search_result_current == $i ? "*" : " ",
  1133.                $i + 1);
  1134.         $o->inform(". $_->{query}\n");
  1135.         $i++;
  1136.         }
  1137.     }
  1138.     else {
  1139.         $o->warn("No search result sets -- provide a search term.\n");
  1140.         return;
  1141.     }
  1142.     }
  1143.  
  1144.     # Args:
  1145.     else {
  1146.     # Show specified result set
  1147.     if ($query =~ /^\d+/) {
  1148.         my $set = int($query);
  1149.         my $s = $o->cache_set('search', $set - 1);
  1150.         unless ($set > 0 and defined $s) {
  1151.         $o->warn("No such search result set '$set'.\n");
  1152.         return;
  1153.         }
  1154.  
  1155.         $query = $o->cache_set('search', $set-1, 'query');
  1156.         $o->inform("Search Results Set $set ($query):\n");
  1157.         $o->print_formatted($s, $o->cache_set_index('search'));
  1158.         $o->cache_set_current('search', $set-1);
  1159.         $o->cache_set_index('search', -1);
  1160.     }
  1161.        
  1162.     # Query is the same as a previous query on the same repository: 
  1163.     # Use cached results and set them as default
  1164.     elsif(grep { $_->{query} eq $query } $o->cache_sets('search')) {
  1165.         my @entries = $o->cache_sets('search');
  1166.         for (my $i=0; $i<@entries; $i++) {
  1167.         if ($o->cache_set('search', $i, 'query') eq $query) {
  1168.             $o->inform("Using cached search result set ", $i+1, ".\n");
  1169.             $o->cache_set_current('search', $i);
  1170.             my $set = $o->cache_set('search');
  1171.             $o->print_formatted($set);
  1172.         }
  1173.         }
  1174.     }
  1175.  
  1176.     # Perform a new search
  1177.     else {
  1178.         my @rlist = $o->reps_on;
  1179.         my $targ = $o->conf('target');
  1180.         my $case = not $o->conf('case-sensitivity');
  1181.  
  1182.         $o->inform("Searching in Active Repositories\n");
  1183.         my $ok = PPM::UI::search(\@rlist, $targ, $query, $case);
  1184.         unless ($ok->is_success) {
  1185.         $o->warn($ok->msg);
  1186.         return unless $ok->ok;
  1187.         }
  1188.         my @matches = $ok->result_l;
  1189.         unless (@matches) {
  1190.         $o->warn("No matches for '$query'; see 'help search'.\n");
  1191.         return 1;
  1192.         }
  1193.         $o->cache_set_index('search', -1);
  1194.         $o->cache_set_add('search', $query, \@matches);
  1195.         $o->cache_set_current('search', scalar($o->cache_sets('search')) - 1);
  1196.         my @set = $o->cache_set('search');
  1197.         $o->print_formatted(\@set);
  1198.     }
  1199.     }
  1200.     1;
  1201. }
  1202. sub alias_search { qw(s) }
  1203.  
  1204. #============================================================================
  1205. # tree
  1206. # tree        # shows the dependency tree for the default/current pkg
  1207. # tree <\d+>    # shows dep tree for numbered pkg in current search set
  1208. # tree <pkg>    # shows dep tree for given package
  1209. # tree <url>    # shows dep tree for package located at <url>
  1210. # tree <glob>    # searches for matches
  1211. #============================================================================
  1212. sub smry_tree { "shows package dependency tree" }
  1213. sub help_tree { <<'END' }
  1214. tree -- Show Dependency Tree for Packages
  1215.   Synopsis
  1216.      tree                Displays the dependency-tree of the current
  1217.                          or default package
  1218.      tree <number>       Displays the dependency-tree of the given <number>
  1219.      tree <range>        Displays a <range> of dependency-trees
  1220.      tree <package name> Displays the dependency-tree of the named package
  1221.      tree <url>          Displays the dependency-tree for the
  1222.                          package at <url>
  1223.      tree <glob pattern> Performs a new search using <glob pattern>
  1224.  
  1225.   Description
  1226.     The tree command is used to show the "dependency tree" of a given
  1227.     package (additional packages that are required by the current package).
  1228.     For example:
  1229.  
  1230.         tree SOAP-lite
  1231.  
  1232.     returns:
  1233.  
  1234.         ====================
  1235.         SOAP-Lite 0.51
  1236.         |__MIME-tools 5.316
  1237.         |   |__MailTools 1.15
  1238.         |   \__IO-stringy 1.216
  1239.         |
  1240.         \__MIME-Lite 2.105
  1241.         ====================
  1242.  
  1243.     SOAP-Lite requires four other packages.
  1244.  
  1245.     When tree is called without a <name> or <number> switch, the command
  1246.     will return the dependency tree of the first package in the default
  1247.     search result. If there is no default search, you will be requested to
  1248.     use search to find a package.
  1249. END
  1250. sub comp_tree { goto &comp_describe }
  1251. sub run_tree {
  1252.     my $o = shift;
  1253.     my @args = @_;
  1254.     trace(1, "PPM: tree @args\n");
  1255.  
  1256.     # Check for anything that looks like a query. If it does, just
  1257.     # send it to search() instead.
  1258.     my $query = $o->raw_args || join ' ', @args;
  1259.     $query ||= '';
  1260.     if ($query and not PPM::UI::is_pkg($args[0]) and not parse_range($query)) {
  1261.     $o->inform("Wildcards detected; using 'search' instead...\n");
  1262.     return $o->run('search', @_);
  1263.     }
  1264.  
  1265.     # No Args: describes current index of current result set, or 1.
  1266.     unless (@args) {
  1267.     my @search_results = $o->cache_sets('search');
  1268.     my $search_result_current = $o->cache_set_current('search');
  1269.     unless (@search_results and
  1270.         bounded(0, $search_result_current, $#search_results)) {
  1271.         $o->warn("No search results to show dependency tree for -- " . 
  1272.           "use 'search' to find a package.\n");
  1273.         return;
  1274.     }
  1275.     else {
  1276.         my @res = $o->cache_set('search');
  1277.         my $npkgs = @res;
  1278.         $o->inform("$SEP\n");
  1279.         if ($o->cache_entry('search')) {
  1280.         my $n = $o->cache_set_index('search') + 1;
  1281.         $o->inform("Package $n:\n");
  1282.         $o->tree_pkg($o->cache_entry('search'));
  1283.         }
  1284.         elsif (defined $o->cache_entry('search', 0)) {
  1285.         $o->inform("Package 1:\n");
  1286.         $o->tree_pkg($o->cache_entry('search', 0));
  1287.         $o->cache_set_index('search', 0);
  1288.         }
  1289.         else {
  1290.         $o->inform("Search Results are empty -- use 'search' again.\n");
  1291.         }
  1292.         $o->inform("$SEP\n");
  1293.     }
  1294.     }
  1295.  
  1296.     # Args provided
  1297.     else {
  1298.  
  1299.     # Describe a particular number:
  1300.     if (my @r = parse_range(@args)) {
  1301.         my @search_results = $o->cache_sets('search');
  1302.         my $search_result_current = $o->cache_set_current('search');
  1303.         unless (bounded(0, $search_result_current, $#search_results)) {
  1304.         $o->inform("No search results to show dependency tree for -- " . 
  1305.           "use 'search' to find a package.\n");
  1306.         return;
  1307.         }
  1308.         else {
  1309.         for my $n (@r) {
  1310.             my $sr = $o->cache_set('search');
  1311.             $o->inform("$SEP\n");
  1312.             if (bounded(1, $n, scalar @$sr)) {
  1313.             $o->inform("Package $n:\n");
  1314.             $o->tree_pkg($o->cache_entry('search', $n-1));
  1315.             }
  1316.             else {
  1317.             $o->inform("No such package $n in result set.\n");
  1318.             }
  1319.             $o->cache_set_index('search', $n - 1);
  1320.         }
  1321.         $o->inform("$SEP\n");
  1322.         }
  1323.     }
  1324.  
  1325.     # Describe a particular package
  1326.     else {
  1327.         return unless $o->assert(
  1328.         scalar $o->reps_on,
  1329.         "No repositories -- use 'rep add' to add a repository.\n"
  1330.         );
  1331.         my $pkg =
  1332.           PPM::UI::describe([$o->reps_on], $o->conf('target'), $args[0]);
  1333.         unless ($pkg->is_success) {
  1334.         $o->warn($pkg->msg);
  1335.         return unless $pkg->ok;
  1336.         }
  1337.         if ($pkg->ok) {
  1338.         $o->inform("$SEP\n");
  1339.         $o->tree_pkg($pkg->result);
  1340.         $o->inform("$SEP\n");
  1341.         }
  1342.     }
  1343.     }
  1344.     1;
  1345. }
  1346.  
  1347. #============================================================================
  1348. # Describe:
  1349. # des        # describes default or current package
  1350. # des <\d+>    # describes numbered package in the current search set
  1351. # des <pkg>    # describes the named package (bypasses cached results)
  1352. # des <url>    # describes the package located at <url>
  1353. #============================================================================
  1354. sub smry_describe { "describes packages in detail" }
  1355. sub help_describe { <<'END' }
  1356. describe -- Describe Packages
  1357.   Synopsis
  1358.      des                Describes default/current package
  1359.      des <number>       Describes package <number> in the
  1360.                         current search set
  1361.      des <range>        Describes packages in the given 
  1362.                         <range> from the current search
  1363.      des <package name> Describes named package
  1364.      des <url>          Describes package located at <url>
  1365.      des <glob pattern> Performes a new search using <glob pattern>
  1366.  
  1367.   Description
  1368.     The describe command returns information about a package, including the
  1369.     name of the package, the author's name and a brief description (called
  1370.     an "Abstract") about the package. For example:
  1371.  
  1372.         describe libnet
  1373.  
  1374.     returns:
  1375.  
  1376.         ===============================
  1377.         Package 1
  1378.         Name: libnet
  1379.         Version: 1.07.03
  1380.         Author: Graham Barr
  1381.         Abstract: Collection of Network protocol modules
  1382.         Implementations:
  1383.                 1.sun4-solaris-thread-multi
  1384.                 2.i686-linux-thread-multi
  1385.                 3.MSWIn32-x86-multi-thread
  1386.         ===============================
  1387.  
  1388.     There are two modifiers to the describe command:
  1389.  
  1390.     -ppd
  1391.         Displays the raw PPD of the package.
  1392.  
  1393.     -dump
  1394.         The same as -ppd.
  1395.  
  1396.     When the describe command is called without arguments, it returns
  1397.     information about the first package in the current search. If there is
  1398.     no default search set, you will be prompted to use the search command to
  1399.     find a package.
  1400.  
  1401.     If describe is called with a numeric argument, that number is set as the
  1402.     default package and the information about that package is returned. If
  1403.     the number given doesn't exist, you will be prompted to use search to
  1404.     find a package. Also, you can use describe to get descriptions of
  1405.     several packages. For example:
  1406.  
  1407.         describe 4-7
  1408.  
  1409.     will return descriptions of packages 4 through 7 in the current search
  1410.     request. You can also enter:
  1411.  
  1412.         describe 3-4,10
  1413.  
  1414.     to get information on packages 3, 4 and 10.
  1415.  
  1416.     If you specify a URL as the argument to describe, PPM will describe the
  1417.     package located at the URL. The URL must point to a PPD file. The URL
  1418.     can also point to a PPD file on your computer.
  1419.  
  1420.     When the describe command is given a name with a wildcard (such as "*"
  1421.     or "?") it executes the search command with the given argument. For
  1422.     example, describe Tk* will return the name(s) of any packages that match
  1423.     the search parameters.
  1424.  
  1425.   See Also
  1426.     properties
  1427. END
  1428. sub comp_describe {
  1429.     my $o = shift;
  1430.     my ($word, $line, $start) = @_;
  1431.  
  1432.     # If no search results
  1433.     my $n_results = $o->cache_sets('search');
  1434.     my $n_current = $o->cache_set_current('search');
  1435.     return ()
  1436.       unless ($n_results and bounded(0, $n_current, $n_results - 1));
  1437.     my @words = $o->line_parsed($line);
  1438.  
  1439.     # If the previous word isn't a number or the command, stop.
  1440.     return ()
  1441.       if ($#words > 0 and
  1442.       $words[$#words] !~ /^\d+/ and
  1443.       $start == length($line) or 
  1444.       $#words > 1);
  1445.  
  1446.     # This is the most optimistic list:
  1447.     my @results = $o->cache_set('search');
  1448.     my $npkgs = @results;
  1449.     my @compls = (1 .. $npkgs);
  1450.  
  1451.     # If the previous word is a number, return only other numbers:
  1452.     return $o->completions($word, \@compls)
  1453.       if $words[$#words] =~ /^\d+/;
  1454.  
  1455.     # Either a number or the names of the packages
  1456.     push @compls, map { $_->name } @results;
  1457.     return $o->completions($word, \@compls);
  1458. }
  1459. sub run_describe {
  1460.     my $o = shift;
  1461.     my @args = @_;
  1462.     
  1463.     # Check for options:
  1464.     my $ppd;
  1465.     {
  1466.     local @ARGV = @args;
  1467.     GetOptions(ppd => \$ppd, dump => \$ppd);
  1468.     @args = @ARGV;
  1469.     }
  1470.  
  1471.     trace(1, "PPM: describe @args\n");
  1472.  
  1473.     # Check for anything that looks like a query. If it does, just
  1474.     # send it to search() instead.
  1475.     my $query = $o->raw_args || join ' ', @args;
  1476.     if ($query and not PPM::UI::is_pkg($args[0]) and not parse_range($query)) {
  1477.     $o->inform("Wildcards detected; using 'search' instead...\n");
  1478.     return $o->run('search', @_);
  1479.     }
  1480.  
  1481.     my $dumper = sub {
  1482.     my $o = shift;
  1483.     my $pkg_obj = shift;
  1484.     my $ppd = $pkg_obj->getppd($o->conf('target'))->result;
  1485.     $o->page($ppd);
  1486.     };
  1487.     my $displayer = $ppd ? $dumper : \&describe_pkg;
  1488.  
  1489.     # No Args: describes current index of current result set, or 1.
  1490.     unless (@args) {
  1491.     my @search_results = $o->cache_sets('search');
  1492.     my $search_result_current = $o->cache_set_current('search');
  1493.     unless (@search_results and
  1494.         bounded(0, $search_result_current, $#search_results)) {
  1495.         $o->warn("No search results to describe -- " . 
  1496.           "use 'search' to find a package.\n");
  1497.         return;
  1498.     }
  1499.     else {
  1500.         my @res = $o->cache_set('search');
  1501.         my $npkgs = @res;
  1502.         $o->inform("$SEP\n");
  1503.         if ($o->cache_entry('search')) {
  1504.         my $n = $o->cache_set_index('search') + 1;
  1505.         $o->inform("Package $n:\n");
  1506.         $o->$displayer($o->cache_entry('search'));
  1507.         }
  1508.         elsif (defined $o->cache_entry('search', 0)) {
  1509.         $o->inform("Package 1:\n");
  1510.         $o->$displayer($o->cache_entry('search', 0));
  1511.         $o->cache_set_index('search', 0);
  1512.         }
  1513.         else {
  1514.         $o->warn("Search Results are empty -- use 'search' again.\n");
  1515.         }
  1516.         $o->inform("$SEP\n");
  1517.     }
  1518.     }
  1519.  
  1520.     # Args provided
  1521.     else {
  1522.  
  1523.     # Describe a particular number:
  1524.     if (my @r = parse_range(@args)) {
  1525.         my @search_results = $o->cache_sets('search');
  1526.         my $search_result_current = $o->cache_set_current('search');
  1527.         unless (bounded(0, $search_result_current, $#search_results)) {
  1528.         $o->warn("No search results to describe -- " . 
  1529.           "use 'search' to find a package.\n");
  1530.         return;
  1531.         }
  1532.         else {
  1533.         for my $n (@r) {
  1534.             my $sr = $o->cache_set('search');
  1535.             $o->inform("$SEP\n");
  1536.             if (bounded(1, $n, scalar @$sr)) {
  1537.             $o->inform("Package $n:\n");
  1538.             $o->$displayer($o->cache_entry('search', $n-1));
  1539.             }
  1540.             else {
  1541.             $o->inform("No such package $n in result set.\n");
  1542.             }
  1543.             $o->cache_set_index('search', $n - 1);
  1544.         }
  1545.         $o->inform("$SEP\n");
  1546.         }
  1547.     }
  1548.  
  1549.     # Describe a particular package
  1550.     else {
  1551.         return unless $o->assert(
  1552.         scalar $o->reps_on,
  1553.         "No repositories -- use 'rep add' to add a repository.\n"
  1554.         );
  1555.         my ($set, $index) = $o->cache_find('search', $args[0]);
  1556.         my ($ok, $pkg);
  1557.         if ($index >= 0) {
  1558.         $o->cache_set_current('search', $set);
  1559.         $o->cache_set_index('search', $index);
  1560.         $pkg = $o->cache_entry('search');
  1561.         }
  1562.         else {
  1563.         $ok = PPM::UI::describe([$o->reps_on],
  1564.                     $o->conf('target'), $args[0]);
  1565.         unless ($ok->is_success) {
  1566.             $o->inform($ok->msg);
  1567.             return unless $ok->ok;
  1568.         }
  1569.         $pkg = $ok->result;
  1570.         $o->cache_set_add('search', $args[0], [$pkg]);
  1571.         my $last = $o->cache_sets('search') - 1;
  1572.         $o->cache_set_current('search', $last);
  1573.         $o->cache_set_index('search', 0);
  1574.         }
  1575.         $o->inform("$SEP\n");
  1576.         $o->$displayer($pkg);
  1577.         $o->inform("$SEP\n");
  1578.     }
  1579.     }
  1580.     1;
  1581. }
  1582.  
  1583. #============================================================================
  1584. # Install:
  1585. # i        # installs default or current package
  1586. # i <\d+>    # installs numbered package in current search set
  1587. # i <pkg>    # installs named package
  1588. # i <url>    # installs the package at <url>
  1589. #============================================================================
  1590. sub smry_install { "installs packages" }
  1591. sub help_install { <<'END' }
  1592. install -- Install Packages
  1593.   Synopsis
  1594.      install           Installs default package
  1595.      install <number>  Installs packages by a specific <number>
  1596.      install <range>   Installs packages in the given numeric <range>
  1597.      install <name>    Installs named package
  1598.      install <url>     Installs the package located at <url>
  1599.  
  1600.   Description
  1601.     The install command is used to install packages from the repository.
  1602.     Install packages by name or number (the number is given by the
  1603.     repository or search request), or set a default package using the
  1604.     describe command. You can specify a full URL to a PPD file; the URL may
  1605.     point to a PPD file on your computer.
  1606.  
  1607.     If you have profile tracking enabled, (see 'help profile') the current
  1608.     profile will be updated to include the newly installed package(s).
  1609.  
  1610.     The following modifiers can be used with the install command:
  1611.  
  1612.     *   -force
  1613.  
  1614.     *   -noforce
  1615.  
  1616.     *   -follow
  1617.  
  1618.     *   -nofollow
  1619.  
  1620.     The force and follow switches determine how packages are installed:
  1621.  
  1622.      FORCE       FOLLOW          RESULT
  1623.      false       false           Checks to see if the package is installed and
  1624.                                  if it is, installation stops. If there are any
  1625.                                  missing prerequisites, the installation will
  1626.                                  fail.
  1627.  
  1628.      false       true            Checks to see if the package is installed and
  1629.                                  if it is, installation stops. If there are any
  1630.                                  missing prerequisites, they are automatically
  1631.                                  installed. NOTE: this is the default setting
  1632.                                  when PPM is first installed.
  1633.  
  1634.      true        false           If the package is installed, PPM will
  1635.                                  reinstall the package. If there are any
  1636.                                  missing prerequisites, the installation will
  1637.                                  fail.
  1638.  
  1639.      true        true            If the package is installed, PPM will
  1640.                                  reinstall the package. All prerequisites are
  1641.                                  installed, missing or not.
  1642.     
  1643.     If you do not specify any options, install uses the default settings.
  1644.     Set or view the current defaults using the 'settings' command.
  1645.  
  1646.     For example:
  1647.  
  1648.         install foo
  1649.  
  1650.     will install the package named "foo", using the default settings.
  1651.     Over-ride the defaults using the install modifiers described above.
  1652.  
  1653.     For example:
  1654.  
  1655.         install foo -force
  1656.  
  1657.     will install the "foo" package, even if it has already been installed.
  1658.     If both -force and -follow are set to "true", all the prerequisites for
  1659.     any package you install will also be installed. For example, the
  1660.     installation of a tk-related package, like "tk-ach" which is 8.4 kB will
  1661.     be preceded by the installation of Tk, which is 1.7 MB.
  1662.  
  1663.     You can also install by package number. Package numbers are based on the
  1664.     current repository or current search request. For example:
  1665.  
  1666.         install 6
  1667.  
  1668.     installs package number 6. You can install more than one package at one
  1669.     time:
  1670.  
  1671.         install 3-5
  1672.  
  1673.     installs packages 3, 4 and 5. You can also type install 3-6,8 to install
  1674.     packages 3,4,5,6 and 8.
  1675.  
  1676.   See Also
  1677.     profile
  1678. END
  1679. sub comp_install { goto &comp_describe }
  1680. sub run_install {
  1681.     my $o = shift;
  1682.     my @args = @_;
  1683.     trace(1, "PPM: install @args\n");
  1684.  
  1685.     # Get the install options
  1686.     my %opts = (
  1687.     force  => $o->conf('force-install'),
  1688.     follow => $o->conf('follow-install'),
  1689.     dryrun => 0,
  1690.     );
  1691.     {
  1692.     local @ARGV = @args;
  1693.     GetOptions('force!'  => \$opts{force},
  1694.            'follow!' => \$opts{follow},
  1695.            'dryrun'  => \$opts{dryrun},
  1696.           );
  1697.     @args = @ARGV;
  1698.     }
  1699.  
  1700.     # No Args -- installs default package
  1701.     unless (@args) {
  1702.     my @search_results = $o->cache_sets('search');
  1703.     my $search_result_current = $o->cache_set_current('search');
  1704.     unless (@search_results and
  1705.         bounded(0, $search_result_current, $#search_results)) {
  1706.         $o->warn("No search results to install -- " . 
  1707.           "use 'search' to find a package.\n");
  1708.         return;
  1709.     }
  1710.     else {
  1711.         my @results = $o->cache_set('search');
  1712.         my $npkgs = @results;
  1713.         my $pkg;
  1714.         if ($o->cache_entry('search')) {
  1715.         my $n = $o->cache_set_index('search') + 1;
  1716.         $o->inform("Package $n:\n");
  1717.         $pkg = $o->cache_entry('search');
  1718.         }
  1719.         else {
  1720.         $o->inform("Package 1:\n");
  1721.         $pkg = $o->cache_entry('search', 0);
  1722.         }
  1723.         return $o->install_pkg($pkg, \%opts);
  1724.     }
  1725.     }
  1726.  
  1727.     # Args provided
  1728.     else {
  1729.  
  1730.     # Install a particular number:
  1731.     if (my @r = parse_range(@args)) {
  1732.         my @search_results = $o->cache_sets('search');
  1733.         my $search_result_current = $o->cache_set_current('search');
  1734.         unless (@search_results and
  1735.             bounded(0, $search_result_current, $#search_results)) {
  1736.         $o->warn("No search results to install -- " . 
  1737.           "use 'search' to find a package.\n");
  1738.         return;
  1739.         }
  1740.         else {
  1741.         my $ok = 0;
  1742.         for my $n (@r) {
  1743.             my $sr = $o->cache_set('search');
  1744.             if (bounded(1, $n, scalar @$sr)) {
  1745.             $o->inform("Package $n:\n");
  1746.             my $pkg = $sr->[$n-1];
  1747.             $ok++ if $o->install_pkg($pkg, \%opts);
  1748.             }
  1749.             else {
  1750.             $o->inform("No such package $n in result set.\n");
  1751.             }
  1752.         }
  1753.         return unless $ok;
  1754.         }
  1755.     }
  1756.  
  1757.     # Install a particular package
  1758.     else {
  1759.         if ($o->reps_on) {
  1760.         return $o->install_pkg($args[0], \%opts);
  1761.         }
  1762.         elsif ($o->reps_all) {
  1763.         $o->warn("Can't install: no repositories are active.\n");
  1764.         }
  1765.         else {
  1766.         $o->warn("Can't install: no repositories defined.\n");
  1767.         }
  1768.         return;
  1769.     }
  1770.     }
  1771.     1;
  1772. }
  1773.  
  1774. #============================================================================
  1775. # Target:
  1776. # t        # displays a list of backend targets
  1777. # t [set] <\d+>    # sets numbered target as default backend target
  1778. # t des [<\d+>]    # describes the given (or default) target
  1779. #============================================================================
  1780. sub smry_targets { "views or sets target installer backends" }
  1781. sub help_targets { <<'END' }
  1782. targets -- View Target Installer Backends
  1783.   Synopsis
  1784.      target                      Displays a list of backend targets
  1785.      target <number>             Sets <number> as default backend target
  1786.      target [select] <name or num>
  1787.                                  Sets <name or num> as default backend target
  1788.      target describe [name or num]
  1789.                                  Describes the given (or default) target
  1790.      target set <key> <val>      Sets the target's <key> to <val> 
  1791.      target rename <name or num> <name>
  1792.                                  Renames the given target to <name>
  1793.  
  1794.   Description
  1795.     The target is the destination location of the install routine, such as
  1796.     the directory where the packages are installed when they're downloaded
  1797.     from the repository. For example:
  1798.  
  1799.         target
  1800.  
  1801.     returns:
  1802.  
  1803.         Targets:
  1804.           1. ActivePerl 618
  1805.         * 2. ActivePerl 629
  1806.  
  1807.     This shows that there are two available targets, and that the second
  1808.     target (ActivePerl 629) is currently the default (as shown by the
  1809.     asterisk). Using multiple targets, you can manage multiple installations
  1810.     of Perl from a single command-line.
  1811. END
  1812. sub comp_targets {
  1813.     my $o = shift;
  1814.     my ($word, $line, $start) = @_;
  1815.     my @words = $o->line_parsed($line);
  1816.     my $words = scalar @words;
  1817.     my @compls;
  1818.     my @targs = PPM::UI::target_list()->result_l;
  1819.  
  1820.     # only return 'set' and 'describe' when we're completing the second word
  1821.     if ($words == 1 or $words == 2 and $start != length($line)) {
  1822.     @compls = ('set', 'select', 'describe', 'rename', 1 .. scalar @targs);
  1823.     return $o->completions($word, \@compls);
  1824.     }
  1825.  
  1826.     if ($words == 2 or $words == 3 and $start != length($line)) {
  1827.     # complete 'set'
  1828.     if (matches($words[1], 's|et')) {
  1829.         my $targ = $o->conf('target');
  1830.         @compls = map { $_->[0] }
  1831.               grep { $_->[1] }
  1832.               PPM::UI::target_config_keys($targ)->result_l;
  1833.         return $o->completions($word, \@compls);
  1834.     }
  1835.     # complete 'describe' and 'rename'
  1836.     elsif (matches($words[1], 'd|escribe')
  1837.         or matches($words[1], 'r|ename')
  1838.         or matches($words[1], 's|elect')) {
  1839.         return $o->completions($word, [1 .. scalar @targs]);
  1840.     }
  1841.     }
  1842.     ();
  1843. }
  1844. sub run_targets {
  1845.     my $o = shift;
  1846.     my @args = @_;
  1847.     trace(1, "PPM: target @args\n");
  1848.  
  1849.     my @targets = PPM::UI::target_list()->result_l;
  1850.     my $targets = @targets;
  1851.  
  1852.     # No arguments: print targets
  1853.     if (@args) {
  1854.     my ($cmd, @rest) = @args;
  1855.     if ($cmd =~ /^\d+$/
  1856.         or matches($cmd, 'se|lect')) {
  1857.         my $num =     $cmd =~ /^\d+$/        ? $cmd        :
  1858.             $rest[0] =~ /^\d+$/    ? $rest[0]    :
  1859.             do {
  1860.                 my $n = find_index($rest[0], 1, @targets);
  1861.                 if ($n < 1) {
  1862.                 $o->warn("No such target '$rest[0]'.\n");
  1863.                 return;
  1864.                 }
  1865.                 $n;
  1866.             };
  1867.  
  1868.         # QA the number: is it too high/low?
  1869.         unless(bounded(1, $num, $targets)) {
  1870.         $o->warn("No such target number '$num'.\n");
  1871.         return;
  1872.         }
  1873.         else {
  1874.         $o->conf('target', $targets[$num-1]);
  1875.         $o->cache_clear('query');
  1876.         }
  1877.     }
  1878.     elsif (matches($cmd, 'r|ename')) {
  1879.         my ($oldnum, $newname) = @rest;
  1880.         $oldnum =    $oldnum =~ /^\d+$/ ? $oldnum :
  1881.             do {
  1882.                 my $n = find_index($oldnum, 1, @targets);
  1883.                 if ($n < 1) {
  1884.                 $o->warn("No such target '$oldnum'.\n");
  1885.                 return;
  1886.                 };
  1887.                 $n;
  1888.             };
  1889.         unless (defined $oldnum && $oldnum =~ /^\d+$/) {
  1890.         $o->warn(<<END);
  1891. target: '$cmd' requires a numeric argument. See 'help $cmd'.
  1892. END
  1893.         return;
  1894.         }
  1895.         unless (bounded(1, $oldnum, $targets)) {
  1896.         $o->warn("No such target number '$oldnum'.\n");
  1897.         return;
  1898.         }
  1899.         unless (defined $newname and $newname) {
  1900.         $newname = '' unless defined $newname;
  1901.         $o->warn(<<END);
  1902. Target names must be non-empty: '$newname' is not a valid name.
  1903. END
  1904.         return;
  1905.         }
  1906.         
  1907.         my $oldname = $targets[$oldnum - 1];
  1908.         my $ret = PPM::UI::target_rename($oldname, $newname);
  1909.         $o->warn($ret->msg) unless $ret->ok;
  1910.         $o->conf('target', $newname)
  1911.           if $o->conf('target') eq $oldname;
  1912.         @targets = PPM::UI::target_list()->result_l;
  1913.         $targets = scalar @targets;
  1914.     }
  1915.     elsif (matches($cmd, "s|et")) {
  1916.         my ($key, $value) = @rest;
  1917.         if (defined $key and $key =~ /=/ and not defined $value) {
  1918.         ($key, $value) = split /=/, $key;
  1919.         }
  1920.         unless(defined($key) && $key) {
  1921.         $o->warn(<<END);
  1922. You must specify what option to set. See 'help target'.
  1923. END
  1924.         return;
  1925.         }
  1926.         unless(defined($value)) {
  1927.         $o->warn(<<END);
  1928. You must provide a value for the option. See 'help target'.
  1929. END
  1930.         return;
  1931.         }
  1932.         my $targ = $o->conf('target');
  1933.         my %keys = map { @$_ }
  1934.                PPM::UI::target_config_keys($targ)->result_l;
  1935.         unless ($keys{$key}) {
  1936.         $o->warn("Invalid set key '$key'; these are the settable values:\n");
  1937.         $o->warn("    $_\n") for (grep { $keys{$_} } keys %keys);
  1938.         return;
  1939.         }
  1940.         my $ok = PPM::UI::target_config_set($targ, $key, $value);
  1941.         unless ($ok->is_success) {
  1942.         $o->warn($ok->msg);
  1943.         return unless $ok->ok;
  1944.         }
  1945.         $o->inform("Target attribute '$key' set to '$value'\n");
  1946.         return 1;
  1947.     }
  1948.     elsif (matches($cmd, "d|escribe")) {
  1949.         my %opts = (exec => 1);
  1950.         my $sel;
  1951.         if (@rest) {
  1952.         local @ARGV = @rest;
  1953.         GetOptions(\%opts, 'exec!');
  1954.         @rest = @ARGV;
  1955.         }
  1956.         if (@rest) {
  1957.         $sel =    $rest[0] =~ /^\d+$/ ? $rest[0] :
  1958.                 do {
  1959.                 my $n = find_index($rest[0], 1, @targets);
  1960.                 if ($n < 1) {
  1961.                     $o->warn("No such target '$rest[0]'.\n");
  1962.                     return;
  1963.                 };
  1964.                 $n;
  1965.                 };
  1966.         unless(bounded(1, $sel, $targets)) {
  1967.             $o->warn("No such target number '$sel'.\n");
  1968.         }
  1969.         }
  1970.         else {
  1971.         $sel = find_index($o->conf('target'), 1, @targets);
  1972.         }
  1973.         my $targ = $targets[$sel-1];
  1974.         my (@keys, @vals);
  1975.         my $res = $opts{exec}
  1976.         ? PPM::UI::target_info($targ)
  1977.         : PPM::UI::target_raw_info($targ);
  1978.         unless ($res->is_success) {
  1979.         $o->warn($res->msg);
  1980.         return unless $res->ok;
  1981.         }
  1982.         my %h = $res->result_h;
  1983.         my @h = sort keys %h;
  1984.         push @keys, @h;
  1985.         push @vals, $h{$_} for @h;
  1986.         if ($opts{exec}) {
  1987.         for (PPM::UI::target_config_info($targ)->result_l) {
  1988.             push @keys, $_->[0];
  1989.             push @vals, $_->[1];
  1990.         }
  1991.         }
  1992.         $_ = ucfirst $_ for @keys;
  1993.         $o->inform("Describing target $sel ($targ):\n");
  1994.         $o->print_pairs(\@keys, \@vals);
  1995.         return 1;
  1996.     }
  1997.     }
  1998.     unless($targets) {
  1999.     $o->warn("No targets. Install a PPM target.\n");
  2000.     return;
  2001.     }
  2002.     else {
  2003.     $o->conf('target', $targets[0])
  2004.         unless $o->conf('target');
  2005.     my $i = 0;
  2006.     $o->inform("Targets:\n");
  2007.     for (@targets) {
  2008.         $o->informf(
  2009.         "%s%2d",
  2010.         $o->conf('target') eq $targets[$i] ? "*" : " ",
  2011.         $i + 1
  2012.         );
  2013.         $o->inform(". $_\n");
  2014.         $i++;
  2015.     }
  2016.     }
  2017.     1;
  2018. }
  2019.  
  2020. #============================================================================
  2021. # Query:
  2022. # query        # displays list of previous queries
  2023. # query <\d+>    # displays results of previous query
  2024. # query <terms>    # performs a new query and displays results
  2025. #============================================================================
  2026. sub smry_query { "queries installed packages" }
  2027. sub help_query { <<'END' }
  2028. query -- Query Installed Packages
  2029.   Synopsis
  2030.      query                   Displays list of previous queries
  2031.      query <number>          Displays results of previous query
  2032.      query <glob pattern>    Performs a new query using <glob pattern>
  2033.      query *                 Displays a list of all installed packages
  2034.  
  2035.   Description
  2036.     The query command displays a list of all installed packages, or a list
  2037.     based on the <glob pattern> switch. You can also check the list of past
  2038.     queries, or the results of a past query.
  2039.  
  2040.     With PPM 3.0, you can now perform much more powerful queries. The syntax
  2041.     is identical to the 'search' command, and almost all the search switches
  2042.     are also available for querying installed packages.
  2043.  
  2044.     Recall previous queries with the 'query <number>' command. PPM3 stores
  2045.     all queries from the current PPM session.
  2046.  
  2047.     Note: Depending on the value of the "case-sensitivity" setting, the
  2048.     query may or may not be case-sensitive. See "help settings" for
  2049.     instructions on setting the default case sensitivity.
  2050.  
  2051.   See Also
  2052.     search, settings
  2053. END
  2054. sub comp_query {()}
  2055. sub run_query {
  2056.     my $o = shift;
  2057.     my $query = $o->raw_args || join ' ', @_;
  2058.     trace(1, "PPM: query @_\n\tquery='$query'\n");
  2059.     my @targets = PPM::UI::target_list()->result_l;
  2060.     my $target = $o->conf('target');
  2061.     my $case = not $o->conf('case-sensitivity');
  2062.     $o->warn("You must install an installation target before using PPM.\n")
  2063.       and return unless @targets;
  2064.  
  2065.     # No args: show cached query sets
  2066.     unless ($query =~ /\S/) {
  2067.     my @query_results = $o->cache_sets('query');
  2068.     my $query_result_current = $o->cache_set_current('query');
  2069.     if (@query_results) {
  2070.         $o->inform("Query Result Sets:\n");
  2071.         my $i = 0;
  2072.         for (@query_results) {
  2073.         $o->informf("%s%2d",
  2074.                $query_result_current == $i ? "*" : " ",
  2075.                $i + 1);
  2076.         $o->inform(". $_->{query}\n");
  2077.         $i++;
  2078.         }
  2079.     }
  2080.     else {
  2081.         $o->warn("No query result sets -- provide a query term.\n");
  2082.         return;
  2083.     }
  2084.     }
  2085.  
  2086.     # Args:
  2087.     else {
  2088.     # Show specified result set 
  2089.     if ($query =~ /^\d+/) {
  2090.         my $set = int($query);
  2091.         unless (defined $o->cache_set('query', $set-1)) {
  2092.         $o->warn("No such query result set '$set'.\n");
  2093.         return;
  2094.         }
  2095.  
  2096.         $query = $o->cache_set('query', $set-1, 'query');
  2097.         $o->inform("Query Results Set $set ($query):\n");
  2098.         $o->print_formatted([$o->cache_set('query', $set-1)],
  2099.                 $o->cache_set_index('query'));
  2100.                 
  2101.         $o->cache_set_current('query', $set-1);
  2102.         $o->cache_set_index('query', -1);
  2103.     }
  2104.  
  2105.     # Query is the same a a previous query on the same target:
  2106.     # Use cached results and set them as default
  2107.     elsif (grep { $_->{query} eq $query } $o->cache_sets('query')) {
  2108.         for (my $i=0; $i<$o->cache_sets('query'); $i++) {
  2109.         if ($o->cache_set('query', $i, 'query') eq $query) {
  2110.             $o->inform("Using cached query result set ", $i+1, ".\n");
  2111.             $o->cache_set_current('query', $i);
  2112.             my $set = $o->cache_set('query');
  2113.             $o->print_formatted($set);
  2114.         }
  2115.         }
  2116.     }
  2117.  
  2118.     # Perform a new query.
  2119.     else {
  2120.         my $num = find_index($target, 1, @targets);
  2121.         $o->inform("Querying target $num (");
  2122.         if (length($target) > 30) {
  2123.         $o->inform(substr($target, 0, 30), "...");
  2124.         }
  2125.         else {
  2126.         $o->inform($target);
  2127.         }
  2128.         $o->inform(")\n");
  2129.  
  2130.         my $res = PPM::UI::query($target, $query, $case);
  2131.         unless ($res->ok) {
  2132.         $o->inform($res->msg);
  2133.         return;
  2134.         }
  2135.         my @matches = $res->result_l;
  2136.         if (@matches) {
  2137.         $o->cache_set_add('query', $query, \@matches);
  2138.         $o->cache_set_current('query', scalar($o->cache_sets('query')) - 1);
  2139.         my @set = $o->cache_set('query');
  2140.         $o->print_formatted(\@set);
  2141.         }
  2142.         else {
  2143.         $o->warn("No matches for '$query'; see 'help query'.\n");
  2144.         }
  2145.     }
  2146.     }
  2147.     1;
  2148. }
  2149.  
  2150. #============================================================================
  2151. # Properties:
  2152. # prop        # describes default installed package
  2153. # prop <\d+>    # describes numbered installed package
  2154. # prop <pkg>    # describes named installed package
  2155. # prop <url>    # describes installed package at location <url>
  2156. #============================================================================
  2157. sub smry_properties { "describes installed packages in detail" }
  2158. sub help_properties { <<'END' }
  2159. properties -- Describe Installed Packages
  2160.   Synopsis
  2161.      prop                    Describes default installed package
  2162.      prop <number>           Describes installed package <number>
  2163.      prop <range>            Describes a <range> of installed packages
  2164.      prop <package name>     Describes named installed package
  2165.      prop <url>              Describes installed package located at <url>
  2166.      prop <glob pattern>     Performs a new query using <glob pattern>
  2167.  
  2168.   Description
  2169.     The properties command is an verbose form of the describe command. In
  2170.     addition to summary information, properties will display the
  2171.     installation date and a URL showing the location of the package within
  2172.     the repository.
  2173.  
  2174.     If you specify the package as a URL, PPM determines the package name
  2175.     from the URL and searches for that.
  2176.  
  2177.     When the properties command is used with wildcard arguments, the text
  2178.     entered at the PPM prompt is passed to the query command.
  2179.  
  2180.     For example, typing 'properties libnet' will give you:
  2181.  
  2182.         ====================
  2183.             Name: libnet
  2184.          Version: 1.07.03
  2185.           Author: Graham Barr
  2186.            Title: libnet
  2187.         Abstract: Collection of Network protocol modules
  2188.         InstDate: Fri Oct  2 16:15:15 1998
  2189.         Location: http://ppm-ia.ActiveState.com/PPM/...
  2190.         ====================
  2191.  
  2192.   See Also
  2193.     describe
  2194. END
  2195. sub comp_properties {
  2196.     my $o = shift;
  2197.     my ($word, $line, $start) = @_;
  2198.  
  2199.     # If no query results
  2200.     my $n_results = scalar $o->cache_sets('query');
  2201.     my $n_current = $o->cache_set_current('query');
  2202.     unless ($n_results and bounded(0, $n_current, $n_results - 1)) {
  2203.     my $targ = $o->conf('target') or return ();
  2204.     my $r = PPM::UI::query($targ, '*');
  2205.     return () unless $r->ok;
  2206.     $o->cache_set_add('query', '*', $r->result);
  2207.     $o->cache_set_current('query', scalar($o->cache_sets('query')) - 1);
  2208.     }
  2209.     my @words = $o->line_parsed($line);
  2210.  
  2211.     # If the previous word isn't a number or the command, stop.
  2212.     return ()
  2213.       if ($#words > 0 and
  2214.       $words[$#words] !~ /^\d+/ and
  2215.       $start == length($line) or 
  2216.       $#words > 1);
  2217.  
  2218.     # This is the most optimistic list:
  2219.     my @results = $o->cache_set('query');
  2220.     my $npkgs = @results;
  2221.     my @compls = (1 .. $npkgs);
  2222.  
  2223.     # If the previous word is a number, return only other numbers:
  2224.     return $o->completions($word, \@compls)
  2225.       if ($words[$#words] =~ /^\d+/);
  2226.  
  2227.     # Either a number or the names of the packages
  2228.     push @compls, map { $_->name } @results;
  2229.     return $o->completions($word, \@compls);
  2230. }
  2231. sub run_properties {
  2232.     my $o = shift;
  2233.     my @args = @_;
  2234.     my $args = $args[0];
  2235.     trace(1, "PPM: properties @args\n");
  2236.  
  2237.     # Check for anything that looks like a query. If it does, send it
  2238.     # to query instead.
  2239.     my $query = $o->raw_args || join ' ', @args;
  2240.     $query ||= '';
  2241.     if ($query and not PPM::UI::is_pkg($args[0]) and not parse_range($query)) {
  2242.     $o->inform("Wildcards detected; using 'query' instead.\n");
  2243.     return $o->run('query', @_);
  2244.     }
  2245.     
  2246.     # No Args: describes current index of current result set, or 1.
  2247.     my $n_results = $o->cache_sets('query');
  2248.     my $n_current = $o->cache_set_current('query');
  2249.     my $ind = $o->cache_set_index('query');
  2250.     unless (@args) {
  2251.     unless ($n_results and bounded(0, $n_current, $n_results - 1)) {
  2252.         $o->inform("No query results to describe -- " . 
  2253.           "use 'query' to find a package.\n");
  2254.         return;
  2255.     }
  2256.     else {
  2257.         my @results = $o->cache_set('query');
  2258.         my $npkgs = @results;
  2259.         $o->inform("$SEP\n");
  2260.         if (bounded(0, $ind, $npkgs-1)) {
  2261.         my $n = $ind + 1;
  2262.         $o->inform("Package $n:\n");
  2263.         $o->describe_pkg($o->cache_entry('query', $ind));
  2264.         }
  2265.         else {
  2266.         $o->inform("Package 1:\n");
  2267.         $o->describe_pkg($results[0]);
  2268.         $o->cache_set_index('query', 0);
  2269.         }
  2270.         $o->inform("$SEP\n");
  2271.     }
  2272.     }
  2273.  
  2274.     # Args provided
  2275.     else {
  2276.  
  2277.     # Describe a particular number:
  2278.     if (my @r = parse_range(@args)) {
  2279.         unless ($n_results and bounded(0, $n_current, $n_results - 1)) {
  2280.         $o->inform("No query results to describe -- " . 
  2281.           "use 'query' to find a package.\n");
  2282.         return;
  2283.         }
  2284.         else {
  2285.         for my $n (@r) {
  2286.             my @results = $o->cache_set('query');
  2287.             my $npkgs = @results;
  2288.             $o->inform("$SEP\n");
  2289.             if (bounded(1, $n, $npkgs)) {
  2290.             $o->inform("Package $n:\n");
  2291.             $o->cache_set_index('query', $n-1);
  2292.             my $old = $o->cache_entry('query');
  2293.             my $prop =
  2294.               PPM::UI::properties($o->conf('target'), $old->name);
  2295.             unless ($prop->is_success) {
  2296.                 $o->warn($prop->msg);
  2297.                 next unless $prop->ok;
  2298.             }
  2299.             my ($pkg, $idate, $loc) = $prop->result_l;
  2300.             $o->describe_pkg($pkg,
  2301.                      [qw(InstDate Location)],
  2302.                      [$idate, $loc],
  2303.                     );
  2304.             }
  2305.             else {
  2306.             $o->inform("No such package $n in result set.\n");
  2307.             }
  2308.         }
  2309.         $o->inform("$SEP\n");
  2310.         }
  2311.     }
  2312.  
  2313.     # Query a particular package
  2314.     else {
  2315.         if ($o->conf('target')) {
  2316.         my $prop =
  2317.           PPM::UI::properties($o->conf('target'), $args);
  2318.         unless ($prop->is_success) {
  2319.             $o->warn($prop->msg);
  2320.             return unless $prop->ok;
  2321.         }
  2322.         my ($pkg, $idate, $loc) = $prop->result_l;
  2323.         my ($s, $index) = $o->cache_find('query', $args);
  2324.         $o->inform("$SEP\n") if $pkg;
  2325.         $o->describe_pkg($pkg,
  2326.                  [qw(InstDate Location)],
  2327.                  [$idate, $loc],
  2328.                 )
  2329.           if $pkg;
  2330.         $o->inform("$SEP\n") if $pkg;
  2331.         if ($index >= 0) {
  2332.             $o->cache_set_current('query', $s);
  2333.             $o->cache_set_index('query', $index);
  2334.         }
  2335.         elsif ($pkg) {
  2336.             $o->cache_set_add('query', $args[0], [$pkg]);
  2337.             my $last = $o->cache_sets('query') - 1;
  2338.             $o->cache_set_current('query', $last);
  2339.             $o->cache_set_index('query', 0);
  2340.         }
  2341.         $o->warn("Package '$args' not found; 'query' for it first.\n")
  2342.           and return unless $pkg;
  2343.         }
  2344.         else {
  2345.         # XXX: Change this output.
  2346.         $o->warn(
  2347.             "There are no targets installed.\n"
  2348.         );
  2349.         return;
  2350.         }
  2351.     }
  2352.     }
  2353.     1;
  2354. }
  2355.  
  2356. #============================================================================
  2357. # Uninstall:
  2358. # uninst    # removes default installed package
  2359. # uninst <\d+>    # removes specified package
  2360. # uninst <pkg>    # removes specified package
  2361. # uninst <url>    # removes the package located at <url>
  2362. #============================================================================
  2363. sub smry_uninstall { "uninstalls packages" }
  2364. sub help_uninstall { <<'END' }
  2365. remove, uninstall -- Uninstalls Installed Packages
  2366.   Synopsis
  2367.      remove              Deletes default installed package
  2368.      remove <number>     Deletes installed package <number>
  2369.      remove <range>      Deletes a <range> of installed packages
  2370.      remove <name>       Deletes a packages by a specific name
  2371.      remove <url>        Deletes the package located at <url>
  2372.  
  2373.   Description
  2374.     The remove and uninstall commands function identically. They are used to
  2375.     delete packages from the current target (specified using the target
  2376.     command). If profile tracking is enabled, (see 'help profile') the
  2377.     current PPM profile on ASPN will be updated.
  2378.  
  2379.     Packages can be removed by package name, by their numerical listing, or
  2380.     by specifying a URL to a PPD file. For example:
  2381.  
  2382.         remove XML-DOM
  2383.  
  2384.     will delete the XML-DOM package from the target.
  2385.  
  2386.     To remove package by number:
  2387.  
  2388.         remove 6
  2389.  
  2390.     and the sixth package in your current query will be removed. If no
  2391.     queries have been run in the current PPM session, you will be prompted
  2392.     to use a query to find a package before deleting it. Remember that
  2393.     removing packages clears all previous query requests, since the
  2394.     numerical sequence stored in any query will no longer be true once
  2395.     package(s) have been removed.
  2396.  
  2397.     Packages can also be removed in groups. For example:
  2398.  
  2399.         remove 4-7
  2400.  
  2401.     will delete packages 4, 5, 6, and 7 from your target. You can also skip
  2402.     packages:
  2403.  
  2404.         remove 3-5, 7
  2405.  
  2406.     this will delete packages 3, 4, 5 and 7, but will leave 6 intact.
  2407.     Remember to run a new query whenever you remove a package from your
  2408.     target.
  2409.  
  2410.     If you specify the package as a URL, PPM determines the package name
  2411.     from the URL and removes that.
  2412.  
  2413.     Please note that wildcards like "*" or "?" cannot be used with the
  2414.     remove command.
  2415.  
  2416.   See Also
  2417.     profile
  2418. END
  2419. sub comp_uninstall { goto &comp_properties; }
  2420. sub run_uninstall {
  2421.     my $o = shift;
  2422.     my @args = @_;
  2423.     trace(1, "PPM: uninstall @args\n");
  2424.  
  2425.     # Get the force option:
  2426.     my ($force);
  2427.     {
  2428.     local @ARGV = @args;
  2429.     GetOptions(
  2430.         'force!' => \$force,
  2431.     );
  2432.     @args = @ARGV;
  2433.     }
  2434.     
  2435.     my $args = $args[0];
  2436.  
  2437.     # No Args -- removes default package
  2438.     my $n_results = $o->cache_sets('query');
  2439.     my $n_current = $o->cache_set_current('query');
  2440.     my $ind = $o->cache_set_index('query');
  2441.     unless (@args) {
  2442.     unless ($n_results and bounded(0, $n_current, $n_results - 1)) {
  2443.         $o->warn("No query results to uninstall -- " . 
  2444.           "use 'query' to find a package.\n");
  2445.         return;
  2446.     }
  2447.     else {
  2448.         my @results = $o->cache_set('query');
  2449.         if (bounded(0, $ind, $#results)) {
  2450.         my $n = $ind + 1;
  2451.         $o->inform("Package $n:\n");
  2452.         $o->remove_pkg($o->cache_entry('query', $ind)->name, $force);
  2453.         }
  2454.         else {
  2455.         $o->inform("Package 1:\n");
  2456.         $o->remove_pkg($o->cache_entry('query', 0)->name, $force);
  2457.         }
  2458.     }
  2459.     }
  2460.  
  2461.     # Args provided
  2462.     else {
  2463.     # Uninstall a particular number:
  2464.     if (my @r = parse_range(@args)) {
  2465.         unless ($n_results and bounded(0, $n_current, $n_results - 1)) {
  2466.         $o->warn("No query results to uninstall -- " . 
  2467.           "use 'query' to find a package.\n");
  2468.         return;
  2469.         }
  2470.         else {
  2471.         my @results = $o->cache_set('query');
  2472.         my $npkgs = @results;
  2473.         my $ok = 0;
  2474.         for my $n (@r) {
  2475.             if (bounded(1, $n, $npkgs)) {
  2476.             $o->inform("Package $n:\n");
  2477.             $ok |=
  2478.               $o->remove_pkg($o->cache_entry('query', $n-1)->name,
  2479.                      $force, 1);
  2480.             }
  2481.             else {
  2482.             $o->warn("No such package $n in result set.\n");
  2483.             }
  2484.         }
  2485.         $o->cache_clear('query') if $ok;
  2486.         }
  2487.     }
  2488.  
  2489.     # Uninstall a particular package
  2490.     else {
  2491.         if ($o->conf('target')) {
  2492.         $o->remove_pkg($_, $force) for @args;
  2493.         }
  2494.         else {
  2495.         print
  2496.           "No targets -- use 'rep add' to add a target.\n";
  2497.         return;
  2498.         }
  2499.     }
  2500.     }
  2501.     1;
  2502. }
  2503. sub alias_uninstall { qw(remove) }
  2504.  
  2505. #============================================================================
  2506. # Settings:
  2507. #============================================================================
  2508. my (%lib_keys, @ui_keys);
  2509. my (@path_keys, @boolean_keys, @integer_keys);
  2510. my (%cache_clear_keys);
  2511. BEGIN {
  2512.     %lib_keys = ('download-chunksize' => 'downloadbytes',
  2513.         'tempdir' => 'tempdir',
  2514.         'trace-file' => 'tracefile',
  2515.         'trace-level' => 'tracelvl',
  2516.         'profile-track' => 'profile_enable',
  2517.         );
  2518.     @ui_keys = qw(
  2519.     case-sensitivity
  2520.     pager
  2521.     fields
  2522.     follow-install
  2523.     force-install
  2524.     prompt-context
  2525.     prompt-slotsize
  2526.     prompt-verbose
  2527.     sort-field
  2528.     verbose-startup
  2529.  
  2530.     install-verbose
  2531.     upgrade-verbose
  2532.     remove-verbose
  2533.     );
  2534.     @boolean_keys = qw(case-sensitivity force-install follow-install
  2535.                prompt-context prompt-verbose profile-track
  2536.                verbose-startup install-verbose upgrade-verbose
  2537.                remove-verbose
  2538.               );
  2539.     @integer_keys = qw(download-chunksize prompt-slotsize trace-level);
  2540.     @path_keys = qw(tempdir pager trace-file);
  2541.     @cache_clear_keys{qw/
  2542.     case-sensitivity
  2543.     /} = ();
  2544. }
  2545. sub settings_getkeys {
  2546.     my $o = shift;
  2547.     my @keys = @ui_keys;
  2548.     push @keys, keys %lib_keys;
  2549.     @keys;
  2550. }
  2551. sub settings_getvals {
  2552.     my $o = shift;
  2553.     my @vals;
  2554.     push @vals, $o->settings_getkey($_) for $o->settings_getkeys;
  2555.     @vals;
  2556. }
  2557.  
  2558. sub conf {
  2559.     my $o   = shift;
  2560.     my $key = shift;
  2561.     my $val = shift;
  2562.     my $un  = shift;
  2563.     return $o->settings_setkey($key, $val, $un) if defined $val;
  2564.     return $o->settings_getkey($key);
  2565. }
  2566.  
  2567. sub settings_getkey {
  2568.     my $o = shift;
  2569.     my $key = shift;
  2570.     return PPM::UI::config_get($lib_keys{$key})->result if $lib_keys{$key};
  2571.     return $o->{SHELL}{conf}{DATA}{$key};
  2572. }
  2573. sub settings_setkey {
  2574.     my $o = shift;
  2575.     my ($key, $val, $un) = @_;
  2576.     if (grep { $key eq $_ } @boolean_keys) {
  2577.     $val = 0 if $un;
  2578.     unless ($val =~ /^\d+$/ && ($val == 0 || $val == 1)) {
  2579.         $o->warn(<<END);
  2580. Setting '$key' must be boolean: '0' or '1'. See 'help settings'.
  2581. END
  2582.         return;
  2583.     }
  2584.     }
  2585.     elsif (grep { $key eq $_ } @integer_keys) {
  2586.     $val = 0 if $un;
  2587.     unless ($val =~ /^\d+$/) {
  2588.         $o->warn(<<END);
  2589. Setting '$key' must be numeric. See 'help settings'.
  2590. END
  2591.         return;
  2592.     }
  2593.     }
  2594.     elsif ($key eq 'sort-field') {
  2595.     $val = 'name' if $un;
  2596.     my @fields = sort_fields();
  2597.     unless (grep { lc($val) eq $_ } @fields) {
  2598.         $o->warn(<<END);
  2599. Error setting '$key' to '$val': should be one of:
  2600. @fields.
  2601. END
  2602.         return;
  2603.     }
  2604.     else {
  2605.         $val = lc($val);
  2606.         $o->cache_set_index('search', -1); # invalidates current indices.
  2607.         $o->cache_set_index('query', -1);
  2608.     }
  2609.     }
  2610.     elsif ($key eq 'fields') {
  2611.     $val = 'name version abstract' if $un;
  2612.     my @fields = sort_fields();
  2613.     my @vals = split ' ', $val;
  2614.     for my $v (@vals) {
  2615.         unless (grep { lc $v eq lc $_ } @fields) {
  2616.         $o->warn(<<END);
  2617. Error adding field '$v': should be one of:
  2618. @fields.
  2619. END
  2620.         return;
  2621.         }
  2622.     }
  2623.     $val = lc $val;
  2624.     }
  2625.  
  2626.     if ($un and $key eq 'tempdir') {
  2627.     $o->warn("Can't unset 'tempdir': use 'set' instead.\n");
  2628.     return;
  2629.     }
  2630.  
  2631.     # Check for any cache-clearing that needs to happen:
  2632.     if (exists $cache_clear_keys{$key}) {
  2633.     $o->cache_clear('search');
  2634.     $o->cache_clear('query');
  2635.     }
  2636.  
  2637.     if ($lib_keys{$key}) { PPM::UI::config_set($lib_keys{$key}, $val) }
  2638.     else {
  2639.     $o->{SHELL}{conf}{DATA}{$key} = $val;
  2640.     $o->{SHELL}{conf}->save;
  2641.     }
  2642.     $o->inform(<<END);
  2643. Setting '$key' set to '$val'.
  2644. END
  2645. }
  2646.  
  2647. sub smry_settings { "view or set PPM options" }
  2648. sub help_settings { <<'END' }
  2649. settings -- View or Set PPM Settings
  2650.   Synopsis
  2651.      set                 Displays current settings
  2652.      set <name>          Displays the current setting of the given <name>
  2653.      set <name> <value>  Sets <name> to <value>
  2654.      unset <name>        Sets <name> to a "false" value: '0' for boolean
  2655.                          Settings, '' for others.
  2656.  
  2657.   Description
  2658.     The settings command is used to configure the default PPM environment.
  2659.     Settings such as the number of lines displayed per page,
  2660.     case-sensitivity, and the log file are configured using the settings
  2661.     command.
  2662.  
  2663.     Setting names may be abbreviated to uniqueness. For example, instead of
  2664.     typing 'case-sensitivity', you may type 'case'.
  2665.  
  2666.     Available settings:
  2667.  
  2668.      NAME                VALUE           DESCRIPTION
  2669.      case-sensitivity    1 or 0      If 1, searches and queries are
  2670.                                      case-sensitive.
  2671.  
  2672.      download-chunksize  integer     If this is set to a positive,
  2673.                                      non-zero integer, PPM updates the
  2674.                                      status after "integer" of bytes
  2675.                                      transferred during an install or
  2676.                                      upgrade.
  2677.  
  2678.      fields              fields      A space-separated list of fields to 
  2679.                                      display in the search results. Valid
  2680.                                      fields are:
  2681.  
  2682.                                        ABSTRACT
  2683.                                        AUTHOR
  2684.                                        NAME
  2685.                                        REPOSITORY
  2686.                                        TITLE
  2687.                                        VERSION
  2688.  
  2689.                                      Usually, NAME and TITLE have the same
  2690.                                      content.
  2691.  
  2692.      follow-install      1 or 0      See 'help install' for details.
  2693.  
  2694.      force-install       1 or 0      See 'help install' for details.
  2695.  
  2696.      install-verbose     1 or 0      If 0, suppresses most output when
  2697.                                      installing packages. If 1, PPM prints
  2698.                                      each file as it is installed.
  2699.  
  2700.      pager               path        The path to an external pager program
  2701.                                      used to page long displays. If blank,
  2702.                                      or set to 'internal', the internal
  2703.                                      pager is used. If 'none', paging
  2704.                                      is disabled.
  2705.  
  2706.      profile-track       1 or 0      If 1, PPM arranges to have the 
  2707.                                      ASPN server track your PPM profile. 
  2708.                                      This means that every time your install
  2709.                                      or remove a package, your profile is
  2710.                                      updated on the server. If 0, you must
  2711.                                      manually save your profile using
  2712.                                      'profile save'.
  2713.  
  2714.      prompt-context      1 or 0      If 1, enables the prompt to change
  2715.                                      based on the current state of PPM, i.e
  2716.                                      showing current target, query, etc.
  2717.  
  2718.      prompt-slotsize     integer     If prompt-verbose is 1, this defines
  2719.                                      the width of each slot in the prompt.
  2720.                                      For instance, 4 means to use 4 
  2721.                                      character-wide slots.
  2722.  
  2723.      prompt-verbose      1 or 0      If 0, uses numbers to represent the
  2724.                                      context in the prompt; much shorter.
  2725.                                      If prompt-context is set to 0, there
  2726.                                      will be no visible difference in the
  2727.                                      'prompt-verbose' settings.
  2728.  
  2729.      remove-verbose      1 or 0      If 0, suppresses most output when
  2730.                                      removing packages. If 1, prints the
  2731.                                      name of each file as it is removed.
  2732.  
  2733.      sort-field          field       The field by which to sort search and
  2734.                                      query results. Valid fields are
  2735.                                      ABSTRACT, AUTHOR, NAME, TITLE
  2736.                                      and VERSION.
  2737.  
  2738.      tempdir             path        A temporary directory into which
  2739.                                      packages are downloaded and expanded
  2740.                                      during 'install' and 'upgrade'.
  2741.  
  2742.      trace-file          path        A file to which PPM will write tracing
  2743.                                      information.
  2744.  
  2745.      trace-level         integer     If 0 or negative, tracing is disabled.
  2746.                                      Positive, non-zero integers result in
  2747.                                      tracing information being written to
  2748.                                      'trace-file'. Higher settings of
  2749.                                      'trace-level' result in more trace
  2750.                                      information.
  2751.  
  2752.      upgrade-verbose     1 or 0      If 0, suppresses most output when
  2753.                                      upgrading packages. If 1, prints the
  2754.                                      name of each file as it is upgraded.
  2755.  
  2756.     For information about migrating options used by previous versions of
  2757.     PPM, see 'help ppm_migration'.
  2758.  
  2759.     When you assign a value to a setting, PPM saves the configuration.
  2760.     Therefore, setting values persist across sessions.
  2761. END
  2762. sub comp_settings {
  2763.     my $o = shift;
  2764.     my ($word, $line, $start) = @_;
  2765.     my @words = $o->line_parsed($line);
  2766.  
  2767.     # To please the users of Bash, we'll allow 'set foo=bar' to work as well,
  2768.     # since it's really easy to do:
  2769.     if (defined $words[1] and $words[1] =~ /=/ and not defined $words[2]) {
  2770.     my @kv = split '=', $words[1];
  2771.     splice(@words, 1, 1, @kv);
  2772.     }
  2773.     my $words = @words;
  2774.     my @compls;
  2775.  
  2776.     # return the keys when we're completing the second word
  2777.     if ($words == 1 or $words == 2 and $start != length($line)) {
  2778.     @compls = $o->settings_getkeys();
  2779.     return $o->completions($word, \@compls);
  2780.     }
  2781.  
  2782.     # Return no completions for 'unset'.
  2783.     return () if matches($o->{API}{cmd}{run}{name}, 'u|nset');
  2784.  
  2785.     # provide intelligent completion for arguments:
  2786.     if ($words ==2 or $words == 3 and $start != length($line)) {
  2787.     # Completion for boolean values:
  2788.     my @bool = $o->completions($words[1], \@boolean_keys);
  2789.     my @path = $o->completions($words[1], \@path_keys);
  2790.     if (@bool == 1) {
  2791.         return $o->completions($word, [0, 1]);
  2792.     }
  2793.     elsif (@path == 1) {
  2794.         @compls = readline::rl_filename_list($word);
  2795.         return $o->completions($word, \@compls);
  2796.     }
  2797.     elsif (matches($words[1], 's|ort-field')) {
  2798.         @compls = sort_fields();
  2799.         return $o->completions(lc($word), \@compls);
  2800.     }
  2801.     }
  2802.  
  2803.     # Don't complete for anything else.
  2804.     ()
  2805. }
  2806. sub run_settings {
  2807.     my $o = shift;
  2808.     my @args = @_;
  2809.     my $key = $args[0];
  2810.     my $val = $args[1];
  2811.  
  2812.     # To please the users of Bash, we'll allow 'set foo=bar' to work as well,
  2813.     # since it's really easy to do:
  2814.     if (defined $key and $key =~ /=/ and not defined $val) {
  2815.     ($key, $val) = split '=', $key;
  2816.     }
  2817.  
  2818.     trace(1, "PPM: settings @args\n");
  2819.     my $unset = matches($o->{API}{cmd}{run}{name}, 'u|nset');
  2820.     my @stuff = $o->completions($key, [$o->settings_getkeys()])
  2821.       if $key;
  2822.     my $fullkey = $stuff[0] if @stuff == 1;
  2823.     if (defined $key and defined $val) {
  2824.     # validate the key:
  2825.     unless ($fullkey) {
  2826.         $key = '' unless defined $key;
  2827.         $o->warn("Unknown or ambiguous setting '$key'. See 'help settings'.\n");
  2828.         return;
  2829.     }
  2830.     $o->conf($fullkey, $val, $unset);
  2831.     }
  2832.     elsif (defined $key) {
  2833.     unless ($fullkey) {
  2834.         $key = '' unless defined $key;
  2835.         $o->warn("Unknown or ambiguous setting '$key'. See 'help settings'.\n");
  2836.         return;
  2837.     }
  2838.     if ($unset) {
  2839.         $o->conf($fullkey, '', $unset);
  2840.     }
  2841.     else {
  2842.         my $val = $o->conf($fullkey);
  2843.         $o->print_pairs([$fullkey], [$val]);
  2844.     }
  2845.     }
  2846.     else {
  2847.     my (@keys, @vals);
  2848.     @keys = $o->settings_getkeys();
  2849.     @vals = $o->settings_getvals();
  2850.     my %k;
  2851.     @k{@keys} = @vals;
  2852.     @keys = sort keys %k;
  2853.     @vals = map { $k{$_} } @keys;
  2854.     $o->print_pairs(\@keys, \@vals);
  2855.     }
  2856. }
  2857. sub alias_settings { qw(unset) }
  2858.  
  2859. sub help_help { <<'END' }
  2860. help -- General help, or help on specific commands.
  2861.   Synopsis
  2862.      help                Lists available commands and help topics
  2863.      help 'command'      Lists detailed help about a specific command
  2864.  
  2865.   Description
  2866.     The help command provides a brief description of the commands available
  2867.     within PPM. For help on a specific command, enter help followed by the
  2868.     command name. For example, enter help settings or help set for a
  2869.     detailed description of the settings command.
  2870.  
  2871.     There are some extra help topics built into PPM. They can be accessed
  2872.     within the PPM environment as follows:
  2873.  
  2874.       help ppm_migration
  2875.  
  2876.     shows more details about the changes from previous versions of PPM
  2877.  
  2878.       help quickstart
  2879.  
  2880.     an easy-to-follow guide to getting started with PPM
  2881.  
  2882.       help prompt
  2883.  
  2884.     provides a detailed explanation about the PPM prompt
  2885. END
  2886.  
  2887. #============================================================================
  2888. # Version:
  2889. #============================================================================
  2890. sub smry_version { "displays the PPM version ($VERSION)" }
  2891. sub help_version { <<'END' }
  2892. version -- print the name and version of PPM.
  2893.     Prints the name and version of PPM3.
  2894. END
  2895. sub comp_version {()}
  2896. sub run_version {
  2897.     my $o = shift;
  2898.     if ($o->mode eq 'SHELL') {
  2899.     $o->inform("$NAME version $VERSION\n");
  2900.     }
  2901.     else {
  2902.     $o->inform("$SHORT_NAME $VERSION\n");
  2903.     }
  2904.     1;
  2905. }
  2906.  
  2907. #============================================================================
  2908. # Exit:
  2909. #============================================================================
  2910. sub help_exit { <<'END' }
  2911. exit, q, quit -- Exit the program
  2912.   Synopsis
  2913.      exit                Exit
  2914.      quit                Exit
  2915.      q                   Exit
  2916.      q <query>           Perform a new query (shortcut for query)
  2917.  
  2918.   Description
  2919.     When you leave the PPM environment, the current settings are saved.
  2920. END
  2921. sub comp_exit {
  2922.     my $o = shift;
  2923.     return &comp_query
  2924.     if $o->{API}{cmd}{run}{name} eq 'q' and @_;
  2925.     ();
  2926. }
  2927. sub run_exit {
  2928.     my $o = shift;
  2929.     # Special case: 'q' with no arguments should mean 'quit', but 'q' with
  2930.     # arguments should mean 'query'.
  2931.     if ($o->{API}{cmd}{run}{name} eq 'q' and @_) {
  2932.     return $o->run('query', @_);
  2933.     }
  2934.     $o->stoploop;
  2935. }
  2936. sub alias_exit { qw(quit q) }
  2937.  
  2938. #============================================================================
  2939. # Upgrade
  2940. # upgrade    # lists upgrades available
  2941. # upgrade <\d+> # upgrades specified package
  2942. # upgrade<pkg>    # upgrades named package
  2943. #============================================================================
  2944. sub smry_upgrade { "shows availables upgrades for installed packages" }
  2945. sub help_upgrade { <<'END' }
  2946. upgrade -- List or install available upgrades
  2947.   Synopsis
  2948.      upgrade [*]         Lists upgrades available for all installed packages
  2949.      upgrade <number>    Upgrades installed package <number>
  2950.      upgrade <range>     Upgrades a <range> of installed packages
  2951.      upgrade <package>   Upgrades the named <package>
  2952.  
  2953.   Description
  2954.     The upgrade command lists package upgrades that are available on the
  2955.     current repository for packages installed on your system. To install
  2956.     available upgrades, use the '--install' option.
  2957.  
  2958.     If profile tracking is enabled, (see 'help profile'), your profile will
  2959.     be updated to reflect changes to any packages which are upgraded.
  2960.  
  2961.     There are several modifiers to the upgrade command:
  2962.  
  2963.     -install
  2964.         Installs, rather than lists, available upgrades
  2965.  
  2966.     -precious
  2967.         Allows upgrading of "precious" packages
  2968.  
  2969.     -force
  2970.         See 'help install'
  2971.  
  2972.     -follow
  2973.         See 'help install'
  2974.  
  2975.     By default, 'upgrade' typed by itself only lists the available upgrades.
  2976.     To actually install all available upgrades, enter
  2977.  
  2978.         upgrade -install
  2979.  
  2980.     To enable upgrading "precious" packages, enter
  2981.  
  2982.         upgrade -install -precious
  2983.  
  2984.   See Also
  2985.     profile
  2986. END
  2987. sub comp_upgrade { goto &comp_properties; }
  2988. sub run_upgrade {
  2989.     my $o = shift;
  2990.     my @args = @_;
  2991.     trace(1, "PPM: upgrade @args\n");
  2992.  
  2993.     # Get options:
  2994.     my %opts = (
  2995.     install => 0,
  2996.     doprecious => 0,
  2997.     dryrun => 0,
  2998.     force => $o->conf('force-install'),
  2999.     follow => $o->conf('follow-install'),
  3000.     );
  3001.     {
  3002.     local @ARGV = @args;
  3003.     GetOptions(install => \$opts{install},
  3004.            precious => \$opts{doprecious},
  3005.            'force!' => \$opts{force},
  3006.            'follow!' => \$opts{follow},
  3007.            dryrun => \$opts{dryrun},
  3008.           );
  3009.     @args = @ARGV;
  3010.     }
  3011.  
  3012.     my $rlist = [$o->reps_on];
  3013.     my $targ  = $o->conf('target');
  3014.     my @pkgs;
  3015.  
  3016.     # Allow 'upgrade *';
  3017.     @args = grep { $_ ne '*' } @args;
  3018.  
  3019.     # List upgrades for a particular package
  3020.     if (@args) {
  3021.     my $pkg = $args[0];
  3022.     my @n = parse_range($o->raw_args);
  3023.     for my $n (@n) {
  3024.         my $ppd = $o->cache_entry('query', $n-1);
  3025.         unless($ppd) {
  3026.         $o->warn("No such query result '$pkg' in result set.\n");
  3027.         return;
  3028.         }
  3029.         else {
  3030.         push @pkgs, $ppd;
  3031.         }
  3032.     }
  3033.  
  3034.     # The name of the package:
  3035.     unless (@n) {
  3036.         my $ppd = PPM::UI::properties($o->conf('target'), $pkg);
  3037.         unless ($ppd->is_success) {
  3038.         $o->warn($ppd->msg);
  3039.         return unless $ppd->ok;
  3040.         }
  3041.         my $real_ppd = ($ppd->result_l)[0];
  3042.         push @pkgs, $real_ppd;
  3043.     }
  3044.     }
  3045.     # List upgrades for all packages
  3046.     else {
  3047.     @pkgs = PPM::UI::query($targ, '*', 0)->result_l;
  3048.     @pkgs = $o->sort_pkgs($o->conf('sort-field'), @pkgs);
  3049.     }
  3050.  
  3051.     my $verify = PPM::UI::verify_pkgs($rlist, $targ, @pkgs);
  3052.     unless ($verify->is_success) {
  3053.     $o->error("Error verifying packages: ", $verify->msg_raw, "\n");
  3054.     return;
  3055.     }
  3056.     my %bypackage;
  3057.     for my $result ($verify->result_l) {
  3058.     next unless $result->is_success; # ignore unfound packages
  3059.     my ($uptodate, $server_pkg, $inst_pkg, $b, $p) = $result->result_l;
  3060.     my $name = $server_pkg->name;
  3061.     my $nver = $server_pkg->version;
  3062.     my $over = $inst_pkg->version;
  3063.     my $repo = $server_pkg->repository->name;
  3064.     $bypackage{$name}{$repo} = {
  3065.         uptodate => $uptodate,
  3066.         oldver => $over,
  3067.         newver => $nver,
  3068.         repo => $repo,
  3069.         bundled => $b,
  3070.         precious => $p,
  3071.         pkg => $server_pkg,
  3072.     };
  3073.     }
  3074.     for my $pkg (sort keys %bypackage) {
  3075.     my $default;
  3076.     my @updates;
  3077.     my $p = $bypackage{$pkg};
  3078.     for my $rep (sort { $p->{$b}{newver} cmp $p->{$a}{newver} } keys %$p) {
  3079.         my $tmp = $default = $p->{$rep};
  3080.         push @updates, [@$tmp{qw(oldver newver repo)}] unless $tmp->{uptodate};
  3081.     }
  3082.     my $upgrade = $opts{install} ? 1 : 0;
  3083.         for (@updates) {
  3084.         $o->inform("$pkg $_->[0]: new version $_->[1] available in $_->[2]\n");
  3085.     }
  3086.     unless (@updates) {
  3087.         $o->inform("$pkg $default->{oldver}: up to date.\n");
  3088.         $upgrade &= $opts{force};
  3089.     }
  3090.     if ($upgrade) {
  3091.         my @k = keys %$p;
  3092.         my $ask = (@updates > 1 or @k > 1 and !@updates);
  3093.         if ($ask) {
  3094.         # Which one do they want to install?
  3095.         $o->inform(<<MANY);
  3096.  
  3097.    Note: $pkg version $default->{oldver} is available from more than one place.
  3098.    Which repository would you like to upgrade from?
  3099.  
  3100. MANY
  3101.         my @repos = map { $_->[2] } @updates;
  3102.         $o->print_pairs([ 1 .. @repos ], \@repos, '. ');
  3103.         $o->inform("\n");
  3104.         my $rep = $o->prompt(
  3105.             "Repository? [$default->{repo}] ",
  3106.             $default->{repo},
  3107.             [ 1 .. @repos, @repos ],
  3108.         );
  3109.         $rep = $repos[$rep - 1] if $rep =~ /^\d+$/;
  3110.         $default = $p->{$rep};
  3111.         }
  3112.         elsif (!@updates) {
  3113.         ($default) = values %$p;
  3114.         }
  3115.         if (not $default->{precious} or $default->{precious} && $opts{doprecious}) {
  3116.         $o->upgrade_pkg($default->{pkg}, \%opts);
  3117.         }
  3118.         else {
  3119.         $o->warn(<<END);
  3120. Use '-precious' to force precious packages to be upgraded.
  3121. END
  3122.         }
  3123.     }
  3124.     }
  3125.     1;
  3126. }
  3127.  
  3128. #============================================================================
  3129. # Profile:
  3130. # profile        # lists the profiles available on the repository
  3131. # profile N        # switches profiles
  3132. # profile add "name"    # adds a new profile
  3133. # profile delete N    # deletes the given profile
  3134. # profile describe N    # describes the given profile
  3135. # profile save        # saves the current state to the current profile
  3136. # profile restore    # restores the current profile
  3137. # profile rename    # renames the given profile
  3138. #============================================================================
  3139. sub smry_profiles { "manage PPM profiles" }
  3140. sub help_profiles { <<'END' }
  3141. profile -- Manage PPM Profiles
  3142.   Synopsis
  3143.      profile                     Lists profiles available on the repository
  3144.      profile <num>               Switches to the given profile
  3145.      profile add <name>          Creates a new profile on the repository
  3146.      profile delete <name or num>
  3147.                                  Deletes the given profile
  3148.      profile describe [name or num]
  3149.                                  Describes the current or given profile
  3150.      profile save                Saves the client state to the current profile
  3151.      profile restore             Restores the current profile
  3152.      profile rename <name or num> <name>
  3153.                                  Renames the given profile to <name>
  3154.  
  3155.   Description
  3156.     Profiles store information about packages that are installed on your
  3157.     system. If the 'profile-track' setting is enabled, your ASPN Profile
  3158.     will be updated with information about installed packages. Profiles
  3159.     allow you to easily migrate, reinstall, upgrade or restore PPM packages
  3160.     in one or more locations.
  3161.  
  3162.     To use profiles, you must have a license for ASPN. For license
  3163.     information, see http://www.ActiveState.com/ASPN/About. Disable profile
  3164.     tracking by setting 'profile-track=0'.
  3165. END
  3166. sub comp_profiles {
  3167.     my $o = shift;
  3168.     my ($word, $line, $start) = @_;
  3169.     my @words = $o->line_parsed($line);
  3170.     my $words = scalar @words;
  3171.     my @profs = PPM::UI::profile_list();
  3172.     my @cmds = ('add', 'delete', 'describe', 'save', 'restore', 'rename');
  3173.  
  3174.     if ($words == 1 or $words == 2 and $start != length($line)) {
  3175.     my @compls = (@cmds, 1 .. scalar @profs);
  3176.     return $o->completions($word, \@compls);
  3177.     }
  3178.     if ($words == 2 or $words == 3 and $start != length($line)) {
  3179.     return ()
  3180.       if ($o->completions($words[1], [qw(add save restore)])==1);
  3181.     return $o->completions($word, [1 .. scalar @profs])
  3182.       if ($o->completions($words[1], [qw(delete describe rename)])==1);
  3183.     }
  3184.     ();
  3185. }
  3186. sub run_profiles {
  3187.     my $o = shift;
  3188.     my @args = @_;
  3189.     trace(1, "PPM: profile @args\n");
  3190.  
  3191.     my $ok = PPM::UI::profile_list();
  3192.     unless ($ok->is_success) {
  3193.     $o->warn($ok->msg);
  3194.     return unless $ok->ok;
  3195.     }
  3196.     my @profiles = dictsort $ok->result_l;
  3197.     $ok = PPM::UI::profile_get();
  3198.     unless ($ok->is_success) {
  3199.     $o->warn($ok->msg);
  3200.     return unless $ok->ok;
  3201.     }
  3202.     my $profile = $ok->result;
  3203.     my $which = find_index($profile, 0, @profiles);
  3204.     if ($which < 0 and @profiles) {
  3205.     $profile = $profiles[0];
  3206.     PPM::UI::profile_set($profile);
  3207.     }
  3208.  
  3209.     if (@args) {
  3210.     # Switch to profile N:
  3211.     if ($args[0] =~ /^\d+$/) {
  3212.         my $num = $args[0];
  3213.         if (bounded(1, $num, scalar @profiles)) {
  3214.         my $profile = $profiles[$num-1];
  3215.         PPM::UI::profile_set($profile);
  3216.         }
  3217.         else {
  3218.         $o->warn("No such profile number '$num'.\n");
  3219.         return;
  3220.         }
  3221.     }
  3222.  
  3223.     # Describe profile N:
  3224.     elsif (matches($args[0], "des|cribe")) {
  3225.         my $num =     $args[1] =~ /^\d+$/ ? $args[1] :
  3226.             do {
  3227.                 my $n = find_index($args[1], 1, @profiles);
  3228.                 if ($n < 1) {
  3229.                 $o->warn("No such profile '$args[1]'.\n");
  3230.                 return;
  3231.                 }
  3232.                 $n;
  3233.             } if defined $args[1];
  3234.         my $prof;
  3235.         if (defined $num and $num =~ /^\d+$/) {
  3236.         if (bounded(1, $num, scalar @profiles)) {
  3237.             $prof = $profiles[$num - 1];
  3238.         }
  3239.         else {
  3240.             $o->warn("No such profile number '$num'.\n");
  3241.             return;
  3242.         }
  3243.         }
  3244.         elsif (defined $num) {
  3245.         $o->warn("Argument to '$args[0]' must be numeric; see 'help profile'.\n");
  3246.         return;
  3247.         }
  3248.         else {
  3249.         $prof = $profile;
  3250.         }
  3251.  
  3252.         my $res = PPM::UI::profile_info($prof);
  3253.         $o->warn($res->msg) and return unless $res->ok;
  3254.         my @res = $res->result_l;
  3255.         {
  3256.         my ($pkg, $version, $target);
  3257.         my $picture = <<'END';
  3258. [[[[[[[[[[[[[[[[[[[    [[[[[[[[[[[    [[[[[[[[[[[[[[[[[[[[[[
  3259. END
  3260.         ($pkg, $version, $target) = qw(PACKAGE VERSION TARGET);
  3261.         my $text = '';
  3262.         $text .= form($picture, $pkg, $version, $target)
  3263.           if @res;
  3264.         for my $entity (@res) {
  3265.             ($pkg, $version, $target) = @$entity;
  3266.             $version = "[$version]";
  3267.             $text .= form($picture, $pkg, $version, $target);
  3268.         }
  3269.         if (@res) {
  3270.             $o->inform("Describing Profile '$prof':\n");
  3271.         }
  3272.         else {
  3273.             $o->inform("Profile '$prof' is empty.\n");
  3274.         }
  3275.         $o->page($text);
  3276.         }
  3277.         return 1;
  3278.     }
  3279.  
  3280.     # Add a profile "name":
  3281.     elsif (matches($args[0], "a|dd")) {
  3282.         my $name = $args[1];
  3283.         if ($name) {
  3284.         # Note: do some heavy-duty error-checking; XXX
  3285.         PPM::UI::profile_add($name);
  3286.         PPM::UI::profile_save($name)
  3287.           if $o->conf('profile-track');
  3288.         PPM::UI::profile_set($name)
  3289.           unless $which >= 0;
  3290.         @profiles = PPM::UI::profile_list()->result_l;
  3291.         }
  3292.         else {
  3293.         $o->warn("Invalid use of 'add' command; see 'help profile'.\n");
  3294.         return;
  3295.         }
  3296.     }
  3297.  
  3298.     # Remove profile N:
  3299.     elsif (matches($args[0], "del|ete")) {
  3300.         my $num =    $args[1] =~ /^\d+$/ ? $args[1] :
  3301.             do {
  3302.                 my $n = find_index($args[1], 1, @profiles);
  3303.                 if ($n < 1) {
  3304.                 $o->inform("No such profile '$args[1]'.\n");
  3305.                 return;
  3306.                 }
  3307.                 $n;
  3308.             } if defined $args[1];
  3309.         if (defined $num and $num =~ /^\d+$/) {
  3310.         my $dead_profile = $profiles[$num-1];
  3311.         if (bounded(1, $num, scalar @profiles)) {
  3312.             PPM::UI::profile_del($dead_profile);
  3313.             @profiles = dictsort PPM::UI::profile_list()->result_l;
  3314.             if (@profiles and $dead_profile eq $profile) {
  3315.             $profile = $profiles[0];
  3316.             PPM::UI::profile_set($profile);
  3317.             }
  3318.             elsif (not @profiles) {
  3319.             $o->conf('profile-track', 0);
  3320.             PPM::UI::profile_set('');
  3321.             }
  3322.         }
  3323.         else {
  3324.             $o->warn("No such profile '$num'.\n");
  3325.             return;
  3326.         }
  3327.         }
  3328.         elsif (defined $num) {
  3329.         $o->warn(<<END);
  3330. Argument to '$args[0]' must be numeric; see 'help profile'.
  3331. END
  3332.         return;
  3333.         }
  3334.         else {
  3335.         $o->warn(<<END);
  3336. Invalid use of '$args[0]' command; see 'help profile'.
  3337. END
  3338.         return;
  3339. }
  3340.     }
  3341.  
  3342.     # Save current profile:
  3343.     elsif (matches($args[0], "s|ave")) {
  3344.         unless (@profiles) {
  3345.         $o->warn(<<END);
  3346. No profiles on the server. Use 'profile add' to add a profile.
  3347. END
  3348.         return;
  3349.         }
  3350.         unless ($which >= 0) {
  3351.         $o->warn(<<END);
  3352. No profile selected. Use 'profile <number>' to select a profile.
  3353. END
  3354.         return;
  3355.         }
  3356.         my $ok = PPM::UI::profile_save($profile);
  3357.         if ($ok->ok) {
  3358.         $o->inform("Profile '$profile' saved.\n");
  3359.         }
  3360.         else {
  3361.         $o->warn($ok->msg);
  3362.         return;
  3363.         }
  3364.         return 1;
  3365.     }
  3366.  
  3367.     # Rename profile:
  3368.     elsif (matches($args[0], "ren|ame")) {
  3369.         unless (@profiles) {
  3370.         $o->warn(<<END);
  3371. No profiles on the server. Use 'profile add' to add a profile.
  3372. END
  3373.         return;
  3374.         }
  3375.  
  3376.         # Determine the old name:
  3377.         my $num =    $args[1] =~ /^\d+$/ ? $args[1] :
  3378.             do {
  3379.                 my $n = find_index($args[1], 1, @profiles);
  3380.                 if ($n < 1) {
  3381.                 $o->warn("No such profile '$args[1]'.\n");
  3382.                 return;
  3383.                 };
  3384.                 $n;
  3385.             } if defined $args[1];
  3386.         my $oldprof;
  3387.         if (defined $num and $num =~ /^\d+$/) {
  3388.         if (bounded(1, $num, scalar @profiles)) {
  3389.             $oldprof = $profiles[$num - 1];
  3390.         }
  3391.         else {
  3392.             $o->warn("No such profile number '$num'.\n");
  3393.             return;
  3394.         }
  3395.         }
  3396.         elsif (defined $num) {
  3397.         $o->warn("Argument to '$args[0]' must be numeric; see 'help profile'.\n");
  3398.         return;
  3399.         }
  3400.         else {
  3401.         $o->warn("profile: invalid use of '$args[0]' command: see 'help profile'.\n");
  3402.         return;
  3403.         }
  3404.  
  3405.         # Validate the new name:
  3406.         my $newprof = $args[2];
  3407.         unless (defined $newprof and length($newprof)) {
  3408.         $newprof = '' unless defined $newprof;
  3409.         $o->warn(<<END);
  3410. Profile names must be non-empty: '$newprof' is not a valid name.
  3411. END
  3412.         return;
  3413.         }
  3414.  
  3415.         # Actually do it:
  3416.         my $ok = PPM::UI::profile_rename($oldprof, $newprof);
  3417.         unless ($ok->is_success) {
  3418.         $o->warn($ok->msg);
  3419.         return unless $ok->ok;
  3420.         }
  3421.         if ($profile eq $oldprof) {
  3422.         $profile = $newprof;
  3423.         PPM::UI::profile_set($profile);
  3424.         }
  3425.         @profiles = dictsort PPM::UI::profile_list()->result_l;
  3426.     }
  3427.  
  3428.     # Restore current profile:
  3429.     elsif (matches($args[0], "res|tore")) {
  3430.         unless (@profiles) {
  3431.         $o->warn(<<END);
  3432. No profiles on this server. Use 'profile add' to add a profile.
  3433. END
  3434.         return;
  3435.         }
  3436.         unless ($which >= 0) {
  3437.         $o->warn(<<END);
  3438. No profile selected. Use 'profile <number>' to select a profile.
  3439. END
  3440.         return;
  3441.         }
  3442.         my ($clean_packages, $dry) = (0, 0);
  3443.         my ($force, $follow) = (1, 0);
  3444.         {
  3445.         local @ARGV = @args;
  3446.         GetOptions('clean!' => \$clean_packages,
  3447.                'force!' => \$force,
  3448.                'follow!' => \$follow,
  3449.                'dryrun' => \$dry,
  3450.               );
  3451.         @args = @ARGV;
  3452.         }
  3453.         my $cb_inst = $dry ? \&dr_install : \&cb_install;
  3454.         my $cb_rm   = $dry ? \&dr_remove  : \&cb_remove ;
  3455.         my $ok = PPM::UI::profile_restore($profile, $cb_inst,
  3456.                           $cb_rm, $force, $follow,
  3457.                           $dry, $clean_packages);
  3458.         if ($ok->ok) {
  3459.         $o->cache_clear('query');
  3460.         $o->inform("Profile '$profile' restored.\n");
  3461.         }
  3462.         else {
  3463.         $o->warn($ok->msg);
  3464.         return;
  3465.         }
  3466.         return 1;
  3467.     }
  3468.  
  3469.     # Unrecognized subcommand:
  3470.     else {
  3471.         $o->warn("No such profile command '$args[0]'; see 'help profile'.\n");
  3472.         return;
  3473.     }
  3474.     }
  3475.     if (@profiles) {
  3476.     @profiles = dictsort @profiles;
  3477.     my $i = 0;
  3478.     $o->inform("Profiles:\n");
  3479.     my $profile = PPM::UI::profile_get()->result;
  3480.     for (@profiles) {
  3481.         $o->informf("%s%2d", $profile eq $profiles[$i] ? "*" : " ", $i + 1);
  3482.         $o->inform(". $_\n");
  3483.         $i++;
  3484.     }
  3485.     }
  3486.     elsif (defined $args[0] and matches($args[0], "del|ete")) {
  3487.     # assume that we just deleted the last profile
  3488.     $o->warn(<<END);
  3489. Profile deleted; no remaining profiles on the server.
  3490. END
  3491.     }
  3492.     else {
  3493.     $o->warn(<<END);
  3494. No profiles. Use 'profile add' to add a profile.
  3495. END
  3496.     }
  3497.     1;
  3498. }
  3499.  
  3500. #============================================================================
  3501. # Help-only topics:
  3502. #============================================================================
  3503. sub smry_prompt { "how to interpret the PPM prompt" }
  3504. sub help_prompt { <<'END' }
  3505. prompt -- information about the PPM3 prompt
  3506.   Description
  3507.     The PPM prompt can tell you six things:
  3508.  
  3509.     1)  The current repository;
  3510.  
  3511.     2)  The current target;
  3512.  
  3513.     3)  The last search you made on the current repository;
  3514.  
  3515.     4)  The last query you made on the current target;
  3516.  
  3517.     5)  The last package you described from this repository; and,
  3518.  
  3519.     6)  The last package you described from this target.
  3520.  
  3521.     To enable the prompt to tell you this information, you must set
  3522.     'prompt-context' to '1'. The following examples all assume this setting.
  3523.  
  3524.   Examples
  3525.     1   Repository and Target:
  3526.  
  3527.         Set 'prompt-context' The prompt will resemble:
  3528.  
  3529.             ppm:1:1> 
  3530.  
  3531.         In this case, the first '1' means that the first repository is
  3532.         selected. The second '1' means the first target is selected. You can
  3533.         prove this by adding another repository and switching to it:
  3534.  
  3535.             ppm:1:1> rep add TEMP http://my/repository
  3536.             Repositories:
  3537.               1. ActiveState Package Repository
  3538.             * 2. TEMP
  3539.             ppm:1:1> rep 2
  3540.             Repositories:
  3541.               1. ActiveState Package Repository
  3542.             * 2. TEMP
  3543.             ppm:2:1> 
  3544.  
  3545.         The same is true for targets. If you have multiple versions of Perl
  3546.         installed, when you swtich to a different target the second number
  3547.         reflects the change.
  3548.  
  3549.         If you delete all the repositories, the repository number changes to
  3550.         '?'. The same goes for targets. If either item is indicated by a
  3551.         question mark, you must configure a repository or target before
  3552.         proceeding.
  3553.  
  3554.     2   Search and Query:
  3555.  
  3556.         PPM stores searches and search results from in the current session.
  3557.         The prompt displays the search number:
  3558.  
  3559.             ppm:1:1> search Text
  3560.             [results displayed here]
  3561.             ppm:1:1:s1> 
  3562.  
  3563.         The 's1' indicates that the last search you performed can be viewed
  3564.         again by entering 'search 1'. Type 'search' with no arguments to
  3565.         view the list of cached searches:
  3566.  
  3567.             ppm:1:1:s1> search
  3568.             Search Result Sets:
  3569.             * 1. Text
  3570.  
  3571.         If you then enter 'search 1', you will see the same results as when
  3572.         you typed 'search Text' earlier. If you search for something else
  3573.         ('search Parse') then the number will change to 's2':
  3574.  
  3575.             ppm:1:1:s1> search Parse
  3576.             [results displayed here]
  3577.             ppm:1:1:s2>
  3578.  
  3579.         The same indicators apply to the query command. When you run a
  3580.         query, a numerical indicator displays the current query:
  3581.  
  3582.             ppm:1:1:s1> query PPM
  3583.             [results displayed here]
  3584.             ppm:1:1:s1:q1> 
  3585.  
  3586.         You can view the past queries with 'query', and view results by
  3587.         querying a particular number.
  3588.  
  3589.     3   Describe and Properties:
  3590.  
  3591.         When you use the describe command with the numerical switch (to view
  3592.         package information based on the package number in the last search
  3593.         or query), PPM sets that index to the current index. If you use the
  3594.         desribe command with the name switch, and the name is found within
  3595.         the current result, the index is set to the current one. If no
  3596.         package is found, PPM creates a new search or query on-the-fly, and
  3597.         sets it as the current search or query.
  3598.  
  3599.         For example:
  3600.  
  3601.             ppm:1:1> search Text
  3602.             1. Convert-Context  [0.501]     an Attributed Text data type
  3603.             2. gettext          [1.01]      message handling functions
  3604.             3. HTML-FromText    [1.005]     mark up text as HTML
  3605.             4. HTML-Subtext     [1.03]      Perform text substitutions on an HTML
  3606.                                             template
  3607.             5. Locale-Maketext  [0.18]      framework for software localization
  3608.             ppm:1:1:s1>
  3609.  
  3610.             ppm:1:1:s1> describe 1
  3611.             ====================
  3612.             Package 1:
  3613.                 Name: Convert-Context
  3614.              Version: 0.501
  3615.               Author: Martin Schwartz (martin@nacho.de)
  3616.             Abstract: an Attributed Text data type
  3617.             Implementations:
  3618.                    1. i686-linux-thread-multi
  3619.                    2. MSWin32-x86-multi-thread
  3620.                    3. sun4-solaris-thread-multi
  3621.             ====================
  3622.             ppm:1:1:s1:sp1> 
  3623.  
  3624.         The last prompt has an extra 'sp1'. That stands for 'search package
  3625.         1', and it means that PPM considers 'Convert-Context' to be the
  3626.         default package. If you now type 'describe' or 'install' with no
  3627.         arguments, PPM will apply your command to this package.
  3628.  
  3629.         If you go back to where you had no default package selected:
  3630.  
  3631.             ppm:1:1> search Text
  3632.             1. Convert-Context  [0.501]     an Attributed Text data type
  3633.             2. gettext          [1.01]      message handling functions
  3634.             3. HTML-FromText    [1.005]     mark up text as HTML
  3635.             4. HTML-Subtext     [1.03]      Perform text substitutions on an HTML
  3636.                                             template
  3637.             5. Locale-Maketext  [0.18]      framework for software localization
  3638.             ppm:1:1:s1>
  3639.  
  3640.         ...and you describe 'Locale-Maketext', you will see this:
  3641.  
  3642.             ppm:1:1:s1> describe Locale-Maketext
  3643.             ====================
  3644.                 Name: Locale-Maketext
  3645.              Version: 0.18
  3646.               Author: Sean M. Burke (sburke@cpan.org)
  3647.             Abstract: framework for software localization
  3648.             Prerequisites:
  3649.                    1. I18N-LangTags 0.13
  3650.             Implementations:
  3651.                    1. i686-linux-thread-multi
  3652.                    2. MSWin32-x86-multi-thread
  3653.                    3. sun4-solaris-thread-multi
  3654.             ====================
  3655.             ppm:1:1:s1:sp5>
  3656.  
  3657.         Notice that the correct package got selected, even though you
  3658.         specified it by name.
  3659.  
  3660.     This behaviour also applies to the query and properties commands.
  3661.  
  3662.   See Also
  3663.     describe, properties, query, search
  3664. END
  3665.  
  3666. sub run_quickstart  { $_[0]->help('quickstart') }
  3667. sub smry_quickstart { "a crash course in using PPM" }
  3668. sub help_quickstart { <<'END' }
  3669. quickstart -- a beginners' guide to PPM3
  3670.   Description
  3671.     PPM (Programmer's Package Manager) is a utility for managing software
  3672.     "packages". A package is a modular extension for a language or a
  3673.     software program. Packages reside in repositories. PPM can use three
  3674.     types of repositories:
  3675.  
  3676.      1) A directory on a CD-ROM or hard drive in your computer
  3677.      2) A website
  3678.      3) A remote Repository Server (such as ASPN)
  3679.  
  3680.     Common Commands:
  3681.  
  3682.     To view PPM help:
  3683.  
  3684.       help
  3685.       help <command>
  3686.  
  3687.     To view the name of the current repository:
  3688.  
  3689.       repository
  3690.  
  3691.     To search the current repository:
  3692.  
  3693.       search <keywords>
  3694.  
  3695.     To install a package:
  3696.  
  3697.       install <package_name>
  3698.  
  3699.     Most commands can be truncated; as long as the command is unambiguous,
  3700.     PPM will recognize it. For example, 'repository add foo" can be entered
  3701.     as 'rep add foo'.
  3702.  
  3703.     PPM features user profiles, which store information about installed
  3704.     packages. Profiles are stored as part of your ASPN account; thus, you
  3705.     can easily maintain package profiles for different languages, or
  3706.     configure one machine with your favorite packages, and then copy that
  3707.     installation to another machine by accessing your ASPN profile.
  3708.  
  3709.     For more information, type 'help profile' at the PPM prompt.
  3710. END
  3711.  
  3712. sub smry_ppm_migration { "guide for those familiar with PPM" }
  3713. sub help_ppm_migration { <<'END' }
  3714. ppm migration -- PPM Migration Guide
  3715.   Description
  3716.     Those familiar with PPM version 2 should appreciate the extended
  3717.     functionality of PPM version 3, including the command-line history,
  3718.     autocomplete and profiles. Some PPM version 2 commands are different in
  3719.     PPM version 3. Examples of command changes include:
  3720.  
  3721.     1   Adding a repository
  3722.  
  3723.         PPM2:
  3724.  
  3725.           set repository my_repository http://my/repository
  3726.  
  3727.         PPM3:
  3728.  
  3729.           repository add my_repository http://my/repository
  3730.  
  3731.     2   Removing a repository
  3732.  
  3733.         PPM2:
  3734.  
  3735.           set repository --remove my_repository
  3736.  
  3737.         PPM3:
  3738.  
  3739.           repository del my_repository
  3740.  
  3741.     3   Setting the temporary directory
  3742.  
  3743.         PPM2:
  3744.  
  3745.           set build DIRECTORY
  3746.  
  3747.         PPM3
  3748.  
  3749.           set tempdir DIRECTORY
  3750.  
  3751.     4   Setting frequency of download updates
  3752.  
  3753.         PPM2:
  3754.  
  3755.           set downloadstatus NUMBER
  3756.  
  3757.         PPM3:
  3758.  
  3759.           set download-chunksize NUMBER
  3760.  
  3761.     5   Changing the installation root directory:
  3762.  
  3763.         PPM2:
  3764.  
  3765.           set root DIRECTORY
  3766.  
  3767.         PPM3:
  3768.  
  3769.           target set root DIRECTORY
  3770.  
  3771.     6   Listing all installed packages:
  3772.  
  3773.         PPM2:
  3774.  
  3775.           query
  3776.  
  3777.         PPM3:
  3778.  
  3779.           query *
  3780.  
  3781.     7   Listing all packages on server:
  3782.  
  3783.         PPM2:
  3784.  
  3785.           search
  3786.  
  3787.         PPM3:
  3788.  
  3789.           search *
  3790. END
  3791.  
  3792. sub smry_unicode { "notes about unicode author names" }
  3793. sub help_unicode { <<'END' }
  3794. unicode -- Notes About Unicode Author Names
  3795.   Description
  3796.     CPAN author names are defined to be in Unicode. Unicode is an
  3797.     international standard ISO 10646, defining the *Universal Character Set
  3798.     (UCS)*. UCS contains all characters of all other character set
  3799.     standards. For more information about Unicode, see
  3800.     http://www.unicode.org/.
  3801.  
  3802.     The CPAN authors website is located at your local CPAN mirror under
  3803.     /authors/00whois.html. For example, you can view it at
  3804.     http://www.cpan.org/authors/00whois.html. This page can be rendered by
  3805.     Mozilla 0.9.8 and Internet Explorer 5.0, but you may have to install
  3806.     extra language packs to view all the author names.
  3807.  
  3808.     By default, PPM3 renders all characters as Latin1 when it prints them to
  3809.     your console. Characters outside the Latin1 range (0-255) are not
  3810.     printed at all.
  3811.  
  3812.     If your console can render UTF-8 characters, you can tell PPM3 not to
  3813.     recode characters by using one of the following environment variables:
  3814.  
  3815.     *   LC_ALL
  3816.  
  3817.     *   LC_CTYPE
  3818.  
  3819.     *   LANG
  3820.  
  3821.     *   PPM_LANG
  3822.  
  3823.     PPM3 requires one of these environment variables to contain the string
  3824.     'UTF-8'. For example, the following setting make PPM3 print
  3825.     beautifully-formatted authors in RedHat Linux 7.2 (assumes you're using
  3826.     a Bourne shell):
  3827.  
  3828.       $ PPM_LANG='en_US.UTF-8' xterm -u8 -e ppm3
  3829.  
  3830.     Linux and Solaris users should refer to xterm for more information about
  3831.     setting up xterm to display UTF-8 characters.
  3832. END
  3833.  
  3834. #============================================================================
  3835. # Utility Functions
  3836. #============================================================================
  3837. sub sort_fields { qw(name title author abstract version repository) }
  3838. sub sort_pkgs {
  3839.     my $o = shift;
  3840.     my $field = lc shift;
  3841.     my @pkgs = @_;
  3842.     my $targ = $o->conf('target');
  3843.     my $filt = sub { $_[0]->getppd_obj($targ)->result->$field };
  3844.     if ($field eq 'name') {
  3845.     return dictsort $filt, @pkgs;
  3846.     }
  3847.     if ($field eq 'title') {
  3848.     return dictsort $filt, @pkgs;
  3849.     }
  3850.     if ($field eq 'author') {
  3851.     return dictsort $filt, @pkgs;
  3852.     }
  3853.     if ($field eq 'abstract') {
  3854.     return dictsort $filt, @pkgs;
  3855.     }
  3856.     if ($field eq 'repository') {
  3857.     return dictsort sub { $_[0]->repository->name }, @pkgs;
  3858.     }
  3859.     if ($field eq 'version') {
  3860.     return sort {
  3861.         my $pa = $a->getppd_obj($targ)->result;
  3862.         my $pb = $b->getppd_obj($targ)->result;
  3863.         $pb->uptodate($pa->version_osd) <=> $pa->uptodate($pb->version_osd)
  3864.     } @pkgs;
  3865.     }
  3866.     @pkgs;
  3867. }
  3868.  
  3869. sub find_index {
  3870.     my $entry = shift || '';
  3871.     my $index = shift;
  3872.     $index = 0 unless defined $index;
  3873.     for (my $i=0; $i<@_; $i++) {
  3874.     return $index + $i if $entry eq $_[$i];
  3875.     }
  3876.     return $index - 1;
  3877. }
  3878.  
  3879. sub bounded {
  3880.     my $lb = shift;
  3881.     my $d = shift;
  3882.     my $ub = shift;
  3883.     return ($d >= $lb and $d <= $ub);
  3884. }
  3885.  
  3886. sub dictsort(@) {
  3887.     my $o = shift if eval { $_[0]->isa("PPMShell") };
  3888.     my $filt = ref($_[0]) eq 'CODE' ? shift @_ : undef;
  3889.     return map { $_->[0] }
  3890.        sort { lc $a->[1] cmp lc $b->[1] }
  3891.        map { [ $_, $filt ? $filt->($_) : $_ ] } @_;
  3892. }
  3893.  
  3894. sub path_under {
  3895.     my $path = shift;
  3896.     my $cmp  = shift;
  3897.     if ($^O eq 'MSWin32') {
  3898.     $path =~ s#\\#/#g;
  3899.     $cmp  =~ s#\\#/#g;
  3900.     return $path =~ /^\Q$cmp\E/i;
  3901.     }
  3902.     else {
  3903.     return $path =~ /^\Q$cmp\E/;
  3904.     }
  3905. }
  3906.  
  3907. sub prompt_str {
  3908.     my $o = shift;
  3909.  
  3910.     # Hack: set the pager here, instead of in settings_setkey()
  3911.     $o->{API}{pager} = $o->conf('pager');
  3912.  
  3913.     my @search_results = $o->cache_sets('search');
  3914.     my $search_result_current = $o->cache_set_current('search');
  3915.     my $search_result_index = $o->cache_set_index('search');
  3916.     my @query_results = $o->cache_sets('query');
  3917.     my $query_result_current = $o->cache_set_current('query');
  3918.     my $query_result_index = $o->cache_set_index('query');
  3919.  
  3920.     # Make sure a profile is selected if they turned tracking on.
  3921.     my $profile_track = $o->conf('profile-track');
  3922.     my $profile       = PPM::UI::profile_get()->result;
  3923.     $o->setup_profile()
  3924.     if $profile_track and not $profile and $o->mode eq 'SHELL';
  3925.  
  3926.     my @targs = PPM::UI::target_list()->result_l;
  3927.     if (@targs and not find_index($o->conf('target'), 1, @targs)) {
  3928.     $o->conf('target', $targs[0]);
  3929.     }
  3930.  
  3931.     if ($o->conf('prompt-context')) {
  3932.     my ($targ, $rep, $s, $sp, $q, $qp);
  3933.  
  3934.     if ($o->conf('prompt-verbose')) {
  3935.         my $sz = $o->conf('prompt-slotsize');
  3936.         $targ = substr($o->conf('target'), 0, $sz);
  3937.         $rep  = substr($o->conf('repository'), 0, $sz);
  3938.  
  3939.         my $sq_tmp = $o->cache_set('search', undef, 'query');
  3940.         my $ss_tmp = $o->cache_set('search');
  3941.         my $sp_tmp = $o->cache_entry('search');
  3942.         $s = (defined $sq_tmp)
  3943.           ? ":" . substr($sq_tmp, 0, $sz)
  3944.           : "";
  3945.         $sp = ($s and defined $sp_tmp and
  3946.            bounded(0, $search_result_index, $#$ss_tmp))
  3947.           ? ":" . substr($sp_tmp->name, 0, $sz)
  3948.           : "";
  3949.  
  3950.         my $qq_tmp = $o->cache_set('query', undef, 'query');
  3951.         my $qs_tmp = $o->cache_set('query');
  3952.         my $qp_tmp = $o->cache_entry('query');
  3953.         $q = (defined $qq_tmp)
  3954.           ? ":" . substr($qq_tmp, 0, $sz)
  3955.           : "";
  3956.         $qp = ($q and defined $qp_tmp and
  3957.            bounded(0, $query_result_index, $#$qs_tmp))
  3958.           ? ":" . substr($qp_tmp->name, 0, $sz)
  3959.           : "";
  3960.     }
  3961.     else {
  3962.         # Target and Repository:
  3963.         $targ = find_index($o->conf('target'), 1, @targs);
  3964.         $targ = '?' if $targ == 0;
  3965.     
  3966.         # Search number & package:
  3967.         $s = @search_results ? ":s".($search_result_current + 1) : "";
  3968.         my $sp_tmp = $o->cache_set('search');
  3969.         $sp = ($s and defined $sp_tmp and 
  3970.            bounded(0, $search_result_index, $#$sp_tmp))
  3971.           ? ":sp".($search_result_index + 1)
  3972.           : "";
  3973.     
  3974.         # Query number & package:
  3975.         $q = @query_results ? ":q".($query_result_current + 1) : "";
  3976.         my $qp_tmp = $o->cache_set('query');
  3977.         $qp = ($q and defined $qp_tmp and
  3978.            bounded(0, $query_result_index, $#$qp_tmp))
  3979.           ? ":qp".($query_result_index + 1)
  3980.           : "";
  3981.     }
  3982.     return "ppm:$targ$s$sp$q$qp> ";
  3983.     }
  3984.     else {
  3985.     return "ppm> ";
  3986.     }
  3987. }
  3988.  
  3989. {
  3990.     # Weights for particular fields: these are stored in percentage of the
  3991.     # screen width, based on the number of columns they use on an 80 column
  3992.     # terminal. They also have a minimum and maximum.
  3993.     use constant MIN    => 0;
  3994.     use constant MAX    => 1;
  3995.     my %weight = (
  3996.     name     => [12, 20],
  3997.     title    => [12, 20],
  3998.     abstract => [12, 20],
  3999.     author   => [12, 20],
  4000.     repository => [12, 20],
  4001.     version  => [ 4,  9],
  4002.     );
  4003.     my %meth = (
  4004.     name     => 'name',
  4005.     title    => 'title',
  4006.     version  => 'version',
  4007.     abstract => 'abstract',
  4008.     author   => 'author',
  4009.     repository => sub {
  4010.         my $o = shift;
  4011.         my $rep = $o->repository or return "Installed";
  4012.         my $name = $rep->name;
  4013.         my $id   = $o->id || $name;
  4014.         my $loc  = $rep->location;
  4015.         "$name [$loc]"
  4016.     },
  4017.     );
  4018.     # These are Text::Autoformat justification marks. They're actually used to
  4019.     # build a printf() format string, since it's so much more efficient for a
  4020.     # non-line-wrapping case.
  4021.     my %just = (
  4022.     name     => '<',
  4023.     title    => '<',
  4024.     abstract => '<',
  4025.     author   => '<',
  4026.     repository => '<',
  4027.     version  => '>',
  4028.     );
  4029.     my %plus = (
  4030.     name     => '0',
  4031.     title    => '0',
  4032.     abstract => '0',
  4033.     author   => '0',
  4034.     repository => '0',
  4035.     version  => '2',
  4036.     );
  4037.     my %filt = (
  4038.     version => q{"[$_]"},
  4039.     );
  4040.     sub picture_optimized {
  4041.     my $o = shift;
  4042.     my @items = @{shift(@_)};
  4043.     unless ($o->conf('fields')) {
  4044.         my $m = $o->setmode('SILENT');
  4045.         $o->conf('fields', '', 1);
  4046.         $o->setmode($m);
  4047.     }
  4048.     my @fields = split ' ', $o->conf('fields');
  4049.     $_ = lc $_ for @fields;
  4050.     my (%max_width, %width);
  4051.     my $cols = $o->termsize->{cols};
  4052.     for my $f (@fields) {
  4053.         my $meth = $meth{$f};
  4054.         $max_width{$f} = max { length($_->$meth) } @items;
  4055.         $max_width{$f} += $plus{$f};
  4056.         $width{$f} = $max_width{$f} / 80 * $cols;
  4057.         my $max_f  = $weight{$f}[MAX] / 80 * $cols;
  4058.         my $min_f  = $weight{$f}[MIN];
  4059.         my $gw     = $width{$f};
  4060.         $width{$f} = (
  4061.         $width{$f} > $max_width{$f} ? $max_width{$f} :
  4062.         $width{$f} > $max_f         ? $max_f         :
  4063.         $width{$f} < $min_f         ? $min_f         : $width{$f}
  4064.         );
  4065.     }
  4066.     my $right = $fields[-1];
  4067.     my $index_sz = length( scalar(@items) ) + 3; # index spaces
  4068.     my $space_sz = @fields + 1; # separator spaces
  4069.     my $room = $cols - $index_sz - $space_sz;
  4070.     $width{$right} = $room - sum { $width{$_} } @fields[0 .. $#fields-1];
  4071.     while ($width{$right} > $max_width{$right}) {
  4072.         my $smallest;
  4073.         my $n;
  4074.         for my $k (@fields[0 .. $#fields-1]) {
  4075.         my $max = $max_width{$k};
  4076.         my $sz  = $width{$k};
  4077.         $smallest = $k, $n = $max - $sz if $max - $sz > $n;
  4078.         }
  4079.         $width{$right}--;
  4080.         $width{$smallest}++;
  4081.     }
  4082.     while ($width{$right} < $weight{$right}[MIN]) {
  4083.         my $biggest;
  4084.         my $n;
  4085.         for my $k (@fields[0 .. $#fields-1]) {
  4086.         my $max = $max_width{$k};
  4087.         my $sz  = $width{$k};
  4088.         $biggest = $k, $n = $max - $sz if $max - $sz < $n;
  4089.         }
  4090.         $width{$right}++;
  4091.         $width{$biggest}--;
  4092.     }
  4093.     my $picture;
  4094.     $picture = "\%${index_sz}s "; # printf picture
  4095.     $picture .= join ' ', map {
  4096.         my $w = $width{$_};
  4097.         my $c = $just{$_};
  4098.         my $pad = $c eq '>' ? '' : '-';
  4099.         "\%${pad}${w}s" # printf picture
  4100.     } @fields;
  4101.     ($picture, \@fields, [@width{@fields}]);
  4102.     }
  4103.  
  4104.     sub print_formatted {
  4105.     my $o = shift;
  4106.     my $targ = $o->conf('target');
  4107.     my @items = map { $_->getppd_obj($targ)->result } @{shift(@_)};
  4108.     my $selected = shift;
  4109.     my $format;
  4110.  
  4111.     # Generate a picture and a list of fields for Text::Autoformat:
  4112.     my (@fields, %width);
  4113.     my ($picture, $f, $w) = $o->picture_optimized(\@items);
  4114.     $picture .= "\n";
  4115.     @fields = @$f;
  4116.     @width{@fields} = @$w;
  4117.  
  4118.     # The line-breaking sub: use '~' as hyphenation signal
  4119.     my $wrap = sub {
  4120.         my ($str, $maxlen, $width) = @_;
  4121.         my $field = substr($str, 0, $maxlen - 1) . '~';
  4122.         my $left  = substr($str, $maxlen - 1);
  4123.         ($field, $left);
  4124.     };
  4125.  
  4126.     my $lines = 0;
  4127.     my $i = 1;
  4128.     my @text;
  4129.     my %seen;
  4130.     for my $pkg (@items) {
  4131.         my $star = (defined $selected and $selected == $i - 1) ? "*" : " ";
  4132.         my $num  = "$star $i.";
  4133.         my @vals = (
  4134.         map {
  4135.             my $field  = $_;
  4136.             my $method = $meth{$field};
  4137.             local $_   = $pkg->$method;
  4138.             my $val = defined $filt{$field} ? eval $filt{$field} : $_;
  4139.             ($val) = $wrap->($val, $width{$field})
  4140.                 if length $val > $width{$field};
  4141.             $val;
  4142.         }
  4143.         @fields
  4144.         );
  4145. #        my $key = join '', @vals;
  4146. #        if (exists $seen{$key}) {
  4147. #        my $index = $seen{$key};
  4148. #        substr($text[$index], 0, 1) = '+';
  4149. #        next;
  4150. #        }
  4151. #        $seen{$key} = $i - 1;
  4152.         (my $inc = sprintf $picture, $num, @vals) =~ s/[ ]+$//;
  4153.         push @text, $inc;
  4154.         $i++;
  4155.     }
  4156.  
  4157.     # And, page it.
  4158.     $o->page(join '', @text);
  4159.     }
  4160. }
  4161.  
  4162. sub tree_pkg {
  4163.     my $o = shift;
  4164.     my @rlist = $o->reps_on;
  4165.     my $tar = $o->conf('target');
  4166.     my $pkg = shift;
  4167.     my $ppd;
  4168.     if (eval { $pkg->isa('PPM::Package') }) {
  4169.     $ppd = $pkg->getppd_obj($tar)->result;
  4170.     }
  4171.     else {
  4172.     my ($s, $i) = $o->cache_find('search', $pkg);
  4173.     if ($i >= 0) {
  4174.         $ppd = $o->cache_entry('search', $i, $s);
  4175.     } 
  4176.     else {
  4177.         my $ok = PPM::UI::describe(\@rlist, $tar, $pkg);
  4178.         unless ($ok->is_success) {
  4179.         $o->warn($ok->msg);
  4180.         return unless $ok->ok;
  4181.         }
  4182.         $ppd = $ok->result->getppd_obj($tar)->result;
  4183.     }
  4184.     }
  4185.  
  4186.     my $pad = "\n";
  4187.     $o->inform($ppd->name, " ", $ppd->version);
  4188.     $o->Tree(\@rlist, $tar, $ppd->name, $pad, {});
  4189.     $o->inform($pad);
  4190. }
  4191.  
  4192. my ($VER, $HOR, $COR, $TEE, $SIZ) = ('|', '_', '\\', '|', ' ');
  4193.  
  4194. sub Tree {
  4195.     my $o = shift;
  4196.     my $reps = shift;
  4197.     my $tar = shift;
  4198.     my $pkg = shift;
  4199.     my $ind = shift;
  4200.     my $seen = shift;
  4201.     my $pad = $ind . "  " . $VER;
  4202.  
  4203.     my $ppd;
  4204.     if (exists $seen->{$pkg}) {
  4205.     $ppd = $seen->{$pkg};
  4206.     }
  4207.     else {
  4208.     my ($s, $i) = $o->cache_find('search', $pkg);
  4209.     if ($i >= 0) {
  4210.         $ppd = $o->cache_entry('search', $i, $s);
  4211.     }
  4212.     else {
  4213.         my $ok = PPM::UI::describe($reps, $tar, $pkg);
  4214.         unless ($ok->is_success) {
  4215.         $o->inform(" -- package not found; skipping tree");
  4216.         return 0 unless $ok->ok;
  4217.         }
  4218.         $ppd = $ok->result;
  4219.     }
  4220.     $ppd->make_complete($tar);
  4221.     $ppd = $ppd->getppd_obj($tar)->result;
  4222.     $seen->{$pkg} = $ppd;
  4223.     }
  4224.  
  4225.     my @impls   = $ppd->implementations;
  4226.     return 0 unless @impls;
  4227.     my @prereqs = $impls[0]->prereqs;
  4228.     return 0 unless @prereqs;
  4229.     my $nums = scalar @prereqs;
  4230.  
  4231.     for (1..$nums) {
  4232.     my $doneblank = 0;
  4233.     my $pre = $prereqs[$_-1];
  4234.     my $txt = $pre->name . " " . $pre->version;
  4235.     if ($_ == $nums) {
  4236.         substr($pad, -1) = $COR;
  4237.         $o->inform($pad, "$HOR$HOR", $txt);
  4238.         substr($pad, -1) = ' ';
  4239.     }
  4240.     else {
  4241.         substr($pad, -1) = $TEE;
  4242.         $o->inform($pad, "$HOR$HOR", $txt);
  4243.         substr($pad, -1) = $VER;
  4244.     }
  4245.     if ($o->Tree($reps, $tar, $pre->name, $pad, $seen) != 0 and
  4246.         $doneblank == 0) {
  4247.         $o->inform($pad); ++$doneblank;
  4248.     }
  4249.     }
  4250.     return $nums;
  4251. }
  4252.  
  4253. sub describe_pkg {
  4254.     my $o = shift;
  4255.     my $pkg = shift;
  4256.     my ($extra_keys, $extra_vals) = (shift || [], shift || []);
  4257.     my $n; 
  4258.  
  4259.     # Get the PPM::PPD object out of the PPM::Package object.
  4260.     my $pkg_des = $pkg->describe($o->conf('target'))->result;
  4261.  
  4262.     # Basic information:
  4263.     $n = $o->print_pairs(
  4264.     [qw(Name Version Author Title Abstract), @$extra_keys],
  4265.     [(map { $pkg_des->$_ } qw(name version author title abstract)),
  4266.      @$extra_vals],
  4267.     undef,    # separator
  4268.     undef,    # left
  4269.     undef,    # indent
  4270.     undef,    # length
  4271.     1,    # wrap (yes, please wrap)
  4272.     );
  4273.  
  4274.     # The repository:
  4275.     if (my $rep = $pkg_des->repository) {
  4276.     $o->print_pairs(
  4277.         ["Location"],
  4278.         [$rep->name],
  4279.         undef,    # separator
  4280.         undef,    # left
  4281.         undef,    # indent
  4282.         $n,        # length
  4283.         1,        # wrap
  4284.     );
  4285.     }
  4286.     
  4287.     # Prerequisites:
  4288.     my @impls = grep { $_->architecture } $pkg_des->implementations;
  4289.     my @prereqs = @impls ? $impls[0]->prereqs : ();
  4290.     $o->inform("Prerequisites:\n") if @prereqs;
  4291.     $o->print_pairs(
  4292.     [ 1 .. @prereqs ],
  4293.     [ map { $_->name . ' ' . $_->version} @prereqs ],
  4294.     '. ',    # separator
  4295.     undef,    # left
  4296.     undef,    # indent
  4297.     $n,    # length
  4298.     0,    # wrap (no, please don't wrap)
  4299.     );
  4300.     
  4301.     # Implementations:
  4302.     $o->inform("Available Platforms:\n") if @impls;
  4303.     my @impl_strings;
  4304.     for (@impls) {
  4305.     my $arch  = $_->architecture;
  4306.     my $os    = $_->os;
  4307.     my $osver = $_->osversion;
  4308.     my $str   = $arch;
  4309.     $osver    =~ s/\Q(any version)\E//g;
  4310.     if ($os and $osver) {
  4311.         $str .= ", $os $osver";
  4312.     }
  4313.     push @impl_strings, $str;
  4314.     }
  4315.     @impl_strings = dictsort @impl_strings;
  4316.     $o->print_pairs(
  4317.     [ 1 .. @impls ],
  4318.     [ @impl_strings ],
  4319.     '. ', undef, undef, $n
  4320.     );
  4321. }
  4322.  
  4323. sub remove_pkg {
  4324.     my $o = shift;
  4325.     my $package = shift;
  4326.     my $target = $o->conf('target');
  4327.     my $force = shift;
  4328.     my $quell_clear = shift;
  4329.     my $verbose = $o->conf('remove-verbose');
  4330.     my $ok = PPM::UI::remove($target, $package, $force, sub { $o->cb_remove(@_) }, $verbose);
  4331.     unless ($ok->is_success) {
  4332.     $o->warn($ok->msg);
  4333.     return 0 unless $ok->ok;
  4334.     }
  4335.     else {
  4336.     $o->warn_profile_change($ok);
  4337.     }
  4338.     $o->cache_clear('query') if ($ok->ok and not $quell_clear);
  4339.     1;
  4340. }
  4341.  
  4342. sub upgrade_pkg {
  4343.     push @_, 'upgrade';
  4344.     goto &install_pkg;
  4345. }
  4346. sub install_pkg {
  4347.     my $o = shift;
  4348.     my $pkg = shift;
  4349.     my $opts = shift;
  4350.     my $action = shift;
  4351.     my $quell_clear = shift;
  4352.     $action = 'install' unless defined $action;
  4353.  
  4354.     # Find the package:
  4355.     while (1) {
  4356.     # 1. Return if they specified a full filename or URL:
  4357.     last if PPM::UI::is_pkg($pkg);
  4358.  
  4359.     # 2. Check if whatever they specified returns 1 search result:
  4360.     my $search =
  4361.       PPM::UI::search([$o->reps_on], $o->conf('target'), $pkg, 
  4362.               $o->conf('case-sensitivity'));
  4363.     unless ($search->is_success) {
  4364.         $o->warn($search->msg);
  4365.         return unless $search->ok;
  4366.     }
  4367.     my @ret = $search->result_l;
  4368.     if (@ret > 1) {
  4369.         $o->warn(<<END);
  4370. Searching for '$pkg' returned multiple results. Using 'search' instead...
  4371. END
  4372.         $o->run_search($pkg);
  4373.         return;
  4374.     }
  4375.     elsif (not @ret) {
  4376.         $o->warn(<<END);
  4377. Searching for '$pkg' returned no results. Try a broader search first.
  4378. END
  4379.         return;
  4380.     }
  4381.     $pkg = $ret[0]->name;
  4382.     last;
  4383.     }
  4384.  
  4385.     my $cb = (
  4386.     $opts->{dryrun}
  4387.     ? $action eq 'install' ? \&dr_install : \&dr_upgrade
  4388.     : $action eq 'install' ? \&cb_install : \&cb_upgrade
  4389.     );
  4390.  
  4391.     # Now, do the install
  4392.     my $ok;
  4393.     my @rlist = $o->reps_on;
  4394.     my $targ = $o->conf('target');
  4395.  
  4396.     if ($action eq 'install') {
  4397.     $opts->{verbose} = $o->conf('install-verbose');
  4398.     my $prop = PPM::UI::properties($targ, $pkg);
  4399.     my $pkgname = ref $pkg ? eval { $pkg->name } || $pkg : $pkg;
  4400.     $o->inform("Note: Package '$pkgname' is already installed.\n")
  4401.         if $prop->ok;
  4402.     $ok = PPM::UI::install(\@rlist, $targ, $pkg, $opts, sub {$o->$cb(@_)});
  4403.     }
  4404.     else {
  4405.     $opts->{verbose} = $o->conf('upgrade-verbose');
  4406.     $ok = PPM::UI::upgrade(\@rlist, $targ, $pkg, $opts, sub {$o->$cb(@_)});
  4407.     }
  4408.  
  4409.     unless ($ok->is_success) {
  4410.     $o->warn($ok->msg);
  4411.     return unless $ok->ok;
  4412.     }
  4413.     else {
  4414.     $o->warn_profile_change($ok);
  4415.     $o->cache_clear('query') unless $quell_clear;
  4416.     }
  4417.     1;
  4418. }
  4419.  
  4420. # The dry run callback; just prints out package name and version:
  4421. sub dr_install {
  4422.     my $o = shift;
  4423.     my $pkg = shift;
  4424.     my $version = shift;
  4425.     my $target_name = shift;
  4426.     $o->inform(<<END);
  4427. Dry run install '$pkg' version $version in $target_name.
  4428. END
  4429. }
  4430.  
  4431. sub dr_upgrade {
  4432.     my $o = shift;
  4433.     my $pkg = shift;
  4434.     my $version = shift;
  4435.     my $target_name = shift;
  4436.     $o->inform(<<END);
  4437. Dry run upgrade '$pkg' version $version in $target_name.
  4438. END
  4439. }
  4440.  
  4441. sub dr_remove {
  4442.     my $o = shift;
  4443.     my $pkg = shift;
  4444.     my $version = shift;
  4445.     my $target_name = shift;
  4446.     $o->inform(<<END);
  4447. Dry run remove '$pkg' version $version from $target_name.
  4448. END
  4449. }
  4450.  
  4451. sub cb_remove {
  4452.     my $o = shift;
  4453.     my $pkg = shift;
  4454.     my $version = shift;
  4455.     my $target_name = shift;
  4456.     my $status = shift;
  4457.     if ($status eq 'COMPLETE') {
  4458.     $o->inform(
  4459.         "Successfully removed $pkg version $version from $target_name.\n"
  4460.     )
  4461.     }
  4462.     else {
  4463.     $o->inform(<<END);
  4464. $SEP
  4465. Remove '$pkg' version $version from $target_name.
  4466. $SEP
  4467. END
  4468.     }
  4469. }
  4470.  
  4471. sub cb_install {
  4472.     my $o = shift;
  4473.     unshift @_, $o, 'install';
  4474.     &cb_status;
  4475. }
  4476.  
  4477. sub cb_upgrade {
  4478.     my $o = shift;
  4479.     unshift @_, $o, 'upgrade';
  4480.     &cb_status;
  4481. }
  4482.  
  4483. sub cb_status {
  4484.     my $o = shift;
  4485.     my $ACTION = shift;
  4486.     my $pkg = shift;
  4487.     my $version = shift;
  4488.     my $target_name = shift;
  4489.     my $status = shift;
  4490.     my $bytes = shift;
  4491.     my $total = shift;
  4492.     my $secs = shift;
  4493.  
  4494.     my $cols = $ENV{COLUMNS} || 78;
  4495.  
  4496.     $o->inform(<<END) and return if ($status eq 'PRE-INSTALL');
  4497. $SEP
  4498. \u$ACTION '$pkg' version $version in $target_name.
  4499. $SEP
  4500. END
  4501.  
  4502.     # Print the output on one line, repeatedly:
  4503.     my ($line, $pad, $eol);
  4504.     if ($status eq 'DOWNLOAD') {
  4505.     if ($bytes < $total) {
  4506.         $line = "Transferring data: $bytes/$total bytes.";
  4507.         $eol = "\r";
  4508.     }
  4509.     else {
  4510.         $line = "Downloaded $bytes bytes.";
  4511.         $eol = "\n";
  4512.     }
  4513.     }
  4514.     elsif ($status eq 'PRE-EXPAND') {
  4515.     $line = ""; #"Extracting package. This may take a few seconds.";
  4516.     $eol = "\r";  #"\n";
  4517.     }
  4518.     elsif ($status eq 'EXPAND') {
  4519.     $line = "Extracting $bytes/$total: $secs";
  4520.     $eol = $bytes < $total ? "\r" : "\n";
  4521.     }
  4522.     elsif ($status eq 'COMPLETE') {
  4523.     my $verb = $ACTION eq 'install' ? 'installed' : 'upgraded';
  4524.     $o->inform(
  4525.         "Successfully $verb $pkg version $version in $target_name.\n"
  4526.     );
  4527.     return;
  4528.     }
  4529.     $pad = ' ' x ($cols - length($line));
  4530.     $o->verbose($line, $pad, $eol);
  4531. }
  4532.  
  4533. sub warn_profile_change {
  4534.     my $o = shift;
  4535.     my $ok = shift;
  4536.  
  4537.     my $profile_track = $o->conf('profile-track');
  4538.     my $profile = PPM::UI::profile_get()->result;
  4539.  
  4540.     if ($profile_track) {
  4541.     $o->verbose(<<END);
  4542. Tracking changes to profile '$profile'.
  4543. END
  4544.     }
  4545. }
  4546.  
  4547. sub parse_range {
  4548.     my @numbers;
  4549.     my $arg;
  4550.     while ($arg = shift) {
  4551.       while ($arg) {
  4552.     if ($arg =~ s/^\s*,?\s*(\d+)\s*-\s*(\d+)//) {
  4553.         push @numbers, ($1 .. $2);
  4554.     }
  4555.     elsif ($arg =~ s/^\s*,?\s*(\d+)//) {
  4556.         push @numbers, $1;
  4557.     }
  4558.     else {
  4559.         last;
  4560.     }
  4561.       }
  4562.     }
  4563.     @numbers;
  4564. }
  4565.  
  4566. sub raw_args {
  4567.     my $o = shift;
  4568.     strip($o->line_args);
  4569. }
  4570.  
  4571. sub strip {
  4572.     my $f = shift;
  4573.     $f =~ s/^\s*//;
  4574.     $f =~ s/\s*$//;
  4575.     $f;
  4576. }
  4577.  
  4578. # matches("neil", "ne|il") => 1
  4579. # matches("ne", "ne|il") => 1
  4580. # matches("n", "ne|il") => 0
  4581. sub matches {
  4582.     my $cmd = shift;
  4583.     my $pat = shift || "";
  4584.  
  4585.     my ($required, $extra) = split '\|', $pat;
  4586.     $extra ||= "";
  4587.     my $regex = "$required(?:";
  4588.     for (my $i=1; $i<=length($extra); $i++) {
  4589.     $regex .= '|' . substr($extra, 0, $i);
  4590.     }
  4591.     $regex .= ")";
  4592.     return $cmd =~ /^$regex$/i;
  4593. }
  4594.  
  4595. sub pause_exit {
  4596.     my $o = shift;
  4597.     my $exit_code = shift || 0;
  4598.     my $pause = shift || 0;
  4599.     if ($pause) {
  4600.     if ($o->have_readkey) {
  4601.         $o->inform("Hit any key to exit...");
  4602.     }
  4603.     else {
  4604.         $o->inform("Hit <ENTER> to exit...");
  4605.     }
  4606.     $o->readkey;
  4607.     }
  4608.     exit $exit_code;
  4609. }
  4610.  
  4611. #============================================================================
  4612. # Check if this is the first time we've ever used profiles. This can be
  4613. # guessed: if the 'profile' entry is not set, but the 'profile-track' flag
  4614. # is, then it's the first time profile-track has been set to '1'.
  4615. #============================================================================
  4616. sub setup_profile {
  4617.     my $o = shift;
  4618.     $o->inform(<<END);
  4619. $SEP
  4620. You have profile tracking turned on: now it's time to choose a profile name.
  4621. ActiveState's PPM 3.0 Server will track which packages you have installed on
  4622. your machine. This information is stored in a "profile", located on the
  4623. server.
  4624.  
  4625. Here are some features of profiles:
  4626.  o You can have as many profiles as you want;
  4627.  o Each profile can track an unlimited number of packages;
  4628.  o PPM defaults to "tracking" your profile (it updates your profile every time
  4629.    you add or remove a package;
  4630.  o You can disable profile tracking by modifying the 'profile-track' option;
  4631.  o You can manually select, save, and restore profiles;
  4632.  o You can view your profile from ASPN as well as inside PPM 3.
  4633. $SEP
  4634.  
  4635. END
  4636.  
  4637.     my $response = PPM::UI::profile_list();
  4638.     my @l;
  4639.     unless ($response->ok) {
  4640.     $o->warn($response->msg);
  4641.     $o->warn(<<END);
  4642.  
  4643. You can still use PPM3, but profiles are not enabled. To try setting up
  4644. profiles again, enter 'set profile-track=1'. Or, you can set up profiles
  4645. by hand, using the 'profile add' command.
  4646.  
  4647. END
  4648.     $o->run('unset', 'profile-track');
  4649.     return;
  4650.     }
  4651.     else {
  4652.     @l = sort $response->result_l;
  4653.     $o->inform("It looks like you have profiles on the server already.\n")
  4654.       if @l;
  4655.     $o->print_pairs([1 .. @l], \@l, '. ', 1, ' ');
  4656.     $o->inform("\n") if @l;
  4657.     }
  4658.  
  4659.     require PPM::Sysinfo;
  4660.     (my $suggest = PPM::Sysinfo::hostname()) =~ s/\..*$//;
  4661.     $suggest ||= "Default Profile";
  4662.     my $profile_name = $o->prompt(
  4663.     "What profile name would you like? [$suggest] ", $suggest, @l
  4664.     );
  4665.  
  4666.     my $select_existing = grep { $profile_name eq $_ } $response->result_l
  4667.       if $response->ok;
  4668.     if ($select_existing) {
  4669.     $o->inform("Selecting profile '$profile_name'...\n");
  4670.     PPM::UI::profile_set($profile_name);
  4671.     $o->inform(<<END);
  4672. You should probably run either 'profile save' or 'profile restore' to bring
  4673. the profile in sync with your computer.
  4674. END
  4675.     }
  4676.     elsif ($response->ok) {
  4677.     $o->inform("Creating profile '$profile_name'...\n");
  4678.     $o->run('profile', 'add', $profile_name);
  4679.     $o->inform("Saving profile '$profile_name'...\n");
  4680.     $o->run('profile', 'save');
  4681.     $o->inform(<<END);
  4682. Congratulations! PPM is now set up to track your profile.
  4683. END
  4684.     }
  4685.     else {
  4686.     $o->warn($response->msg);
  4687.     $o->warn(<<END);
  4688.  
  4689. You can still use PPM3, but profiles will not be enabled. To try setting up
  4690. profiles again, enter 'set profile-track=1'. Or, you can set up profiles
  4691. yourself using the 'profile add' command.
  4692.  
  4693. END
  4694.     $o->run('unset', 'profile-track');
  4695.     }
  4696. }
  4697.  
  4698. package main;
  4699. use Getopt::Long;
  4700. use Data::Dumper;
  4701.  
  4702. $ENV{PERL_READLINE_NOWARN} = "1";
  4703. $ENV{PERL_RL} = $^O eq 'MSWin32' ? "0" : "Perl";
  4704.  
  4705. my ($pause, $input_file, $target);
  4706.  
  4707. BEGIN {
  4708.     my ($shared_config_files, @fixpath, $gen_inst_key);
  4709.  
  4710.     Getopt::Long::Configure('pass_through');
  4711.     $target = 'auto';
  4712.     GetOptions(
  4713.     'file=s' => \$input_file,
  4714.     'shared' => \$shared_config_files,
  4715.     'target:s' => \$target,
  4716.     'fixpath=s' => \@fixpath,
  4717.     'generate-inst-key' => \$gen_inst_key,
  4718.     pause => \$pause,
  4719.     );
  4720.     Getopt::Long::Configure('no_pass_through');
  4721.  
  4722.     if ($shared_config_files) {
  4723.     $ENV{PPM3_shared_config} = 1;
  4724.     }
  4725.  
  4726.     if (@fixpath) {
  4727.     PPM::UI::target_fix_paths(@fixpath);
  4728.     exit;
  4729.     }
  4730.     if ($gen_inst_key) {
  4731.     require PPM::Config;
  4732.     PPM::Config::load_config_file('instkey');
  4733.     exit;
  4734.     }
  4735. }
  4736.  
  4737. # If we're being run from a file, tell Term::Shell about it:
  4738. if ($input_file) {
  4739.     my $line = 0;
  4740.     open SCRIPT, $input_file or die "$0: can't open $input_file: $!";
  4741.     my $shell = PPMShell->new(
  4742.     term => ['PPM3', \*SCRIPT, \*STDOUT],
  4743.     target => $target,
  4744.     pager => 'none',
  4745.     );
  4746.     $shell->setmode('SCRIPT');
  4747.     while (<SCRIPT>) {
  4748.     $line++;
  4749.     next if /^\s*#/ or /^\s*$/;
  4750.     my ($cmd, @args) = $shell->line_parsed($_);
  4751.     my $ret = $shell->run($cmd, @args);
  4752.     my $warn = <<END;
  4753. $0: $input_file:$line: fatal error: unknown or ambiguous command '$cmd'. 
  4754. END
  4755.     $shell->warn($warn) and $shell->pause_exit(2, $pause)
  4756.         unless $shell->{API}{cmd}{run}{found};
  4757.     $shell->pause_exit(1, $pause) unless $ret;
  4758.     }
  4759.     close SCRIPT;
  4760.     $shell->pause_exit(0, $pause);
  4761. }
  4762.  
  4763. # If we've been told what to do from the command-line, do it right away:
  4764. elsif (@ARGV) {
  4765.     my $shell = PPMShell->new(target => $target, pager => 'none');
  4766.     $shell->setmode('BATCH');
  4767.     my $ret = $shell->run($ARGV[0], @ARGV[1..$#ARGV]);
  4768.     my $warn = <<END;
  4769. Unknown or ambiguous command '$ARGV[0]'; type 'help' for commands.
  4770. END
  4771.     $shell->warn($warn) and $shell->pause_exit(2, $pause)
  4772.     unless $shell->{API}{cmd}{run}{found};
  4773.     $shell->pause_exit(0, $pause) if $ret;
  4774.     $shell->pause_exit(1, $pause);
  4775. }
  4776.  
  4777. # Just run the command loop
  4778. if (-t STDIN and -t STDOUT) {
  4779.     my $shell = PPMShell->new(target => $target);
  4780.     $shell->setmode('SHELL');
  4781.     $shell->cmdloop;
  4782. }
  4783. else {
  4784.     die <<END;
  4785.  
  4786. Error:
  4787.     PPM3 cannot be run in interactive shell mode unless both STDIN and
  4788.     STDOUT are connected to a terminal or console. If you want to
  4789.     capture the output of a command, use PPM3 in batch mode like this:
  4790.  
  4791.        ppm3 search IO-stringy > results.txt
  4792.  
  4793.     Type 'perldoc ppm3' for more information.
  4794.  
  4795. END
  4796. }
  4797.  
  4798.  
  4799. =head1 NAME
  4800.  
  4801. ppm3-bin - ppm3 executable
  4802.  
  4803. =head1 SYNOPSIS
  4804.  
  4805. Do not run I<ppm3-bin> manually. It is meant to be called by the wrapper
  4806. program I<ppm3>. See L<ppm3>.
  4807.  
  4808. =head1 DESCRIPTION
  4809.  
  4810. I<ppm3> runs I<ppm3-bin> after setting up a few environment variables. You
  4811. should run I<ppm3> instead.
  4812.  
  4813. For information about I<ppm3> commands, see L<ppm3>.
  4814.  
  4815. =head1 SEE ALSO
  4816.  
  4817. See L<ppm3>.
  4818.  
  4819. =head1 AUTHOR
  4820.  
  4821. ActiveState Corporation (support@ActiveState.com)
  4822.  
  4823. =head1 COPYRIGHT
  4824.  
  4825. Copyright (C) 2001, 2002, ActiveState Corporation. All Rights Reserved.
  4826.  
  4827. =cut
  4828.