about summary refs log tree commit diff stats
Commit message (Expand)AuthorAgeFilesLines
...
| * | Mention C-x C-r (reload inputrc) in the man pagePaul Fertser2022-04-091-0/+5
|/ /
* | Fix preferences testsMichael Vetter2022-04-081-2/+2
* | Dont show presence status changes by defaultMichael Vetter2022-04-071-2/+2
* | Merge pull request #1683 from paulfertser/more-example-aliasesMichael Vetter2022-04-041-0/+2
|\ \
| * | Include useful aliases in profrc examplePaul Fertser2022-04-031-0/+2
* | | Merge pull request #1674 from paulfertser/allow-bold-for-default-coloursMichael Vetter2022-04-041-12/+13
|\ \ \
| * | | Allow bold for default coloursPaul Fertser2022-04-011-12/+13
* | | | Merge pull request #1680 from paulfertser/add-irssi-themeMichael Vetter2022-04-042-1/+132
|\ \ \ \
| * | | | Add irssi themePaul Fertser2022-04-021-0/+131
| * | | | Use default rather than boothj5 theme in profrc examplePaul Fertser2022-04-021-1/+1
* | | | | Start new cycleMichael Vetter2022-04-04102-5496/+1
* | | | | Release 0.12.1Michael Vetter2022-04-04104-3/+5518
* | | | | Merge pull request #1681 from akaWolf/fix_theme_load_non_existMichael Vetter2022-04-031-0/+3
|\ \ \ \ \ | |_|_|/ / |/| | | |
| * | | | disable execution of colors-changing code when call for theme load and it doe...Artjom Vejsel2022-04-021-0/+3
| | |/ / | |/| |
* | | | Merge pull request #1675 from paulfertser/fix-no-me-historyMichael Vetter2022-04-031-0/+1
|\ \ \ \ | |_|/ / |/| | |
| * | | Use correct colour for their nick when showing historyPaul Fertser2022-04-011-0/+1
| |/ /
* | | Include `config.h` in `src/config.cafile.c`Maxi Wuttke2022-04-021-0/+2
* | | Fix a segfault when uploading or downloading filesMaxi Wuttke2022-04-022-2/+2
|/ /
* | Merge pull request #1673 from profanity-im/fix-loggingMichael Vetter2022-04-011-1/+7
|\ \
| * | Fix logging (this time for real)Steffen Jaeckel2022-04-011-1/+7
|/ /
* | Merge pull request #1672 from profanity-im/fix-loggingMichael Vetter2022-04-011-1/+3
|\ \
| * | fix path where logs are storedSteffen Jaeckel2022-04-011-1/+3
|/ /
* | Merge pull request #1664 from paulfertser/tab-completion-cleanupMichael Vetter2022-04-011-41/+11
|\ \
| * | Tab completion code simplificationPaul Fertser2022-03-301-41/+11
* | | Merge pull request #1667 from paulfertser/fix-screen-arrows-bindingsMichael Vetter2022-04-011-0/+3
|\ \ \
| * | | Add Alt/Ctrl-arrows combinations for GNU ScreenPaul Fertser2022-03-301-0/+3
* | | | Merge pull request #1669 from paulfertser/make-rl-functions-bindableMichael Vetter2022-04-011-0/+5
|\ \ \ \
| * | | | Make all existing input functions bindable from configPaul Fertser2022-03-301-0/+5
| |/ / /
* | | | Merge pull request #1670 from profanity-im/moar-cleanupMichael Vetter2022-04-014-48/+61
|\ \ \ \
| * | | | fix `account set theme` helpSteffen Jaeckel2022-04-011-1/+1
| * | | | fix linter warningsSteffen Jaeckel2022-03-311-1/+2
| * | | | less duplicationSteffen Jaeckel2022-03-312-37/+58
| * | | | use `_string_matches_one_of()` at more placesSteffen Jaeckel2022-03-311-16/+7
| |/ / /
* | | | Merge pull request #1668 from paulfertser/document-input-rcMichael Vetter2022-04-011-0/+12
|\ \ \ \
| * | | | Document custom input configuration in man pagePaul Fertser2022-03-301-0/+12
| |/ / /
* | | | Merge pull request #1671 from paulfertser/fix-resize-raceMichael Vetter2022-04-011-3/+1
|\ \ \ \ | |/ / / |/| | |
| * | | Fix race condition on resizePaul Fertser2022-04-011-3/+1
|/ / /
* | | Merge pull request #1666 from paulfertser/man-page-improvementsMichael Vetter2022-03-301-5/+27
|\ \ \
| * | | Improve manpage formatting a bitPaul Fertser2022-03-301-3/+8
| * | | Add all missing key bindings to man pagePaul Fertser2022-03-301-2/+19
|/ / /
* | | Merge pull request #1665 from profanity-im/moar-cleanupMichael Vetter2022-03-307-179/+137
|\ \ \ | |/ / |/| |
| * | fix installation of manpagesSteffen Jaeckel2022-03-301-3/+3
| * | update gitignoreSteffen Jaeckel2022-03-301-0/+5
| * | add CI job to check coding styleSteffen Jaeckel2022-03-301-0/+23
| * | run `make format`Steffen Jaeckel2022-03-302-3/+4
| * | add `_string_matches_one_of()` helper functionSteffen Jaeckel2022-03-301-21/+39
| * | clean-up connection (act I)Steffen Jaeckel2022-03-301-152/+63
|/ /
* | Start new cycleMichael Vetter2022-03-30102-5496/+1
* | Release 0.12.0Michael Vetter2022-03-30104-4/+5500
* | Merge pull request #1660 from paulfertser/fix-invalid-mbrlen-inputMichael Vetter2022-03-291-0/+4
|\ \
e>
8e63339d ^
6f8ca83b ^
8e63339d ^
6f8ca83b ^


