filesystem.py 22.6 KB
Newer Older
Marcel's avatar
Marcel committed
1
# -*- coding: utf-8 -*-
2

Marcel's avatar
Marcel committed
3
# imports
4
5
from StringIO import StringIO
from distutils.spawn import find_executable
6
7
from mimetypes import guess_type
from zipfile import ZipFile
8
from threading import Lock
9
import ConfigParser
10
import json
11
12
13
14
import logging
import os
import re
import shutil
Gero Müller's avatar
Gero Müller committed
15
import stat
16
import subprocess
17
18
import fsmonitor
import vispa
19
20
21

try:
    import Image
Gero Müller's avatar
Gero Müller committed
22
    import ImageFilter
23
24
25
26
27
28
29
30
31
32
    HAVE_PIL = True
except:
    HAVE_PIL = False

if not HAVE_PIL:
    convert_executable = find_executable('convert')
    if convert_executable and os.path.isfile(convert_executable):
        HAVE_CONVERT = True
    else:
        HAVE_CONVERT = False
33

34
35
logger = logging.getLogger(__name__)

36

37
38
class FileSystem(object):

39
40
    FILE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "ps", "eps", "pdf",
                       "txt", "xml", "py", "c", "cpp", "root", "pxlio"]
Marcel's avatar
Marcel committed
41
42
43
    BROWSER_EXTENSIONS = ["png", "jpg", "jpeg", "bmp"]
    ADDITIONAL_MIMES = {
        "pxlio": "text/plain",
44
        "root": "text/plain"
Marcel's avatar
Marcel committed
45
    }
46
47
48
49

    def __init__(self):
        # allowed extensions
        self.allowed_extensions = FileSystem.FILE_EXTENSIONS
50
51
52
53
54
55
56
        self._monitor_thread = fsmonitor.FSMonitorThread(self._monitor_callback)
        self._monitor_watches = {}
        self._monitor_listener = {}
        self._monitor_lock = Lock()
    
    def __del__(self):
        self.close()
57

58
    def setup(self, basedir=None):
Marcel's avatar
Marcel committed
59
60
        if basedir is None:
            basedir = self.expand('~/')
murban's avatar
murban committed
61
        if not os.path.isdir(basedir):
Marcel's avatar
Marcel committed
62
            raise Exception("Basedir '%s' does not exist!" % basedir)
murban's avatar
murban committed
63
64
        # the basedir
        self.basedir = os.path.join(basedir, ".vispa")
65
66
        if os.path.isdir(self.basedir):
            return "Basedir already exists"
67
        else:
Gero Müller's avatar
Gero Müller committed
68
            os.makedirs(self.basedir, 0o700)
69
            return "Basedir now exists"
70

71
72
73
74
75
    def close(self):
        if self._monitor_thread:
            self._monitor_thread.remove_all_watches()
            self._monitor_thread.running = False
    
murban's avatar
murban committed
76
    def get_mime_type(self, filepath):
Marcel's avatar
Marcel committed
77
        filepath = self.expand(filepath)
78
79
80
81
        mime, encoding = guess_type(filepath)
        if mime is not None:
            return mime
        ext = filepath.split(".")[-1]
Gero Müller's avatar
Gero Müller committed
82
83
        if ext is not None and ext != "" and ext.lower(
        ) in FileSystem.ADDITIONAL_MIMES.keys():
84
85
86
            return FileSystem.ADDITIONAL_MIMES[ext]
        return None

murban's avatar
murban committed
87
    def check_file_extension(self, path, extensions=[]):
Marcel's avatar
Marcel committed
88
        path = self.expand(path)
89
90
91
92
93
94
95
96
        if (len(extensions) == 0):
            return True
        for elem in extensions:
            elem = elem if elem.startswith(".") else "." + elem
            if path.lower().endswith(elem.lower()):
                return True
        return False

Marcel's avatar
Marcel committed
97
98
    def exists(self, path, type=None):
        # type may be 'f' or 'd'
Marcel's avatar
Marcel committed
99
        path = self.expand(path)
100
101
        # path exists physically?
        if not os.path.exists(path):
Marcel's avatar
Marcel committed
102
103
            return None
        # type correct?
