Project

General

Profile

1
import time
2
from watchdog.observers import Observer
3
from watchdog.events import FileSystemEventHandler
4
import os
5
from os import listdir
6
from os.path import isdir, join, exists
7

    
8

    
9
def get_latest_name(m_path, b_path):
10
    pt= m_path.replace(b_path,'')
11
    data =pt.split('/')
12
    if len(data[0]) > 1:
13
        return data[0]+'-LATEST.war'
14
    else:
15
        return data[1]+'-LATEST.war'
16

    
17
class MyHandler(FileSystemEventHandler):
18

    
19
    def on_any_event(self, event):
20
        if event.event_type == 'created':
21
            if len(event.src_path) >4:
22
                if event.src_path[-4:] == '.war' and 'LATEST.war' not in event.src_path:
23
                    self.update_symbolic_link(event.src_path)
24

    
25
    def update_symbolic_link(self, input_path):
26
        data = input_path.split('/')
27
        symbolic_link= "/".join(data[0:5])+"/"+ get_latest_name(input_path,'/var/www/ci_upload/')
28
        print symbolic_link
29
        print input_path
30
        print get_latest_name(input_path,'/var/www/ci_upload/')
31
        if exists(symbolic_link):
32
            os.system("rm %s" %symbolic_link)
33
        print "updating symbolic link"
34
        os.system("ln -s "+input_path+ " "+ symbolic_link)
35
        print "garbage old version"
36
        self.try_to_delete_previous('/var/www/ci_upload/')
37

    
38
    def try_to_delete_previous(self, base_path):
39
        project_dir = [f for f in listdir(base_path) if isdir(join(base_path, f))]
40

    
41
        for item in project_dir:
42
            newPath=join(base_path, item)
43
            folder_dir = [f for f in listdir(newPath) if isdir(join(newPath, f))]
44
            if len(folder_dir)>10:
45
                folder_dir.sort()
46
                for k in  folder_dir[0:-10]:
47
                    print "Deleting "+join(newPath,k)
48
                    os.system("rm -rf "+join(newPath,k))
49

    
50

    
51
if __name__ == "__main__":
52
    event_handler = MyHandler()
53
    observer = Observer()
54
    observer.schedule(event_handler, path='/var/www/ci_upload/', recursive=True)
55
    observer.start()
56

    
57
    try:
58
        while True:
59
            time.sleep(1)
60
    except KeyboardInterrupt:
61
        observer.stop()
62
    observer.join()
(2-2/6)