5ca9ab8c ^
6f8ca83b ^

56549de7 ^




6f8ca83b ^
4ead0882 ^




6f8ca83b ^
4ead0882 ^
79c760d7 ^

6f8ca83b ^
4ead0882 ^


6f8ca83b ^

4ead0882 ^

542d3a25 ^
4ead0882 ^










ea8c70ca ^
53f8129c ^
ea8c70ca ^
49e5aa69 ^
4ead0882 ^

6f8ca83b ^
5ca9ab8c ^






6f8ca83b ^
34c0d954 ^
6f8ca83b ^
456bddd6 ^
4ead0882 ^

6f8ca83b ^
5ca9ab8c ^
6f8ca83b ^

456bddd6 ^



06a00bd0 ^
6f8ca83b ^
bddd9010 ^
5ca9ab8c ^


26e2fcc7 ^

5ca9ab8c ^

26e2fcc7 ^

5ca9ab8c ^





6f8ca83b ^
8f343062 ^
34c0d954 ^
5ca9ab8c ^
654a81ca ^
26e2fcc7 ^
34c0d954 ^
654a81ca ^
34c0d954 ^
8f343062 ^

c908fd3d ^

1e2d7ced ^
c908fd3d ^
34c0d954 ^
5ca9ab8c ^

8f343062 ^
ddefc642 ^



8f343062 ^

5ca9ab8c ^
4ead0882 ^
032bd50b ^


45dd1a43 ^


542d3a25 ^




45dd1a43 ^



4ead0882 ^
33562459 ^
4ead0882 ^
33562459 ^












4ead0882 ^
bddd9010 ^
4ead0882 ^

33562459 ^
4ead0882 ^




33562459 ^


4ead0882 ^


33562459 ^

26e2fcc7 ^
33562459 ^

26e2fcc7 ^
33562459 ^










4ead0882 ^

33562459 ^
26e2fcc7 ^
33562459 ^
6f8ca83b ^

