Skip to content

Commit

Permalink
Merge pull request #4 from klaascuvelier/improvements
Browse files Browse the repository at this point in the history
Improvements
  • Loading branch information
klaascuvelier authored Mar 27, 2018
2 parents 753bae1 + bcf1cb0 commit 091c8cd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 11 deletions.
49 changes: 38 additions & 11 deletions CommandOnSave.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,47 @@
import os
import sublime
import sublime_plugin
import subprocess


class CommandOnSave(sublime_plugin.EventListener):
def on_post_save(self, view):
_STATUS_KEY = 'CommandOnSave'

class CommandOnSave(sublime_plugin.EventListener):
def on_post_save_async(self, view):
settings = sublime.load_settings('CommandOnSave.sublime-settings').get('commands')
if settings is None:
return

file = view.file_name()
before_stat = None

view.erase_status(_STATUS_KEY)
for path, commands in settings.items():
if file.startswith(path):
for command in commands:
# record the mtime so we can check if we need to reload the file
if before_stat is None:
before_stat = os.stat(file)

command = re.sub(
r"\b_file_\b",
file,
command
)

process = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.stdout.read()
code = process.wait()
if code != 0:
view.set_status(_STATUS_KEY, 'ERROR: Command failed: %s' % (
' '.join(command)))
print('CommandOnSave %s failed code %d; output: %s' % (
' '.join(command), code, output))
# attempt to execute any other commands

if not settings == None:
for path in settings.keys():
commands = settings.get(path)
if file.startswith(path) and len(commands) > 0:
print("Command on Save:")
for command in commands:
p = subprocess.Popen([command], shell=True, stdout=subprocess.PIPE)
out, err = p.communicate()
print (out.decode('utf-8'))
if before_stat is not None and not view.is_dirty():
after_stat = os.stat(file)
if before_stat.st_mtime != after_stat.st_mtime:
# it seems like the file changed: reload the view
view.run_command('revert')
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ Usage
=====
This plugin reads commands from the settings file. The commands settings-key is an associative array of paths and their commands. Everytime a file is saved, all commands for every matched path-key is executed.

The path of the file that is being save can get injected into your command with the `_file_` placeholder.

If your command updates the content of the save file, the file will be reloaded in Sublime afterwards (thanks to @evanj).

For more info, see the examples


Expand Down

0 comments on commit 091c8cd

Please sign in to comment.