104
105
106
107
108
109
110
        target_type = 'd' if os.path.isdir(path) else 'f'
        if not type:
            return target_type
        type = type.lower()
        if type not in ['f', 'd']:
            return None
        return target_type if target_type == type else None
111

112
113
114
115
116
117
118
    def get_file_count(self, path, window_id=None, view_id=None, watch_id=None):
        # inline watch
        if window_id and view_id and watch_id:
            if self.watch(path, window_id, view_id, watch_id):
                pass
                # return -2 # don't fail atm since it would emit the wrong error message
        # actual function
119
120
121
122
123
124
        path = self.expand(path)
        if os.path.exists(path):
            return len(os.listdir(path))
        else:
            return -1

Gero Müller's avatar
Gero Müller committed
125
126
    def get_file_list(self, path, deep=False,
                      filter=None, reverse=False,
127
128
129
130
131
132
133
134
                      hide_hidden=True, encode_json=True,
                      window_id=None, view_id=None, watch_id=None):
        # inline watch
        if window_id and view_id and watch_id:
            if self.watch(path, window_id, view_id, watch_id):
                pass
                # return "" # don't fail atm since it would not be caught on the client side
        # actual function
135
        filter = re.compile(filter) if filter else None
136
        filelist = []
Marcel's avatar
Marcel committed
137
        path_expand = self.expand(path)
138
139
140
141
142
143
144
        try:
            for elem in os.listdir(path_expand):
                # hide hidden files?
                if elem.startswith('.') and hide_hidden:
                    continue

                # excluded by filters?
145
                if filter and bool(filter.search(elem)) != reverse:
146
                    continue
147
                
Gero Müller's avatar
Gero Müller committed
148
149
150
                info = {
                    'name': elem
                }
151

Gero Müller's avatar
Gero Müller committed
152
                fullpath = os.path.join(path_expand, elem)
Gero Müller's avatar
Gero Müller committed
153
                stats = os.lstat(fullpath)
Gero Müller's avatar
Gero Müller committed
154
                is_symlink = stat.S_ISLNK(stats.st_mode)
Gero Müller's avatar
Gero Müller committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
                if is_symlink:
                    realfullpath = os.path.realpath(fullpath)
                    info.update({'symlink': True, 'realpath': realfullpath})
                    if os.path.exists(realfullpath):
                        stats = os.stat(realfullpath)

                info.update({
                    'size': stats.st_size,
                    'mtime': stats.st_mtime,
                    'type': 'd' if stat.S_ISDIR(stats.st_mode) else 'f'
                })

                filelist.append(info)
                if deep:
                    filelist.extend(self.get_file_list(fullpath, deep,
                                                       filter, reverse))
        except:
            pass
173
174

        # Determine the parent
Gero Müller's avatar
Gero Müller committed
175
        # parentpath = path_expand[:-1] if path_expand.endswith(os.sep) and
Gero Müller's avatar
Gero Müller committed
176
        #    path_expand != os.sep else path_expand
177
        parentpath = os.path.dirname(path_expand)
178
179
180
        data = {'filelist': filelist, 'parentpath': parentpath}
        if encode_json:
            return json.dumps(data)
181
182
        else:
            return data
183

Gero Müller's avatar
Gero Müller committed
184
185
    def get_suggestions(
            self, path, length=1, append_hidden=True, encode_json=True):
Marcel's avatar
Marcel committed
186
187
188
        suggestions = []
        source, filter = None, None
        # does the path exist?
Marcel's avatar
Marcel committed
189
190
        path_expanded = self.expand(path)
        if os.path.exists(path_expanded):
Marcel's avatar
Marcel committed
191
            # dir case
Marcel's avatar
Marcel committed
192
            if os.path.isdir(path_expanded):
Marcel's avatar
Marcel committed
193
194
195
196
197
198
199
200
201
202
203
                if path.endswith('/'):
                    source = path
                else:
                    suggestions.append(path + os.sep)
                    return suggestions
            # file case
            else:
                return suggestions
        else:
            # try to estimate source and filter
            head, tail = os.path.split(path)
Marcel's avatar
Marcel committed
204
            if os.path.isdir(os.path.expanduser(os.path.expandvars(head))):
Marcel's avatar
Marcel committed
205
206
207
208
209
210
211
                source = head
                filter = tail

        # return empty suggestions when source is not set
        if not source:
            return suggestions

