summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorhut <hut@lavabit.com>2010-01-24 19:04:04 +0100
committerhut <hut@lavabit.com>2010-01-24 19:04:04 +0100
commit331ebf78aea448611e0de237c867cad3ba9bfd32 (patch)
tree10d367c599cb80910054414cfcf7c26451df9df0
parentc3cdeb9cbb3a4718d8b0d707e0864c00aca7a580 (diff)
downloadranger-331ebf78aea448611e0de237c867cad3ba9bfd32.tar.gz
added a new runner class
-rw-r--r--ranger/runner.py175
1 files changed, 175 insertions, 0 deletions
diff --git a/ranger/runner.py b/ranger/runner.py
new file mode 100644
index 00000000..c5d5a78c
--- /dev/null
+++ b/ranger/runner.py
@@ -0,0 +1,175 @@
+# Copyright (c) 2009, 2010 hut <hut@lavabit.com>
+#
+# Permission to use, copy, modify, and/or distribute this software for any
+# purpose with or without fee is hereby granted, provided that the above
+# copyright notice and this permission notice appear in all copies.
+#
+# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""
+This module is an abstract layer over subprocess.Popen
+
+It gives you highlevel control about how processes are run.
+
+Example:
+run = Runner(logfunc=print)
+run('sleep 2', wait=True)         # waits until the process exists
+run(['ls', '--help'], flags='p')  # pipes output to pager
+run()                             # prints an error message
+
+List of allowed flags:
+s: silent mode. output will be discarded.
+d: detach the process.
+p: redirect output to the pager
+(An uppercase key ensures that a certain flag will not be used.)
+"""
+
+import os
+import sys
+from subprocess import Popen, PIPE
+from ranger.ext.shell_escape import shell_escape
+from ranger.ext.waitpid_no_intr import waitpid_no_intr
+
+
+ALLOWED_FLAGS = 'sdpSDP'
+devnull = open(os.devnull, 'a')
+
+
+class Context(object):
+	"""
+	A context object contains data on how to run a process.
+	"""
+
+	def __init__(self, **keywords):
+		self.__dict__ = keywords
+	
+	@property
+	def filepaths(self):
+		if hasattr(self, files):
+			return [f.path for f in self.files]
+		return []
+
+	def __iter__(self):
+		"""Iterate over file paths"""
+		return iter(self.filepaths)
+
+	def squash_flags(self):
+		"""Remove duplicates and lowercase counterparts of uppercase flags"""
+		for flag in self.flags:
+			if ord(flag) <= 90:
+				bad = flag + flag.lower()
+				self.flags = ''.join(c for c in self.flags if c not in bad)
+
+
+class Runner(object):
+	def __init__(self, ui=None, logfunc=None, apps=None):
+		self.ui = ui
+		self.logfunc = logfunc
+		self.apps = apps
+	
+	def _log(self, text):
+		try:
+			self.logfunc(text)
+		except TypeError:
+			pass
+		return False
+
+	def _activate_ui(self, boolean):
+		if self.ui is not None:
+			if boolean:
+				try: self.ui.initialize()
+				except: self._log("Failed to initialize UI")
+			else:
+				try: self.ui.suspend()
+				except: self._log("Failed to suspend UI")
+	
+	def __call__(self, action=None, try_app_first=False,
+			app='default', files=None, mode=0,
+			flags='', wait=True, **popen_kws):
+		"""
+		Run the application in the way specified by the options.
+
+		Returns False if nothing can be done, None if there was an error,
+		otherwise the process object returned by Popen().
+
+		This function tries to find an action if none is defined.
+		"""
+
+		# Find an action if none was supplied by
+		# creating a Context object and passing it to
+		# an Application object.
+
+		context = Context(app=app, files=files, mode=mode,
+				flags=flags, wait=wait, popen_kws=popen_kws)
+
+		if self.apps:
+			if try_app_first and action is not None:
+				test = self.apps.apply(app, context)
+				if test:
+					action = test
+			if action is None:
+				action = self.apps.apply(app, context)
+				if action is None:
+					return self._log("No action found!")
+
+		if action is None:
+			return self._log("No way of determining the action!")
+
+		# Preconditions
+
+		context.squash_flags()
+		popen_kws = context.popen_kws  # shortcut
+
+		toggle_ui = True
+		pipe_output = False
+
+		popen_kws['args'] = action
+		if 'shell' not in popen_kws:
+			popen_kws['shell'] = isinstance(action, str)
+		if 'stdout' not in popen_kws:
+			popen_kws['stdout'] = sys.stdout
+		if 'stderr' not in popen_kws:
+			popen_kws['stderr'] = sys.stderr
+
+		# Evaluate the flags to determine keywords
+		# for Popen() and other variables
+
+		if 'p' in context.flags:
+			popen_kws['stdout'] = PIPE
+			popen_kws['stderr'] = PIPE
+			toggle_ui = False
+			pipe_output = True
+			context.wait = False
+		if 's' in context.flags or 'd' in context.flags:
+			for key in ('stdout', 'stderr', 'stdin'):
+				popen_kws[key] = devnull
+		if 'd' in context.flags:
+			toggle_ui = False
+			context.wait = False
+	
+		# Finally, run it
+
+		if toggle_ui:
+			self._activate_ui(False)
+		try:
+			process = None
+			try:
+				process = Popen(**popen_kws)
+			except:
+				self._log("Failed to run: " + str(action))
+			else:
+				if context.wait:
+					waitpid_no_intr(process.pid)
+		finally:
+			if toggle_ui:
+				self._activate_ui(True)
+			if pipe_output and process:
+				return self(action='less', app='pager', try_app_first=True,
+						stdin=process.stdout)
+			return process
ef='#n384'>384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785