Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/45 does not open new tab for already opened file #55

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
73 changes: 58 additions & 15 deletions rsub.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,33 @@

SESSIONS = {}
server = None
WORKDIR = None


def say(msg):
print('[rsub] ' + msg)

# https://www.jacobtomlinson.co.uk/2014/02/16/python-script-recursively-remove-empty-folders-directories/
def removeEmptyFolders( path, removeRoot=True ):
'Function to remove empty folders'
if not os.path.isdir(path):
return

# remove empty subfolders
files = os.listdir(path)
if len(files):
for f in files:
fullpath = os.path.join(path, f)
if os.path.isdir(fullpath):
removeEmptyFolders(fullpath)

# if folder empty, delete it
files = os.listdir(path)
if len(files) == 0 and removeRoot:
print( "Removing empty folder:", path )
os.rmdir(path)



class Session:
def __init__(self, socket):
Expand All @@ -34,7 +56,8 @@ def __init__(self, socket):
self.in_file = False
self.parse_done = False
self.socket = socket
self.temp_path = None
self.temp_file = None


def parse_input(self, input_line):
if (input_line.strip() == b"open" or self.parse_done is True):
Expand Down Expand Up @@ -66,48 +89,61 @@ def parse_file(self, line):
self.file += line

def close(self):
global WORKDIR
self.socket.send(b"close\n")
self.socket.send(b"token: " + self.env['token'].encode("utf8") + b"\n")
self.socket.send(b"\n")
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
os.unlink(self.temp_path)
os.rmdir(self.temp_dir)
os.unlink(self.temp_file)
try:
removeEmptyFolders( WORKDIR, True )
except OSError as e:
sublime.error_message( 'Can not clean WORKDIR: %s' % e )


def send_save(self):
self.socket.send(b"save\n")
self.socket.send(b"token: " + self.env['token'].encode("utf8") + b"\n")
temp_file = open(self.temp_path, "rb")
temp_file = open(self.temp_file, "rb")
new_file = temp_file.read()
temp_file.close()
self.socket.send(b"data: " + str(len(new_file)).encode("utf8") + b"\n")
self.socket.send(new_file)
self.socket.send(b"\n")

def on_done(self):
global WORKDIR
# Create a secure temporary directory, both for privacy and to allow
# multiple files with the same basename to be edited at once without
# overwriting each other.

self.env['host'] = self.env['display-name'].split(':')[0]
self.temp_dir = WORKDIR +"/" +self.env['host'] +os.path.dirname( self.env['real-path'] )

try:
self.temp_dir = tempfile.mkdtemp(prefix='rsub-')
if not os.path.exists( self.temp_dir ) :
os.makedirs( self.temp_dir )
except OSError as e:
sublime.error_message('Failed to create rsub temporary directory! Error: %s' % e)
return
self.temp_path = os.path.join(self.temp_dir,
os.path.basename(self.env['display-name'].split(':')[-1]))
self.temp_file = os.path.join(
self.temp_dir,
os.path.basename( self.env['display-name'].split(':')[-1] )
)
try:
temp_file = open(self.temp_path, "wb+")
temp_file = open( self.temp_file, "wb+" )
temp_file.write(self.file[:self.file_size])
temp_file.flush()
temp_file.close()
except IOError as e:
# Remove the file if it exists.
if os.path.exists(self.temp_path):
os.remove(self.temp_path)
if os.path.exists( self.temp_file ):
os.remove( self.temp_file )
try:
os.rmdir(self.temp_dir)
except OSError:
pass
removeEmptyFolders( self.temp_dir )
except OSError as e:
sublime.error_message( 'Can not clean WORKDIR: %s' % e )

sublime.error_message('Failed to write to temp file! Error: %s' % str(e))

Expand All @@ -116,7 +152,7 @@ def on_done(self):
sublime.run_command("new_window")

# Open it within sublime
view = sublime.active_window().open_file(self.temp_path)
view = sublime.active_window().open_file( self.temp_file )

# Add the file metadata to the view's settings
# This is mostly useful to obtain the path of this file on the server
Expand Down Expand Up @@ -186,7 +222,7 @@ def on_close(self, view):


def plugin_loaded():
global SESSIONS, server
global SESSIONS, WORKDIR, server

# Load settings
settings = sublime.load_settings("rsub.sublime-settings")
Expand All @@ -198,6 +234,13 @@ def plugin_loaded():
Thread(target=start_server, args=[]).start()
say('Server running on ' + host + ':' + str(port) + '...')

try:
WORKDIR = tempfile.mkdtemp(prefix='rsub-')
except OSError as e:
sublime.error_message('Failed to create rsub temporary working directory! Error: %s' % e)
return


# call the plugin_loaded() function if running in sublime text 2
if (int(sublime.version())< 3000):
plugin_loaded()