Marcel's avatar
Marcel committed
212
        files = os.listdir(os.path.expanduser(os.path.expandvars(source)))
Marcel's avatar
Marcel committed
213
214
        # resort?
        if append_hidden:
Gero Müller's avatar
Gero Müller committed
215
216
            files = sorted(
                map(lambda f: str(f), files), cmp=file_compare, key=str.lower)
217
        while (len(suggestions) < length or length == 0) and len(files):
Marcel's avatar
Marcel committed
218
219
220
221
            file = files.pop(0)
            if filter and not file.startswith(filter):
                continue
            suggestion = os.path.join(source, file)
Gero Müller's avatar
Gero Müller committed
222
223
            if not suggestion.endswith(
                    '/') and os.path.isdir(os.path.expanduser(os.path.expandvars(suggestion))):
Marcel's avatar
Marcel committed
224
225
226
                suggestion += '/'
            suggestions.append(suggestion)

227
        return suggestions if not encode_json else json.dumps(suggestions)
228

murban's avatar
murban committed
229
    def cut_slashs(self, path):
Marcel's avatar
Marcel committed
230
        path = self.expand(path)
murban's avatar
murban committed
231
        path = path[1:] if path.startswith(os.sep) else path
232
233
        if path == "":
            return path
murban's avatar
murban committed
234
        path = path[:-1] if path.endswith(os.sep) else path
235
236
        return path

murban's avatar
murban committed
237
    def create_folder(self, path, name):
Marcel's avatar
Marcel committed
238
        path = self.expand(path)
Gero Müller's avatar
Gero Müller committed
239
240
        name = self.expand(name)

241
        # folder with the same name existent?
242
        name = self.handle_file_name_collision(name, path)
Marcel's avatar
Marcel committed
243
        fullpath = os.path.join(path, name)
244
245
246
        try:
            os.mkdir(fullpath)
        except Exception as e:
247
            # raise Exception("You don't have the permission to create this folder!")
248
249
            raise Exception(str(e))

murban's avatar
murban committed
250
    def create_file(self, path, name):
Marcel's avatar
Marcel committed
251
        path = self.expand(path)
Gero Müller's avatar
Gero Müller committed
252
253
        name = self.expand(name)

254
        # file with the same name existent?
255
        name = self.handle_file_name_collision(name, path)
Marcel's avatar
Marcel committed
256
        fullpath = os.path.join(path, name)
257
258
259
260
261
262
        try:
            f = file(fullpath, "w")
            f.close()
        except Exception as e:
            raise Exception(str(e))

263
    def rename(self, path, name, new_name, force=False):
Gero Müller's avatar
Gero Müller committed
264
265
266
267
        path = self.expand(path)
        name = self.expand(name)
        new_name = self.expand(new_name)

268
269
270
271
272
273
274
        try:
            if force == False:
                new_name = self.handle_file_name_collision(new_name, path)
            name = os.path.join(path, name)
            new_name = os.path.join(path, new_name)
            os.renames(name, new_name)
            return
Gero Müller's avatar
Gero Müller committed
275
        except Exception as e:
276
            return str(e)
277

murban's avatar
murban committed
278
279
    def remove(self, path):
        if isinstance(path, list):
280
281
282
            for p in path:
                self.remove(p)
        else:
Marcel's avatar
Marcel committed
283
284
285
286
287
            path = self.expand(path)
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)
288
289

    def compress(self, path, paths, name):
Gero Müller's avatar
Gero Müller committed
290
291
        # paths has to be a list of strings
        paths = paths if isinstance(paths, (list, tuple)) else [paths]
Gero Müller's avatar
Gero Müller committed
292
        paths = [self.expand(p) for p in paths]
Gero Müller's avatar
Gero Müller committed
293
294
295

        path = path if not path.endswith(os.sep) else path[:-1]
        path = self.expand(path)
Martin Urban's avatar
Martin Urban committed
296

Gero Müller's avatar
Gero Müller committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
        name = name if name.endswith(".zip") else name + ".zip"
        name = self.handle_file_name_collision(name, path)

        fullpath = os.path.join(path, name)

        with ZipFile(fullpath, "w") as archive:
            i = 0
            while i < len(paths):
                if not paths[i]:
                    i += 1
                    continue
                p = self.expand(paths[i])
                i += 1

                if os.path.isdir(p):
                    for elem in os.listdir(p):
                        fullp = os.path.join(p, elem)
                        if os.path.isdir(fullp):
                            paths.append(fullp)
                        else:
