Add a 'less' command, that does the same as cat, but uses a pager.
authorDennis Kaarsemaker <dennis.kaarsemaker@booking.com>
Wed, 03 Dec 2014 09:47:26 +0100
changeset 72 39e9f802eb40
parent 71 b5adcd83b152
child 73 b3b840a4b56c
Add a 'less' command, that does the same as cat, but uses a pager. To avoid code duplication, refactor run_cat to be a thin wrapper around a common function called by both run_cat and run_less.
shelldap
--- a/shelldap	Mon Aug 11 11:25:33 2014 -0700
+++ b/shelldap	Wed Dec 03 09:47:26 2014 +0100
@@ -239,6 +239,10 @@
     cat uid=mahlon,ou=People,dc=example,o=company
     cat uid=mahlon + userPassword
 
+=item B< less>
+
+Like cat, but uses the configured pager to display output.
+
 =item B<  cd>
 
 Change directory.  Translated to LDAP, this changes the current basedn.
@@ -472,6 +476,7 @@
 	$self->{'API'}->{'match_uniq'} = 0;
 
 	$self->{'editor'} = $conf->{'editor'} || $ENV{'EDITOR'} || 'vi';
+	$self->{'pager'} = $conf->{'pager'} || $ENV{'PAGER'} || 'less';
 	$self->{'env'}	= [ qw/ debug cacheage timeout / ];
 
 	# let autocomplete work with the '=' character
@@ -1113,6 +1118,7 @@
 		copy   => 'cp',
 		cat    => 'read',
 		move   => 'mv',
+		less   => undef,
 		cd     => undef,
 		passwd => undef
 	);
@@ -1196,6 +1202,24 @@
 	my $dn    = shift;
 	my @attrs = (@_) ? @_ : ('*');
 
+	display($self, $dn, \@attrs, 0);
+}
+
+sub run_less
+{
+	my $self  = shift;
+	my $dn    = shift;
+	my @attrs = (@_) ? @_ : ('*');
+
+	display($self, $dn, \@attrs, 1);
+}
+
+sub display{
+	my $self  = shift;
+	my $dn    = shift;
+	my @attrs = @{;shift};
+	my $use_pager = shift;
+
 	unless ( $dn ) {
 		print "No dn provided.\n";
 		return;
@@ -1241,13 +1265,16 @@
 		return;
 	}
 
-	# display to stdout
+	# display to stdout or pager
 	#
+	my $ldif = $self->ldif($use_pager);
 	foreach my $e ( @{ $s->{'entries'} } ) {
-		$self->ldif->write_entry( $e );
-		print "\n";
+		$ldif->write_entry( $e );
 	}
-
+	if($use_pager) {
+		system( $self->{'pager'}, $self->{'ldif_fname'} );
+		unlink $self->{'ldif_fname'};
+	}	
 	return;
 }