9cf43c17 ^




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
                    


                                                                        












                                                                           
              
         
                                  
          
 

                       
                  
 







































                                                                          
                   

                                                               







                             















                                                                                 



                        

















                                                                  

                                              

                                      

                                                  
                                                                                   



                                                      
                          



                                                                





                                                                                             




                                                                                      
                                   





                                                                                      

                                   







                                                                                        
 

                                    
 


                                                           

                                                                                 
                                                                                 
                                        
                                                                                    





                                                                  
                                        
                                                                                   
                                        
                                                                                      
                                       
                                                            
                                            
                                             
                                          


                                                          
                                         
                                                  
                                 

                                                        
                                        

                                                  
                                     
                                                      
                                        


                                       
                                                                            

                                             




                                                                      
 




                                                               
                                       
 

                                                                               
                                                           


                                                           

                              

                                                                                  
                                                        










                                                                                                
                                                         
                                                                                        
                             
                                                                                       

                             
                                                      






                                                                              
                                         
                          
                                             
                                         

                                              
                                          
                                                                               

                                             



                                                          
                                                                                    
 
                                                                                


                                                 

                                                                                       

                                                                                       

                                                                                       





                                                                                       
                              
                                         
 
                                   
                                                                                 
                                                                                   
                                                                          
                                                                                       
                                     

                                                         

                                                                
                                                       
                                                                                
 

                                   
                                              



                                                                                                   

                                                                    
                     
                                                     


                                                                     


                                                                                            




                                                                                                             



                                                                                                   
 
           
                                                                                   












                                                                                    
                                                             
                                                                           

                                                                                 
                                                    




                                                                                             


                                                                               


                                   

                               
                                       

                            
                          










                                                         

                                                                                        
                     
                                                                                              
 

                          




                                          
#!/usr/bin/python -S
# Copyright (C) 2012  Roman Zimbelmann <romanz@lavabit.com>
# This software is distributed under the terms of the GNU GPL version 3.

"""
rifle, the file executor/opener of ranger

This can be used as a standalone program or can be embedded in python code.
When used together with ranger, it doesn't have to be installed to $PATH.

Example usage:

	rifle = Rifle("rilfe.conf")
	rifle.reload_config()
	rifle.execute(["file1", "file2"])
"""

import os.path
import re
from subprocess import Popen, PIPE
import sys

DEFAULT_PAGER = 'less'
DEFAULT_EDITOR = 'nano'
ENCODING = 'utf-8'

try:
	from ranger.ext.get_executables import get_executables
except ImportError:
	_cached_executables = None

	def get_executables():
		"""
		Return all executable files in $PATH + Cache them.
		"""
		global _cached_executables
		if _cached_executables is not None:
			return _cached_executables

		if 'PATH' in os.environ:
			paths = os.environ['PATH'].split(':')
		else:
			paths = ['/usr/bin', '/bin']

		from stat import S_IXOTH, S_IFREG
		paths_seen = set()
		_cached_executables = set()
		for path in paths:
			if path in paths_seen:
				continue
			paths_seen.add(path)
			try:
				content = listdir(path)
			except:
				continue
			for item in content:
				abspath = path + '/' + item
				try:
					filestat = stat(abspath)
				except:
					continue
				if filestat.st_mode & (S_IXOTH | S_IFREG):
					_cached_executables.add(item)
		return _cached_executables


def _is_terminal():
	# Check if stdin (file descriptor 0), stdout (fd 1) and
	# stderr (fd 2) are connected to a terminal
	try:
		os.ttyname(0)
		os.ttyname(1)
		os.ttyname(2)
	except:
		return False
	return True


def squash_flags(flags):
	"""
	Remove lowercase flags if the respective uppercase flag exists

	>>> squash_flags('abc')
	'abc'
	>>> squash_flags('abcC')
	'ab'
	>>> squash_flags('CabcAd')
	'bd'
	"""
	exclude = ''.join(f.upper() + f.lower() for f in flags if f == f.upper())
	return ''.join(f for f in flags if f not in exclude)