Gero Müller's avatar
Gero Müller committed
317
318
                            ap = fullp[
                                len(path):] if fullp.startswith(path) else fullp
Gero Müller's avatar
Gero Müller committed
319
320
321
                            logger.debug(fullp)
                            archive.write(fullp, ap)
                else:
Martin Urban's avatar
Martin Urban committed
322
                    ap = p[len(path):] if p.startswith(path) else p
Gero Müller's avatar
Gero Müller committed
323
                    logger.debug(p)
Martin Urban's avatar
Martin Urban committed
324
                    archive.write(p, ap)
325

326
    def paste(self, path, fullsrc, cut):
Marcel's avatar
Marcel committed
327
        # TODO
328
329
330
331
        path = self.expand(path)
        if isinstance(fullsrc, (list, tuple)):
            for p in fullsrc:
                p = self.expand(p)
murban's avatar
murban committed
332
                self.paste(path, p, cut)
333
334
            return True

335
336
        # fulltarget = os.path.join(path, fullsrc.split(os.sep)[-1])
        logger.error("")
Gero Müller's avatar
Gero Müller committed
337
338
        target = self.handle_file_name_collision(
            fullsrc.split(os.sep)[-1], path)
339
        fulltarget = os.path.join(path, target)
340

341
342
        if os.path.isdir(fullsrc):
            shutil.copytree(fullsrc, fulltarget)
343
            if cut:
344
                shutil.rmtree(fullsrc)
345
        else:
346
            shutil.copy2(fullsrc, fulltarget)
347
            if cut:
348
                os.remove(fullsrc)
349

350
351
    def save_file(self, path, content, force=True, binary=False,
                   utf8=False, window_id=None, view_id=None, watch_id=None):
Marcel's avatar
Marcel committed
352
        path = self.expand(path)
Marcel's avatar
Marcel committed
353
        # check if file already exists
murban's avatar
murban committed
354
        if os.path.exists(path) and not force:
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
            return json.dumps({
                "mtime": 0,
                "success": False,
                "watch_error": ""
            })
        if utf8:
            content = content.encode('utf8')
        try:
            with open(path, "wb" if binary else "w") as f:
                f.write(content)
            mtime = os.path.getmtime(path)
        except Exception as e:
            mtime  = 0
        
        # inline watch
        if window_id and view_id and watch_id:
            watch_error = self.watch(path, window_id, view_id, watch_id)
372
        else:
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
            watch_error = ""
        
        return json.dumps({
            "mtime": os.path.getmtime(path),
            "success": mtime > 0,
            "watch_error": watch_error
        })
    
    def get_file(self, path, binary=False,
                  utf8=False, window_id=None, view_id=None, watch_id=None):
        # inline watch
        if window_id and view_id and watch_id:
            watch_error = self.watch(path, window_id, view_id, watch_id)
        else:
            watch_error = ""
        
        # actual function
        path = self.expand(path)
        try:
            with open(path, "rb" if binary else "r") as f:
                content = f.read()
            if utf8:
                content = content.decode('utf8')
            mtime = os.path.getmtime(path)
        except Exception as e:
            mtime  = 0
            content = ""
        
        return json.dumps({
            "content": content,
            "mtime": mtime,
            "success": mtime > 0,
            "watch_error": watch_error
        })
407

Gero Müller's avatar
Gero Müller committed
408
    def save_file_content(self, filename, content,
Gero Müller's avatar
Gero Müller committed
409
                          path=None, force=True, append=False):
410
411
        # check write permissions
        # if not self.checkPermission(username, vPath, 'w'):
Gero Müller's avatar
Gero Müller committed
412
413
414
415
416
417
        #    return False, "Permission denied!"

        if path:
            filename = os.path.join(path, filename)
        filename = self.expand(filename)

418
        # check if file already exists
Gero Müller's avatar
Gero Müller committed
419
420
421
422
423
424
425
426
427
        if os.path.exists(filename) and not force:
            return False, "The file '%s' already exists!" % filename

        out = open(filename, "ab+" if append else "wb")
        out.write(content)
        out.close()

        return True, "File saved!"

