Sublime Forum

Push Code On Save

#1

How do I connect to my server (not local but paid hosting) and each time I save a change in the source Sublime Text automatically pushes this code to the server please?

Thank you.

Best Regards

0 Likes

#2

Or on a local server how do I get the browser to refresh once I hit save in ST3?

0 Likes

#3

You can do

  • connect to server if sublime is open
  • with each saving command you replace the file on the server with the current one (use: EventListener, on_post_save_async)
  • close the connection if you close ST (unfortunately we have no event on_editor_close, so it must happen manually)
    or
  • with each saving command you connect to server, replace the file on the server with the current one and close the connection

All you need is in the python ftp library.

EDIT:

I’ve tinkered times something quickly :smiley: (It works). In the “allowed_extensions” you can specify the file types that may be used.

import sublime
import sublime_plugin
import ftplib
import os

class SaveListener(sublime_plugin.EventListener):
    def on_post_save_async(self, view):
        # ftp-settings
        server = "ftp.your-server.com"
        user = "USER_NAME"
        password = "PASSWORD"
        dir_on_server = '/upload'  # directory to store the upload

        # check if current file allowed to upload
        fn = sublime.active_window().active_view().file_name()
        basename = os.path.split(fn)[1]
        allowed_extensions = '.lua','.py']  # list with allowed extensions
        if os.path.splitext(fn)[1] not in allowed_extensions:
            return

        try:
            # new session
            session = ftplib.FTP(server, user, password)

            # change into the directory on the server, to upload
            session.cwd(dir_on_server)

            # open current file binary
            fb = open(fn, 'rb')

            # send the file
            session.storbinary(('STOR %s' % basename), fb)

            # close the file
            fb.close()

            # close the connection
            session.quit()
            print('Upload successfully!')

        except Exception as e:
            print('Upload has failed!')
            print("Error {0}".format(str(e)))
0 Likes

#4

Thank you very much for this!

0 Likes