class Rifle(object):
	delimiter1 = '='
	delimiter2 = ','

	def hook_before_executing(self, command, mimetype, flags):
		pass

	def hook_after_executing(self, command, mimetype, flags):
		pass

	def hook_command_preprocessing(self, command):
		return command

	def hook_command_postprocessing(self, command):
		return command

	def hook_environment(self, env):
		return env

	def hook_logger(self, string):
		sys.stderr.write(string + "\n")

	def __init__(self, config_file):
		self.config_file = config_file
		self._app_flags = ''
		self._app_label = None

	def reload_config(self, config_file=None):
		"""Replace the current configuration with the one in config_file"""
		if config_file is None:
			config_file = self.config_file
		f = open(config_file, 'r')
		self.rules = []
		lineno = 1
		for line in f:
			if line.startswith('#') or line == '\n':
				continue
			line = line.strip()
			try:
				if self.delimiter1 not in line:
					raise Exception("Line without delimiter")
				tests, command = line.split(self.delimiter1, 1)
				tests = tests.split(self.delimiter2)
				tests = tuple(tuple(f.strip().split(None, 1)) for f in tests)
				command = command.strip()
				self.rules.append((command, tests))
			except Exception as e:
				self.hook_logger("Syntax error in %s line %d (%s)" % \
					(config_file, lineno, str(e)))
			lineno += 1
		f.close()

	def _eval_condition(self, condition, files, label):
		# Handle the negation of conditions starting with an exclamation mark,
		# then pass on the arguments to _eval_condition2().

		if not condition:
			return True
		if condition[0].startswith('!'):
			new_condition = tuple([condition[0][1:]]) + tuple(condition[1:])
			return not self._eval_condition2(new_condition, files, label)
		return self._eval_condition2(condition, files, label)

	def _eval_condition2(self, rule, files, label):
		# This function evaluates the condition, after _eval_condition() handled
		# negation of conditions starting with a "!".

		if not files:
			return False

		function = rule[0]
		argument = rule[1] if len(rule) > 1 else ''

		if function == 'ext':
			extension = os.path.basename(files[0]).rsplit('.', 1)[-1]
			return bool(re.search('^(' + argument + ')$', extension))
		elif function == 'name':
			return bool(re.search(argument, os.path.basename(files[0])))
		elif function == 'match':
			return bool(re.search(argument, files[0]))
		elif function == 'file':
			return os.path.isfile(files[0])
		elif function == 'directory':
			return os.path.isdir(files[0])
		elif function == 'path':
			return bool(re.search(argument, os.path.abspath(files[0])))
		elif function == 'mime':
			return bool(re.search(argument, self._get_mimetype(files[0])))
		elif function == 'has':
			return argument in get_executables()
		elif function == 'terminal':
			return _is_terminal()
		elif function == 'number':
			if argument.isdigit():
				self._skip = int(argument)
			return True
		elif function == 'label':
			self._app_label = argument
			if label:
				return argument == label
			return True
		elif function == 'flag':
			self._app_flags = argument
			return True
		elif function == 'X':
			return 'DISPLAY' in os.environ
		elif function == 'else':
			return True

	def _get_mimetype(self, fname):
		# Spawn "file" to determine the mime-type of the given file.
		if self._mimetype:
			return self._mimetype
		process = Popen(["file", "--mime-type", "-Lb", fname],
				stdout=PIPE, stderr=PIPE)
		mimetype, _ = process.communicate()
		self._mimetype = mimetype.decode(ENCODING)
		return self._mimetype

	def _build_command(self, files, action, flags):
		# Get the flags
		if isinstance(flags, str):
			self._app_flags += flags
		self._app_flags = squash_flags(self._app_flags)
		flags = self._app_flags

		_filenames = "' '".join(f.replace("'", "'\\\''") for f in files
				if "\x00" not in f)
		command = "set -- '%s'" % _filenames + '\n'

		# Apply flags
		command += self._apply_flags(action, flags)
		return command

	def _apply_flags(self, action, flags):
		# FIXME: Flags do not work properly when pipes are in the command.
		# NOTE: "r" flag is handled in execute()
		if 't' in flags:
			if 'TERMCMD' not in os.environ:
				term = os.environ['TERM']
				if term.startswith('rxvt-unicode'):
					term = 'urxvt'
				if term not in get_executables():
					self.hook_logger("Can not determine terminal command.  "
						"Please set $TERMCMD manually.")
				os.environ['TERMCMD'] = term
			action = "$TERMCMD -e %s" % action
		if 'f' in flags:
			if 'setsid' in get_executables():
				action = "setsid %s > /dev/null 2> /dev/null &" % action
			else:
				action = "nohup %s > /dev/null 2> /dev/null &" % action
		return action

	def list_commands(self, files, mimetype=None):
		"""
		Returns one 4-tuple for all currently applicable commands
		The 4-tuple contains (count, command, label, flags).
		count is the index, counted from 0 upwards,
		command is the command that will be executed.
		label and flags are the label and flags specified in the rule.
		"""
		self._mimetype = mimetype
		count = -1
		for cmd, tests in self.rules:
			self._skip = None
			self._app_flags = ''
			self._app_label = None
			for test in tests:
				if not self._eval_condition(test, files, None):
					break
			else:
				if self._skip is None:
					count += 1
				else:
					count = self._skip
				yield (count, cmd, self._app_label, self._app_flags)

	def execute(self, files, number=0, label=None, flags="", mimetype=None):
		"""
		Executes the given list of files.

		By default, this executes the first command where all conditions apply,
		but by specifying number=N you can run the 1+Nth command.

		If a label is specified, only rules with this label will be considered.

		If you specify the mimetype, rifle will not try to determine it itself.

		By specifying a flag, you extend the flag that is defined in the rule.
		Uppercase flags negate the respective lowercase flags.
		For example: if the flag in the rule is "pw" and you specify "Pf", then
		the "p" flag is negated and the "f" flag is added, resulting in "wf".
		"""
		command = None
		found_at_least_one = None

		# Determine command
		for count, cmd, lbl, flgs in self.list_commands(files, mimetype):
			if label and label == lbl or not label and count == number:
				cmd = self.hook_command_preprocessing(cmd)
				command = self._build_command(files, cmd, flags + flgs)
				break
			else:
				found_at_least_one = True
		else:
			if label and label in get_executables():
				cmd = '%s "$@"' % label
				command = self._build_command(files, cmd, flags)

		# Execute command
		if command is None:
			if found_at_least_one:
				if label:
					self.hook_logger("Label '%s' is undefined" % label)
				else:
					self.hook_logger("Method number %d is undefined." % number)
			else:
				self.hook_logger("No action found.")
		else:
			if 'PAGER' not in os.environ:
				os.environ['PAGER'] = DEFAULT_PAGER
			if 'EDITOR' not in os.environ:
				os.environ['EDITOR'] = DEFAULT_EDITOR
			command = self.hook_command_postprocessing(command)
			self.hook_before_executing(command, self._mimetype, self._app_flags)
			try:
				if 'r' in flags:
					p = Popen(['sudo', '-E', 'su', '-mc', command],
							env=self.hook_environment(os.environ), shell=False)
				else:
					p = Popen(command, env=self.hook_environment(os.environ), shell=True)
				p.wait()
			finally:
				self.hook_after_executing(command, self._mimetype, self._app_flags)