murban's avatar
murban committed
428
    def get_file_content(self, path):
Marcel's avatar
Marcel committed
429
        path = self.expand(path)
Gero Müller's avatar
Gero Müller committed
430
        f = open(path, "rb")
431
432
        content = f.read()
        f.close()
Marcel's avatar
Marcel committed
433
        return content
434

Marcel's avatar
Marcel committed
435
    def get_mtime(self, path):
Marcel's avatar
Marcel committed
436
        path = self.expand(path)
Marcel's avatar
Marcel committed
437
438
        return os.path.getmtime(path)

murban's avatar
murban committed
439
    def is_browser_file(self, path):
Marcel's avatar
Marcel committed
440
        path = self.expand(path)
441
        extension = path.split(".")[-1]
442
        return extension.lower() in FileSystem.BROWSER_EXTENSIONS
443

murban's avatar
murban committed
444
    def handle_file_name_collision(self, name, path):
445
        # collision?
murban's avatar
murban committed
446
        files = os.listdir(path)
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
        if name not in files:
            return name

        # when this line is reached, there is a collision!

        # cut the file extension
        extension = name.split(".")[-1]
        prename = None
        if name == extension:
            extension = ""
            prename = name
        else:
            prename = name.split("." + extension)[0]

        # has the name already a counter at its end?
        hasCounter = False
        preprename = None
        counter = prename.split("_")[-1]

        if counter != prename:
            try:
                counter = int(counter)
                hasCounter = True
                preprename = "_".join(prename.split("_")[:-1])
            except:
                pass

        if hasCounter:
            # increment and try again
            counter += 1
Gero Müller's avatar
Gero Müller committed
477
478
479
            newname = "%s_%d%s" % (preprename,
                                   counter,
                                   "" if extension == "" else "." + extension)
480
        else:
Gero Müller's avatar
Gero Müller committed
481
482
            newname = "%s_1%s" % (
                prename, "" if extension == "" else "." + extension)
483
484

        # return
murban's avatar
murban committed
485
        return self.handle_file_name_collision(newname, path)
Marcel's avatar
Marcel committed
486

Marcel's avatar
Marcel committed
487
488
    def expand(self, path):
        return os.path.expanduser(os.path.expandvars(path))
Marcel's avatar
Marcel committed
489

Gero Müller's avatar
Gero Müller committed
490
    def thumbnail(self, path, width=100, height=100, sharpen=True):
491
492
493
        path = self.expand(path)
        if HAVE_PIL:
            output = StringIO()
Gero Müller's avatar
Gero Müller committed
494
            img = Image.open(path)
Gero Müller's avatar
Gero Müller committed
495
            img.thumbnail((width, height), Image.ANTIALIAS)
Gero Müller's avatar
Gero Müller committed
496
            if sharpen:
497
                img.filter(ImageFilter.SHARPEN)
Gero Müller's avatar
Gero Müller committed
498
            img.save(output, "JPEG")
499
500
501
502
503
504
505
506
507
508
509
510
            contents = output.getvalue()
            output.close()
            return contents
        elif HAVE_CONVERT:
            cmd = ['convert', path,
                   '-thumbnail', '%dx%d' % (width, height),
                   'jpeg:-']
            p = subprocess.Popen(cmd, stdin=None, stdout=subprocess.PIPE)
            return p.communicate()[0]
        else:
            return self.get_file_content(path)

511
512
513
514
    def _monitor_callback(self, event):
        if event.action_name == 'access':
            return
        
515
516
517
518
519
        if os.path.exists(event.watch.path):
            mtime = os.path.getmtime(event.watch.path)
        else:
            mtime = -1
        
520
521
522
523
524
525
526
527
528
        with self._monitor_lock:
            # inform all listener
            for combined_id in event.watch.listener:
                vispa.remote.send_topic(
                    "extension.%s.socket.watch" % combined_id[1],
                    window_id=combined_id[0],
                    data={
                        "path": event.watch.path,
                        "action_name": event.action_name,
529
530
                        "watch_id": combined_id[2],
                        "mtime": mtime
531
532
533
                    })
            
            # cleanup yourself
534
            if event.action_name in ['delete self','move self']:
535
536
                for combined_id in event.watch.listener:
                    del self._monitor_listener[combined_id]