def main():
	"""The main function which is run when you start this program direectly."""
	import sys

	# Find configuration file path
	if 'XDG_CONFIG_HOME' in os.environ and os.environ['XDG_CONFIG_HOME']:
		conf_path = os.environ['XDG_CONFIG_HOME'] + '/ranger/rifle.conf'
	else:
		conf_path = os.path.expanduser('~/.config/ranger/rifle.conf')
	if not os.path.isfile(conf_path):
		conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__),
			'../defaults/rifle.conf'))

	# Evaluate arguments
	from optparse import OptionParser
	parser = OptionParser(usage="%prog [-fhlpw] [files]")
	parser.add_option('-f', type="string", default="", metavar="FLAGS",
			help="use additional flags: f=fork, r=root, t=terminal. "
			"Uppercase flag negates respective lowercase flags.")
	parser.add_option('-l', action="store_true",
			help="list possible ways to open the files (id:label:flags:command)")
	parser.add_option('-p', type='string', default='0', metavar="KEYWORD",
			help="pick a method to open the files.  KEYWORD is either the "
			"number listed by 'rifle -l' or a string that matches a label in "
			"the configuration file")
	parser.add_option('-w', type='string', default=None, metavar="PROGRAM",
			help="open the files with PROGRAM")
	options, positional = parser.parse_args()
	if not positional:
		parser.print_help()
		raise SystemExit(1)

	if options.p.isdigit():
		number = int(options.p)
		label = None
	else:
		number = 0
		label = options.p

	if options.w is not None and not options.l:
		p = Popen([options.w] + list(positional))
		p.wait()
	else:
		# Start up rifle
		rifle = Rifle(conf_path)
		rifle.reload_config()
		#print(rifle.list_commands(sys.argv[1:]))
		if options.l:
			for count, cmd, label, flags in rifle.list_commands(positional):
				print("%d:%s:%s:%s" % (count, label or '', flags, cmd))
		else:
			rifle.execute(positional, number=number, label=label, flags=options.f)


if __name__ == '__main__':
	if 'RANGER_DOCTEST' in os.environ:
		import doctest
		doctest.testmod()
	else:
		main()