537
                event.watch.listener = []
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
                self._check_watch(event.watch)
    
    def _check_watch(self, watch):
        if len(watch.listener) == 0:
            del self._monitor_watches[watch.path]
            self._monitor_thread.remove_watch(watch)
        
    def watch(self, path, window_id, view_id, watch_id):
        # fail if there is no such fie
        path = self.expand(path)
        if not os.path.exists(path):
            return "The file does not exist"
        combined_id = (window_id, view_id, watch_id)
        
        with self._monitor_lock:
            # watch is in use
            if combined_id in self._monitor_listener:
                # has path changed?
                if self._monitor_listener[combined_id].path == path:
                    return ""
                else:
                    self._monitor_listener[combined_id].listener.remove(combined_id)
                    self._check_watch(self._monitor_listener[combined_id])
                    del self._monitor_listener[combined_id]
            
            # create or get the desired watch
            if path not in self._monitor_watches:
                if os.path.isfile(path):
                    watch = self._monitor_thread.add_file_watch(path)
                elif os.path.isdir(path):
                    watch = self._monitor_thread.add_dir_watch(path)
                else:
                    return "This kind of file can't be wachted"
                watch.listener = []
                self._monitor_watches[path] = watch
            else:
                watch = self._monitor_watches[path]
            
            if combined_id in watch.listener:
                return "This file is already watched" # this should never occur
            
            watch.listener.append(combined_id)
            self._monitor_listener[combined_id] = watch

        return ""
        
    def unwatch(self, window_id, view_id, watch_id=None):
        with self._monitor_lock:
            if watch_id is None:
                # will perform poor with lots of watches/listener
                for path, watch in self._monitor_watches.items():
                    for combined_id in watch.listener:
                        if window_id==combined_id[0] and view_id==combined_id[1]:
                            watch.listener.remove(combined_id)
                            del self._monitor_listener[combined_id]
                    
                    self._check_watch(watch)
            
            else:
                combined_id = (window_id, view_id, watch_id)
                if combined_id in self._monitor_listener:
                    self._monitor_listener[combined_id].listener.remove(combined_id)
                    self._check_watch(self._monitor_listener[combined_id])
                    del self._monitor_listener[combined_id]

        return ""

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
    def get_from_public_workspaceini(self, section, option):
        try:
            config = ConfigParser.ConfigParser()
            config.read("/etc/vispa/workspace.ini")
            return json.dumps({
                "content": config.get(section, option),
                "success": True
                })
        except Exception as e:
            return json.dumps({
                "content": str(e),
                "success": False
                })

    def get_from_private_workspaceini(self, section, option):
        try:
            config = ConfigParser.ConfigParser()
            config.read(os.path.expanduser(os.path.expandvars("$HOME/.vispa/workspace.ini")))
            return json.dumps({
                "content": config.get(section, option),
                "success": True
                })
        except Exception as e:
            return json.dumps({
                "content": str(e),
                "success": False
                })

    def set_to_private_workspaceini(self, section, option, value):
        try:
            config = ConfigParser.ConfigParser()
            config.read(os.path.expanduser(os.path.expandvars("$HOME/.vispa/workspace.ini")))
            if (config.has_section(section)):
                config.set(section, option, value)
            else:
                config.add_section(section)
                config.set(section, option, value)
            workspaceini = open(os.path.expanduser(os.path.expandvars("$HOME/.vispa/workspace.ini")), "w")
            config.write(workspaceini)
            workspaceini.close()
            return json.dumps({
                "message": "Written successfully",
                "success": True
                })
        except Exception as e:
            return json.dumps({
                "message": str(e),
                "success": False
                })
654

Marcel's avatar
Marcel committed
655
656
657
658
659
660
661
662
def string_compare(a, b):
    if a == b:
        return 0
    elif a > b:
        return 1
    else:
        return -1

663

Marcel's avatar
Marcel committed
664
665
666
667
668
669
670
671
672
def file_compare(a, b):
    if not a.startswith('.') and not b.startswith('.'):
        return string_compare(a, b)
    elif a.startswith('.') and b.startswith('.'):
        return string_compare(a, b)
    elif a.startswith('.') and not b.startswith('.'):
        return 1
    elif not a.startswith('.') and b.startswith('.'):
        return -1