Exemple #1
0
    def execute(my):
        filename = my.kwargs.get("filename")
        ticket = my.kwargs.get("ticket")
        upload_dir = Environment.get_upload_dir(ticket=ticket)
        # can't rely on that
        #ticket = Environment.get_ticket()
        asset_temp_dir = "%s/temp/%s" % (Environment.get_asset_dir(), ticket)

        if not os.path.exists(asset_temp_dir):
            os.makedirs(asset_temp_dir)

        from_path = "%s/%s" % (upload_dir, filename)
        icon_creator = IconCreator(from_path)
        icon_creator.execute()
        icon_path = icon_creator.get_icon_path()

        to_path = "%s/%s" % (asset_temp_dir, filename)

        if icon_path:
            shutil.copy(icon_path, to_path)
            my.info = {
                "web_path": "/assets/temp/%s/%s" % (ticket, filename),
                "lib_path": to_path
            }
        else:
            my.info = {}
Exemple #2
0
    def delete_sobject(my, sobject):

        search_type = sobject.get_base_search_type()

        # this is used by API method delete_sobject
        auto_discover = my.kwargs.get("auto_discover")
        
        values = my.kwargs.get("values")
        if values:
            related_types = values.get("related_types")
        elif auto_discover:
            related_types = SearchType.get_related_types(search_type, direction="children")
        else:
            related_types = None

        # always delete notes and task and snapshot
        #if not related_types:
        #    related_types = ['sthpw/note', 'sthpw/task', 'sthpw/snapshot']
        #related_types = my.schema.get_related_search_types(search_type)
        if related_types:
            for related_type in related_types:
                if not related_type or related_type == search_type:
                    continue

                # snapshots take care of sthpw/file in the proper manner, so
                # skip them here
                if related_type == 'sthpw/file':
                    continue

                related_sobjects = sobject.get_related_sobjects(related_type)
                for related_sobject in related_sobjects:
                    if related_type == 'sthpw/snapshot':
                        my.delete_snapshot(related_sobject)
                    else:
                        related_sobject.delete()


        # implicitly remove "directory" files associated with the sobject
        search = Search("sthpw/file")
        search.add_op("begin")
        search.add_filter("file_name", "")
        search.add_null_filter("file_name")
        search.add_op("or")
        search.add_parent_filter(sobject)
        file_objects = search.get_sobjects()
        for file_object in file_objects:
            base_dir = Environment.get_asset_dir()
            relative_dir = file_object.get("relative_dir")
            lib_dir = "%s/%s" % (base_dir, relative_dir)
            print "removing: ", lib_dir
            FileUndo.rmdir(lib_dir)
            file_object.delete()


        # finally delete the sobject
        print "deleting: ", sobject.get_search_key()
        if search_type == 'sthpw/snapshot':
            my.delete_snapshot(sobject)
        else:
            sobject.delete()
Exemple #3
0
    def add_file_behaviors(self, item_div, dirname, basename):
        """
        item_div.add_behavior( {
        'type': 'click_up',
        'dirname': dirname,
        'basename': basename,
        'cbjs_action': '''
        var top = bvr.src_el.getParent(".spt_repo_browser_top");
        var content = top.getElement(".spt_repo_browser_content");
        var class_name = "tactic.ui.tools.repo_browser_wdg.RepoBrowserContentWdg";
        var kwargs = {
          dirname: bvr.dirname,
          basename: bvr.basename
        };
        spt.panel.load(content, class_name, kwargs);
        '''
        } )
        """

        # convert this to a repo directory
        asset_dir = Environment.get_asset_dir()


        # FIXME: not sure how general this
        webdirname = "/assets/%s" % dirname.replace(asset_dir, "")

        item_div.add_behavior( {
        'type': 'click_up',
        'webdirname': webdirname,
        'basename': basename,
        'cbjs_action': '''
        window.open(bvr.webdirname + "/" + bvr.basename, '_blank');
        '''
        } )
Exemple #4
0
    def delete_sobject(my, sobject):

        search_type = sobject.get_base_search_type()

        # this is used by API method delete_sobject
        auto_discover = my.kwargs.get("auto_discover")
        
        values = my.kwargs.get("values")
        if values:
            related_types = values.get("related_types")
        elif auto_discover:
            related_types = SearchType.get_related_types(search_type, direction="children")
        else:
            related_types = None

        # always delete notes and task and snapshot
        #if not related_types:
        #    related_types = ['sthpw/note', 'sthpw/task', 'sthpw/snapshot']
        #related_types = my.schema.get_related_search_types(search_type)
        if related_types:
            for related_type in related_types:
                if not related_type or related_type == search_type:
                    continue

                # snapshots take care of sthpw/file in the proper manner, so
                # skip them here
                if related_type == 'sthpw/file':
                    continue

                related_sobjects = sobject.get_related_sobjects(related_type)
                for related_sobject in related_sobjects:
                    if related_type == 'sthpw/snapshot':
                        my.delete_snapshot(related_sobject)
                    else:
                        related_sobject.delete()


        # implicitly remove "directory" files associated with the sobject
        search = Search("sthpw/file")
        search.add_op("begin")
        search.add_filter("file_name", "")
        search.add_null_filter("file_name")
        search.add_op("or")
        search.add_parent_filter(sobject)
        file_objects = search.get_sobjects()
        for file_object in file_objects:
            base_dir = Environment.get_asset_dir()
            relative_dir = file_object.get("relative_dir")
            lib_dir = "%s/%s" % (base_dir, relative_dir)
            print "removing: ", lib_dir
            FileUndo.rmdir(lib_dir)
            file_object.delete()


        # finally delete the sobject
        print "deleting: ", sobject.get_search_key()
        if search_type == 'sthpw/snapshot':
            my.delete_snapshot(sobject)
        else:
            sobject.delete()
Exemple #5
0
    def get_files(self):

        paths = []

        # remember this here for now
        self.files = {}
        self.snapshots = {}

        search_key = self.kwargs.get("search_key")
        sobject = SearchKey.get_by_search_key(search_key)
        # if it is deleted, return
        if not sobject:
            return []

        if isinstance(sobject, Snapshot):
            snapshots = [sobject]
        else:
            snapshots = Snapshot.get_by_sobject(sobject, "publish")

        for snapshot in snapshots:
            snapshot_paths = snapshot.get_all_lib_paths()

            files = snapshot.get_all_file_objects()

            for path, file in zip(snapshot_paths, files):

                # if the path is a directory, get all of the files
                if os.path.isdir(path):
                    for root, dirnames, filenames in os.walk(path):

                        for filename in filenames:
                            item_path = "%s/%s" % (root, filename)
                            paths.append(item_path)
                            self.files[item_path] = file
                            self.snapshots[item_path] = snapshot

                        for dirname in dirnames:
                            item_path = "%s/%s/" % (root, dirname)
                            paths.append(item_path)
                            self.files[item_path] = file
                            self.snapshots[item_path] = snapshot
                    """
                    dirlist = os.listdir(path)
                    for item in dirlist:
                        item_path = "%s%s" % (path, item)
                        if os.path.isdir(path):
                            item_path = "%s/" % item_path
                        paths.append(item_path)
                        self.files[path] = file
                    """

                else:
                    paths.append(path)
                    self.files[path] = file
                    base_dir_alias = file.get_value('base_dir_alias')
                    if not self.base_dir and base_dir_alias:
                        self.base_dir = Environment.get_asset_dir(
                            alias=base_dir_alias)

        return paths
Exemple #6
0
    def get_file_paths(my, transaction, mode='lib'):

        transaction_xml = transaction.get_xml_value("transaction")
        if not transaction_xml:
            return []

        from pyasm.common import Xml, Environment

        if isinstance(transaction_xml, basestring):
            xml = Xml()
            xml.read_string(transaction_xml)
        else:
            xml = transaction_xml


        base_dir = Environment.get_asset_dir()
        paths = []


        # get all of the file nodes
        nodes = xml.get_nodes("transaction/file")
        for node in nodes:

            if xml.get_attribute(node, "type") == 'create':
                src = xml.get_attribute(node, "src")

                if mode == 'relative':
                    path = src
                else:
                    path = "%s/%s" % (base_dir, src)
                paths.append(path)

        return paths
    def execute(my):
        filename = my.kwargs.get("filename")
        ticket = my.kwargs.get("ticket")
        upload_dir = Environment.get_upload_dir(ticket=ticket)
        # can't rely on that
        #ticket = Environment.get_ticket()
        asset_temp_dir = "%s/temp/%s" % (Environment.get_asset_dir(), ticket)

        if not os.path.exists(asset_temp_dir):
            os.makedirs(asset_temp_dir)

        from_path = "%s/%s" % (upload_dir, filename)
        icon_creator = IconCreator(from_path)
        icon_creator.execute()
        icon_path = icon_creator.get_icon_path()

        to_path = "%s/%s" % (asset_temp_dir, filename)
        
        if icon_path:
            shutil.copy(icon_path, to_path)
            my.info = {
                "web_path": "/assets/temp/%s/%s" % (ticket, filename),
                "lib_path": to_path
            }
        else:
            my.info = {}
Exemple #8
0
    def verify_dir(my, base):

        # ignore transactions that a derived from this server
        server_code = Config.get_value("install", "server")
        if base.startswith("%sTRANSACTION" % server_code):
            return False

        if base.find("TRANSACTION") == -1:
            return False

        if not os.path.isdir(base):
            if base.endswith(".zip.enc"):
                return True
            elif base.endswith(".zip"):
                return True
            else:
                return False

        asset_dir = Environment.get_asset_dir()

        transaction_path = "%s/_transaction.xml" % base
        if not os.path.exists(transaction_path):
            return False

        xml = Xml()
        xml.read_file(transaction_path)

        nodes = xml.get_nodes("transaction/file")

        # verify that all the files are present
        for node in nodes:

            code = xml.get_attribute(node, "code")

            file_sobj = Search.get_by_code("sthpw/file", code)

            src = xml.get_attribute(node, "src")
            rel_path = xml.get_attribute(node, "rel_path")

            src_path = "%s/%s" % (base, rel_path)
            if not os.path.exists(src_path):
                print "[%s] has not arrived" % src_path
                return False

            st_size = xml.get_attribute(node, "size")
            if st_size:
                st_size = int(st_size)
            else:
                st_size = -1
            md5 = xml.get_attribute(node, "md5")

            if st_size != -1:
                # check that the size is the same
                if st_size != os.path.getsize(src_path):
                    print "[%s] size does not match" % src_path
                    return False

        # all the tests have passed
        return True
Exemple #9
0
 def get_preallocated_dir(my):
     preallocated = my.snapshot.get_preallocated_path(file_type='maya', file_name='what.ma',ext='ma')
     preallocated_dir_name = os.path.dirname(preallocated)
     preallocated_dir_name = preallocated_dir_name.replace('%s/' %Environment.get_asset_dir(), '')
     # remove the base part
     preallocated_dir_names = preallocated_dir_name.split('/')
     
     preallocated_dir_name = '/'.join(preallocated_dir_names)
     return preallocated_dir_name
Exemple #10
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub

            server = TacticServerStub.get(protocol="local")
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == "none_found":
            # raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias="main"))
            return layout

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir, rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR")
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            f = open(path, "r")
            count = 0
            for line in f:
                line = my.filter_line(line, count)
                html.append(line)
                count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Exemple #11
0
    def do_delete(self, sobject, related_types=None):

        search_type = sobject.get_base_search_type()

        # always delete notes and task and snapshot
        if not related_types:
            related_types = ['sthpw/note', 'sthpw/task', 'sthpw/snapshot']
        #related_types = self.schema.get_related_search_types(search_type)

        if related_types:
            for related_type in related_types:
                if not related_type or related_type == search_type:
                    continue

                # snapshots take care of sthpw/file in the proper manner, so
                # skip them here
                if related_type == 'sthpw/file':
                    continue

                related_sobjects = sobject.get_related_sobjects(related_type)
                for related_sobject in related_sobjects:
                    if related_type == 'sthpw/snapshot':
                        self.delete_snapshot(related_sobject)
                    else:
                        related_sobject.delete()
                        #self.do_delete(related_sobject)


        # implicitly remove "directory" files associated with the sobject
        search = Search("sthpw/file")
        search.add_op("begin")
        search.add_filter("file_name", "")
        search.add_null_filter("file_name")
        search.add_op("or")
        search.add_parent_filter(sobject)
        file_objects = search.get_sobjects()

        #if file_objects:
        #    print("Removing [%s] file objects" % len(file_objects))

        for file_object in file_objects:
            base_dir = Environment.get_asset_dir()
            relative_dir = file_object.get("relative_dir")
            lib_dir = "%s/%s" % (base_dir, relative_dir)
            FileUndo.rmdir(lib_dir)
            file_object.delete()


        # finally delete the sobject
        print("Deleting: ", sobject.get_search_key())
        if search_type == 'sthpw/snapshot':
            self.delete_snapshot(sobject)
        else:
            sobject.delete()
Exemple #12
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub
            server = TacticServerStub.get(protocol='local')
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == 'none_found':
            #raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias='main'))
            return layout

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir, rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir, rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR")
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            f = open(path, 'r')
            count = 0
            for line in f:
                line = my.filter_line(line, count)
                html.append(line)
                count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Exemple #13
0
    def do_delete(self, sobject, related_types=None):

        search_type = sobject.get_base_search_type()

        # always delete notes and task and snapshot
        if not related_types:
            related_types = ['sthpw/note', 'sthpw/task', 'sthpw/snapshot']
        #related_types = self.schema.get_related_search_types(search_type)

        if related_types:
            for related_type in related_types:
                if not related_type or related_type == search_type:
                    continue

                # snapshots take care of sthpw/file in the proper manner, so
                # skip them here
                if related_type == 'sthpw/file':
                    continue

                related_sobjects = sobject.get_related_sobjects(related_type)
                for related_sobject in related_sobjects:
                    if related_type == 'sthpw/snapshot':
                        self.delete_snapshot(related_sobject)
                    else:
                        related_sobject.delete()
                        #self.do_delete(related_sobject)

        # implicitly remove "directory" files associated with the sobject
        search = Search("sthpw/file")
        search.add_op("begin")
        search.add_filter("file_name", "")
        search.add_null_filter("file_name")
        search.add_op("or")
        search.add_parent_filter(sobject)
        file_objects = search.get_sobjects()

        #if file_objects:
        #    print("Removing [%s] file objects" % len(file_objects))

        for file_object in file_objects:
            base_dir = Environment.get_asset_dir()
            relative_dir = file_object.get("relative_dir")
            lib_dir = "%s/%s" % (base_dir, relative_dir)
            FileUndo.rmdir(lib_dir)
            file_object.delete()

        # finally delete the sobject
        print("Deleting: ", sobject.get_search_key())
        if search_type == 'sthpw/snapshot':
            self.delete_snapshot(sobject)
        else:
            sobject.delete()
Exemple #14
0
    def get_by_path(path):
        asset_dir = Environment.get_asset_dir()
        path = path.replace("%s/" % asset_dir, "")
        relative_dir = os.path.dirname(path)
        file_name = os.path.basename(path)

        # NOTE: this does not work with base_dir_alias

        search = Search("sthpw/file")
        search.add_filter("relative_dir", relative_dir)
        search.add_filter("file_name", file_name)
        sobject = search.get_sobject()
        return sobject
Exemple #15
0
    def get_by_path(path):
        asset_dir = Environment.get_asset_dir()
        path = path.replace("%s/" % asset_dir, "")
        relative_dir = os.path.dirname(path)
        file_name = os.path.basename(path)

        # NOTE: this does not work with base_dir_alias

        search = Search("sthpw/file")
        search.add_filter("relative_dir", relative_dir)
        search.add_filter("file_name", file_name)
        sobject = search.get_sobject()
        return sobject
Exemple #16
0
    def get_display(self):

        paths = self.get_files()

        top = self.top
        top.add_style("padding: 10px")
        top.add_color("background", "background")
        top.add_style("min-width: 500px")
        top.add_style("font-size: 12px")
        top.add_class("spt_sobject_dir_list_top")
        self.set_as_panel(top)

        inner = DivWdg()
        top.add(inner)

        show_title = self.kwargs.get("show_title")
        if show_title not in [False, 'false']:
            title_wdg = DivWdg()
            inner.add(title_wdg)
            title_wdg.add("File Browser [%s]" % self.sobject.get_code())
            title_wdg.add_color("background", "background3")
            title_wdg.add_style("padding: 16px 10px")
            title_wdg.add_style("margin: -10px -10px 10px -10px")
            title_wdg.add_style("font-weight: bold")

        show_shelf = self.kwargs.get("show_shelf")
        if show_shelf not in [False, 'false']:
            shelf_wdg = DivWdg()
            inner.add(shelf_wdg)
            shelf_wdg.add(self.get_shelf_wdg())
            shelf_wdg.add_style("padding: 5px")
            shelf_wdg.add_style("margin: -5px -5px 15px -5px")
            shelf_wdg.add_style("font-weight: bold")

        base_dir = Environment.get_asset_dir()

        dir_list = SnapshotDirListWdg(base_dir=base_dir,
                                      location="server",
                                      show_base_dir=True,
                                      paths=paths,
                                      all_open=True,
                                      files=self.files,
                                      snapshots=self.snapshots)

        inner.add(dir_list)

        if self.kwargs.get("is_refresh"):
            return inner
        else:
            return top
Exemple #17
0
    def get_display(my):

        paths = my.get_files()

        top = my.top
        top.add_style("padding: 10px")
        top.add_color("background", "background", -5)
        top.add_style("min-width: 500px")
        top.add_style("font-size: 12px")
        top.add_class("spt_sobject_dir_list_top")
        my.set_as_panel(top)

        inner = DivWdg()
        top.add(inner)


        show_title = my.kwargs.get("show_title")
        if show_title not in [False, 'false']:
            title_wdg = DivWdg()
            inner.add(title_wdg)
            title_wdg.add("File Browser [%s]" % my.sobject.get_code())
            title_wdg.add_gradient("background", "background3")
            title_wdg.add_style("padding: 5px")
            title_wdg.add_style("margin: -10px -10px 10px -10px")
            title_wdg.add_style("font-weight: bold")

        show_shelf = my.kwargs.get("show_shelf")
        if show_shelf not in [False, 'false']:
            shelf_wdg = DivWdg()
            inner.add(shelf_wdg)
            shelf_wdg.add(my.get_shelf_wdg())
            shelf_wdg.add_style("padding: 5px")
            shelf_wdg.add_style("margin: -5px -5px 15px -5px")
            shelf_wdg.add_style("font-weight: bold")




        base_dir = Environment.get_asset_dir()

        dir_list = SnapshotDirListWdg(base_dir=base_dir, location="server", show_base_dir=True,paths=paths, all_open=True, files=my.files, snapshots=my.snapshots)

        inner.add(dir_list)


        if my.kwargs.get("is_refresh"):
            return inner
        else:
            return top
Exemple #18
0
    def get_display(self):

        top = self.top
        top.add_style("padding: 10px")
        top.add_color("background", "background", -5)
        top.add_style("min-width: 600px")

        paths = self.get_files()

        # assume that all the paths are part of the same repo
        repo = 'tactic'
        for file in self.files.values():
            repo = file.get_value("repo_type", no_exception=True)
            break

        if repo == 'perforce':
            search_key = self.kwargs.get("search_key")
            sobject = SearchKey.get_by_search_key(search_key)

            project = sobject.get_project()
            depot = project.get_value("location", no_exception=True)
            if not depot:
                depot = project.get_code()
            location = '//%s' % depot

            dir_list = SnapshotDirListWdg(base_dir=location,
                                          location="scm",
                                          show_base_dir=True,
                                          paths=paths,
                                          all_open=True,
                                          files=self.files,
                                          snapshots=self.snapshots)
        else:
            # If not discovered thru base_dir_alias, use the default
            if not self.base_dir:
                self.base_dir = Environment.get_asset_dir()

            dir_list = SnapshotDirListWdg(base_dir=self.base_dir,
                                          location="server",
                                          show_base_dir=True,
                                          paths=paths,
                                          all_open=True,
                                          files=self.files,
                                          snapshots=self.snapshots)

        top.add(dir_list)

        return top
Exemple #19
0
    def download_transaction_files(self, transactions):
        '''This uses a simple httpd download mechanism to get the files.
        '''

        remote_host = sync_utils.get_remote_host()

        download_mode = 'http'

        # Try a mode where files are zipped
        if download_mode == 'zip':
            remote_server.download_zip(paths)



        # go through each transaction and look at the files
        for transaction in transactions:
            transaction_xml = transaction.get("transaction")
            cmd = TransactionFilesCmd(transaction_xml=transaction_xml, mode='relative')
            paths = cmd.execute()


            # download to the temp dir
            to_dir = Environment.get_tmp_dir()
            ticket = Environment.get_ticket()
            to_dir = "%s/%s" % (to_dir, ticket)

            # or we could download directly to that asset directory
            base_dir = Environment.get_asset_dir()

            # do the slow method
            for path in paths:
                url = "%s/assets/%s" % (remote_host, path)

                print("downloading: ", url)
                remote_server.download(url, to_dir)

                # FIXME: the problem with this is that it is not undoable
                #dirname = os.path.dirname(path)
                #to_dir = "%s/%s" % (base_dir, dirname)
                #print("to_dir: ", to_dir)


                remote_server.download(url, to_dir)
Exemple #20
0
    def execute(self):

        mode = self.kwargs.get('mode')
        if not mode:
            mode = 'lib'


        transaction_xml = self.kwargs.get("transaction_xml")
        assert(transaction_xml)

        from pyasm.common import Xml, Environment

        if isinstance(transaction_xml, basestring):
            xml = Xml()
            xml.read_string(transaction_xml)
        else:
            xml = transaction_xml


        base_dir = Environment.get_asset_dir()
        paths = []


        # get all of the file nodes
        nodes = xml.get_nodes("transaction/file")
        for node in nodes:

            if xml.get_attribute(node, "type") == 'create':
                src = xml.get_attribute(node, "src")

                if mode == 'relative':
                    path = src
                else:
                    if src.startswith(base_dir):
                        path = src
                    else:
                        path = "%s/%s" % (base_dir, src)
                paths.append(path)

        return paths
Exemple #21
0
    def execute(my):

        template_dir = Environment.get_template_dir()

        # find the 
        template_dir = my.kwargs.get("template_dir")
        if not template_dir:
            return


        path = None

        template_name = os.path.basename(template_dir)
        template_dir = os.path.dirname(template_dir)

        filenames = os.listdir(template_dir)
        for filename in filenames:
            if not filename.endswith(".zip"):
                continue

            if filename.startswith(template_name):
                path = "%s/%s" % (template_dir, filename)
                break

        if not path:
            return


        asset_dir = Environment.get_asset_dir()

        ticket = Environment.get_ticket()
        cache_dir = "%s/_cache/%s" % (asset_dir, ticket)

        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)

        shutil.copy(path, cache_dir)

        my.info["filename"] = filename
Exemple #22
0
    def execute(self):

        template_dir = Environment.get_template_dir()

        # find the 
        template_dir = self.kwargs.get("template_dir")
        if not template_dir:
            return


        path = None

        template_name = os.path.basename(template_dir)
        template_dir = os.path.dirname(template_dir)

        filenames = os.listdir(template_dir)
        for filename in filenames:
            if not filename.endswith(".zip"):
                continue

            if filename.startswith(template_name):
                path = "%s/%s" % (template_dir, filename)
                break

        if not path:
            return


        asset_dir = Environment.get_asset_dir()

        ticket = Environment.get_ticket()
        cache_dir = "%s/_cache/%s" % (asset_dir, ticket)

        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)

        shutil.copy(path, cache_dir)

        self.info["filename"] = filename
Exemple #23
0
    def get_display(my):

        top = my.top
        top.add_style("padding: 10px")
        top.add_color("background", "background", -5)
        top.add_style("min-width: 600px")

        paths = my.get_files()

       
        # assume that all the paths are part of the same repo
        repo = 'tactic'
        for file in my.files.values():
            repo = file.get_value("repo_type", no_exception=True)
            break

        if repo == 'perforce':
            search_key = my.kwargs.get("search_key")
            sobject = SearchKey.get_by_search_key(search_key)
     
            project = sobject.get_project()
            depot = project.get_value("location", no_exception=True)
            if not depot:
                depot = project.get_code()
            location = '//%s' % depot

            dir_list = SnapshotDirListWdg(base_dir=location, location="scm", show_base_dir=True,paths=paths, all_open=True, files=my.files, snapshots=my.snapshots) 
        else:
            # If not discovered thru base_dir_alias, use the default
            if not my.base_dir:
                my.base_dir = Environment.get_asset_dir()
            
            dir_list = SnapshotDirListWdg(base_dir=my.base_dir, location="server", show_base_dir=True,paths=paths, all_open=True, files=my.files, snapshots=my.snapshots)

        top.add(dir_list)


        return top
Exemple #24
0
    def add_file_behaviors(my, item_div, dirname, basename):
        """
        item_div.add_behavior( {
        'type': 'click_up',
        'dirname': dirname,
        'basename': basename,
        'cbjs_action': '''
        var top = bvr.src_el.getParent(".spt_repo_browser_top");
        var content = top.getElement(".spt_repo_browser_content");
        var class_name = "tactic.ui.tools.repo_browser_wdg.RepoBrowserContentWdg";
        var kwargs = {
          dirname: bvr.dirname,
          basename: bvr.basename
        };
        spt.panel.load(content, class_name, kwargs);
        '''
        } )
        """

        # convert this to a repo directory
        asset_dir = Environment.get_asset_dir()

        # FIXME: not sure how general this
        webdirname = "/assets/%s" % dirname.replace(asset_dir, "")

        item_div.add_behavior({
            'type':
            'click_up',
            'webdirname':
            webdirname,
            'basename':
            basename,
            'cbjs_action':
            '''
        window.open(bvr.webdirname + "/" + bvr.basename, '_blank');
        '''
        })
Exemple #25
0
    def copy_start(self):

        data_dir = Environment.get_data_dir(manual=True)

        # check to see if the data folder already exists
        print
        print "Data Directory [%s]" % data_dir
        install_dir = Environment.get_install_dir()

        # find criteria for initializing
        initialize = False
        if data_dir and not os.path.exists(data_dir):
            initialize = True

        if data_dir and not os.path.exists("%s/config" % data_dir):
            initialize = True

        if initialize:
            # copy the template over.  This should exist even if it is not used
            print "... not found: initializing\n"
            install_data_path = "%s/src/install/start" % (install_dir)
            if os.path.exists(install_data_path):
                dirnames = os.listdir(install_data_path)
                for dirname in dirnames:
                    to_dir = "%s/%s" % (data_dir, dirname)
                    if os.path.exists(to_dir):
                        print "WARNING: path [%s] exists ... skipping copying" % to_dir
                        continue
                    print "Copying to [%s]" % to_dir
                    from_dir = "%s/%s" % (install_data_path, dirname)
                    shutil.copytree(from_dir, to_dir)
            else:
                shutil.copytree(install_data_path, data_dir)

            # create the dist folder
            to_dir = "%s/dist" % (data_dir)
            if not os.path.exists(to_dir):
                os.makedirs(to_dir)

            # copy the appropriate config file
            if os.name == 'nt':
                filename = 'standalone_win32-conf.xml'
            else:
                filename = 'standalone_linux-conf.xml'
            install_config_path = "%s/src/install/config/%s" % (install_dir,
                                                                filename)
            to_config_path = "%s/config/tactic-conf.xml" % data_dir

            if not os.path.exists(to_config_path):
                dirname = os.path.dirname(to_config_path)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                shutil.copy(install_config_path, to_config_path)

        # some backwards compatibility issues
        old_config_path = "%s/config/tactic_linux-conf.xml" % data_dir
        if os.path.exists(old_config_path):
            new_config_path = "%s/config/tactic-conf.xml" % data_dir
            shutil.move(old_config_path, new_config_path)

        config_path = Config.get_config_path()
        config_exists = False
        if os.path.exists(config_path):
            config_exists = True

        # insert the plugin path to run get_asset_dir()
        plugin_dir = Environment.get_plugin_dir()
        sys.path.insert(0, plugin_dir)

        asset_dir = Environment.get_asset_dir()
        print "Asset Directory [%s]" % asset_dir

        tmp_dir = Environment.get_tmp_dir()
        print "Temp Directory [%s]" % tmp_dir

        # check if there is a config path already exists. If it does,
        # then don't do anything further.  This is likely a previous
        # installation
        if config_exists:
            print "Config path [%s]" % config_path
            return
        else:
            # if there is no config, retrieve data_dir in non-manual mode
            data_dir = Environment.get_data_dir()
            f = open("%s/first_run" % data_dir, 'w')
            f.write("")
            f.close()

        return
Exemple #26
0
            print
            sys.exit(2)

        self.update_tactic_configs()

        # check modules
        try:
            import tacticenv
        except ImportError:
            print 'Error: Failed to "import tacticenv"'
            return
        self.check_modules(install_db)

        # create the asset_dir
        from pyasm.common import Environment
        asset_dir = Environment.get_asset_dir()
        if not os.path.exists(asset_dir):
            os.makedirs(asset_dir)

        # check that the main directories exists
        install_dir = os.getenv("TACTIC_INSTALL_DIR")
        data_dir = os.getenv("TACTIC_DATA_DIR")
        if not os.path.exists(install_dir):
            print "Environment variable TACTIC_INSTALL_DIR '%s' does not exist" % install_dir
            return
        if not os.path.exists(data_dir):
            print "Environment variable TACTIC_DATA_DIR '%s' does not exist" % data_dir
            return

        # create the dist folder
        dist_dir = Environment.get_dist_dir()
Exemple #27
0
    def _test_file_naming_base(my):
       

        naming = SearchType.create('config/naming')
        naming.set_value('search_type','unittest/person')
        naming.set_value('context', 'naming_base_test')
        naming.set_value('dir_naming', '{project.code}/cut/{sobject.code}')
        naming.set_value('file_naming', '{sobject.code}_v{snapshot.version}_{basefile}.{ext}')
        naming.commit()
        
        my.clear_naming()

        # auto_snapshot is at v2
        preallocated = my.auto_snapshot.get_preallocated_path(file_type='some_dir', file_name='racoon',ext=None)
        from pyasm.common import Environment
        base_dir = Environment.get_asset_dir()
        my.assertEquals('%s/unittest/cut/phil/phil_v002_racoon'%base_dir, preallocated)
        
        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon',ext=None)
        my.assertEquals('%s/unittest/cut/phil/phil_v001_racoon'%base_dir, preallocated)
        
        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon.jpg',ext='jpg')
        my.assertEquals('%s/unittest/cut/phil/phil_v001_racoon.jpg'%base_dir, preallocated)


        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon2.PNG')
        my.assertEquals('%s/unittest/cut/phil/phil_v001_racoon2.PNG'%base_dir, preallocated)

        
        # test file expression
        naming.set_value('file_naming', '{@GET(.code)}_v{@GET(snapshot.version)}_{$BASEFILE}.{$EXT}')
        naming.commit()
        my.clear_naming()
        
        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon3.jpg',ext='jpg')
        my.assertEquals('%s/unittest/cut/phil/phil_v1_racoon3.jpg'%base_dir, preallocated)

        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon4.PNG')
        my.assertEquals('%s/unittest/cut/phil/phil_v1_racoon4.PNG'%base_dir, preallocated)


        # test dir expression
        naming.set_value('dir_naming', '{$PROJECT}/exp_cut/{@GET(.code)}')
        naming.commit()
        my.clear_naming()

        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon same.iff',ext='iff')
        my.assertEquals('%s/unittest/exp_cut/phil/phil_v1_racoon same.iff'%base_dir, preallocated)

        # file name clean-up is disabled in 4.2: the actual check-in logic would not replace " " with "_"
        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon 5.PNG')
        my.assertEquals('%s/unittest/exp_cut/phil/phil_v1_racoon 5.PNG'%base_dir, preallocated)
 
        # this one does not need clean-up
        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon_5.PNG')
        my.assertEquals('%s/unittest/exp_cut/phil/phil_v1_racoon_5.PNG'%base_dir, preallocated)


        # test dir expression 2

        naming.set_value('dir_naming', '{$PROJECT}/3D/QC/ShotWork/playblast/ByDate/{$TODAY,|([^\s]+)| }/{@GET(.name_first)}')

        naming.commit()
        my.clear_naming()

        preallocated = my.base_snapshot.get_preallocated_path(file_type='pic', file_name='racoon same.iff',ext='iff')

        today = datetime.datetime.today()
        today = datetime.datetime(today.year, today.month, today.day)
        today = today.strftime("%Y-%m-%d")
        my.assertEquals('%s/unittest/3D/QC/ShotWork/playblast/ByDate/%s/Philip/phil_v1_racoon same.iff'%(base_dir, today), preallocated)

        naming.delete()

        my.clear_naming()
Exemple #28
0
    def get_shelf_wdg(my):

        process = my.get_value("process")
        versions = my.get_value("versions")

        div = DivWdg()

        filter_table = Table()
        div.add(filter_table)
        filter_table.add_row()


        button = SingleButtonWdg(title="Refresh", icon=IconWdg.REFRESH)
        filter_table.add_cell(button)
        filter_table.add_cell("&nbsp;"*5)
        button.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.panel.refresh(bvr.src_el);
            '''
        } )

        # get all of the pipelnes for this search type
        pipeline_code = my.sobject.get_value("pipeline_code", no_exception=True)
        processes = []
        if pipeline_code:
            pipeline = Pipeline.get_by_code(pipeline_code)
            if pipeline:
                process_names = pipeline.get_process_names()
                processes.extend(process_names)

        processes.insert(0, "all")



        filter_table.add_cell("Process: ")
        select = SelectWdg("process")
        select.add_style("width: 200px")
        if process != 'all':
            select.set_value(process)

        select.set_option("values", processes)

        filter_table.add_cell(select)



        filter_table.add_cell("&nbsp;"*10)

        filter_table.add_cell("Versions: ")
        select = SelectWdg("versions")
        select.add_style("width: 200px")
        select.set_option("values", "latest|current|today|last 10|all")
        if versions:
            select.set_value(versions)
        filter_table.add_cell(select)


        asset_dir = Environment.get_asset_dir()

        select = IconButtonWdg( tip="Toggle Selection", icon=IconWdg.SELECT, show_arrow=False )
        div.add(select)
        select.add_style("float: right")
        select.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            var top_class = 'spt_sobject_dir_list_top'
            var toggle_state = bvr.src_el.getAttribute('toggle');
            if (toggle_state && toggle_state=='true')
                bvr.src_el.setAttribute('toggle','false');
            else
                bvr.src_el.setAttribute('toggle','true');

            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            
            toggle_state = bvr.src_el.getAttribute('toggle');
            if (toggle_state == 'true')
                spt.selection.select_all_items();
            else
                spt.selection.unselect_all_items();

            '''
            } )



        show = IconButtonWdg( tip="Switch View", icon=IconWdg.VIEW, show_arrow=False )
        div.add(show)
        show.add_style("float: right")
        show.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            var top_class = 'spt_sobject_dir_list_top'
            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            var els = top.getElements(".spt_file_dir_item");
            for (var i = 0; i < els.length; i++) {
                var el = els[i];
                if (el.getStyle("display") == "none") {
                    els[i].setStyle("display", "");
                }
                else {
                    els[i].setStyle("display", "none");
                }
            }
            var els = top.getElements(".spt_file_item");
            for (var i = 0; i < els.length; i++) {
                var el = els[i];
                if (el.getStyle("padding-left") == "6px") {
                    var padding = el.getAttribute("spt_padding_left");
                    el.setStyle("padding-left", padding);
                }
                else {
                    el.setStyle("padding-left", "6px");
                }

            }


            '''
        } )






        gear = IconButtonWdg( tip="Download", icon=IconWdg.DOWNLOAD, show_arrow=False )
        div.add(gear)
        gear.add_style("float: right")
        gear.add_behavior( {
            'type': 'click_up',
            'cbjs_action': '''
            spt.app_busy.show('Select a folder to download to...','');
            var top_class = 'spt_sobject_dir_list_top';
            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            var items = spt.selection.get_selected();
            
       
            setTimeout( function() {
                var applet = spt.Applet.get();
                var select_dir =true;
                var dir = applet.open_file_browser('', select_dir);
                if (dir.length == 0)
                    dir = applet.get_current_dir();
                else 
                    dir = dir[0];

                if (!dir) {
                    spt.alert("No folder selected to copy to.");
                    spt.app_busy.hide();
                    return;
                }
                if (items.length == 0){
                    spt.alert("Please select at least one file to download.");
                    spt.app_busy.hide();
                    return;
                }
                

                var asset_dir = '%s';
                for (var i = 0; i < items.length; i++) {
                    var path = items[i].getAttribute("spt_path");
                    var env = spt.Environment.get();
                    var server_url = env.get_server_url();
                    var url = server_url + "/assets/" + path.replace(asset_dir, "");
                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    spt.app_busy.show("Downloading file", filename);
                    applet.download_file(url, dir + "/" + filename);
                }
                spt.app_busy.hide();
                if (dir)
                    spt.notify.show_message("Download to '" + dir + "' completed.")
            }, 100);

            ''' % asset_dir
 
        } )

        return div
Exemple #29
0
    def add_top_behaviors(my, top):

        # convert this to a repo directory
        asset_dir = Environment.get_asset_dir()

        # FIXME: not sure how general this
        #webdirname = "/assets/%s" % dirname.replace(asset_dir, "")

        web = WebContainer.get_web()
        browser = web.get_browser()


        if browser == 'Qt':
            top.add_relay_behavior( {
            'type': 'dblclick',
            'bvr_match_class': 'spt_dir_list_item',
            'cbjs_action': '''
            var path = bvr.src_el.getAttribute("spt_path");
            var asset_dir = '%s';
            var url = "/assets/" + path.replace(asset_dir, "");
            //window.open(url);

            var url_parts = url.split("/");
            var file = url_parts.pop();
            file = encodeURIComponent(file);
            url_parts.push(file);
            url = url_parts.join("/");

            var class_name = 'tactic.ui.widget.EmbedWdg';
            var kwargs = {
                src: url
            }

            var parts = path.split("/");
            var filename = parts[parts.length-1];
            spt.tab.set_main_body_tab()
            spt.tab.add_new(filename, filename, class_name, kwargs);
            ''' % asset_dir
            } )
        else:
            top.add_relay_behavior( {
            'type': 'dblclick',
            'bvr_match_class': 'spt_dir_list_item',
            'cbjs_action': '''
            var path = bvr.src_el.getAttribute("spt_path");
            
            if (path.indexOf('####') != -1) {
                spt.info('Cannot open the file sequence');
            } 
            else {
            var asset_dir = '%s';
            var url = "/assets/" + path.replace(asset_dir, "");

            var url_parts = url.split("/");
            var filename = url_parts.pop();
            filename = encodeURIComponent(filename);
            url_parts.push(filename);
            url = url_parts.join("/");

            window.open(url);
            }
            ''' % asset_dir
            } )

        # add a top menu
        menu = Menu(width=180)
        menu_item = MenuItem(type='title', label='Actions')
        menu.add(menu_item)

        menu_item = MenuItem(type='action', label='Download to Folder')
        menu.add(menu_item)
        menu_item.add_behavior( {
        'type': 'click_up',
        'cbjs_action': '''
            var activator = spt.smenu.get_activator(bvr);
            var applet = spt.Applet.get();
            var select_dir = true;
            var dir = applet.open_file_browser('', select_dir);
            if (!dir) {
                dir = applet.get_current_dir();
            }
            if (!dir) {
                spt.alert("No folder selected to copy to");
                return;
            }
            
            var path = activator.getAttribute("spt_path");

            var asset_dir = '%s';
            var env = spt.Environment.get();
            var server_url = env.get_server_url();
            var url = server_url + "/assets/" + path.replace(asset_dir, "");
            var parts = path.split("/");
            var filename = parts[parts.length-1];
            spt.app_busy.show("Downloading file", filename);
            applet.download_file(url, dir + "/" + filename);
            spt.app_busy.hide();
            if (dir)
                spt.notify.show_message("Download to '" + dir + "' completed.")
            ''' % asset_dir
        } )
        #menu_item = MenuItem(type='action', label='Check-out To Sandbox')
        #menu.add(menu_item)
        #menu_item.add_behavior( {
        #'type': 'click_up',
        #'cbjs_action': '''spt.alert('Not implemented yet.')'''
        #} )
        menu_item = MenuItem(type='action', label='Copy to Clipboard')
        menu.add(menu_item)
        menu_item.add_behavior( {
        'type': 'click_up',
        'cbjs_action': '''
        var activator = spt.smenu.get_activator(bvr);
        var path = activator.getAttribute("spt_path");

        var search_key = activator.getAttribute("spt_file_search_key");

        var server = TacticServerStub.get();
        var class_name = 'tactic.command.clipboard_cmd.ClipboardCopyCmd';
        var search_keys = [search_key];
        var kwargs = {
            search_keys: search_keys
        }
        try {
            spt.app_busy.show("Copy to Clipboard ...");
            server.execute_cmd(class_name, kwargs);
            spt.app_busy.hide();
            }
        catch(e) {
            spt.alert(spt.exception.handler(e));
        }
        '''
        } )


        menu_item = MenuItem(type='action', label='View Metadata')
        menu.add(menu_item)
        menu_item.add_behavior( {
        'type': 'click_up',
        'cbjs_action': '''
        var activator = spt.smenu.get_activator(bvr);
        var path = activator.getAttribute("spt_path");

        var search_key = activator.getAttribute("spt_file_search_key");

        var server = TacticServerStub.get();
        var class_name = 'tactic.ui.checkin.SnapshotMetadataWdg';
        var kwargs = {
            search_key: search_key
        }
        spt.panel.load_popup("Metadata", class_name, kwargs);
        '''
        } )



        menus_in = {
            'FILE_MENU_CTX': menu,
        }
        SmartMenu.attach_smart_context_menu( top, menus_in, False )


        my.add_selection(top)
 
        super(SnapshotDirListWdg, my).add_top_behaviors(top)
Exemple #30
0
    def add_top_behaviors(self, top):

        # convert this to a repo directory
        asset_dir = Environment.get_asset_dir()
        web_dir = Environment.get_web_dir()

        web = WebContainer.get_web()
        browser = web.get_browser()
        use_applet = web.use_applet()

        if browser == 'Qt':
            top.add_relay_behavior({
                'type':
                'dblclick',
                'bvr_match_class':
                'spt_dir_list_item',
                'cbjs_action':
                '''
            var path = bvr.src_el.getAttribute("spt_path");
            var asset_dir = '%s';
            var web_dir = '%s';
            var relative_dir = path.replace(asset_dir, "");
            var url = web_dir + "/" + relative_dir;

            var url_parts = url.split("/");
            var file = url_parts.pop();
            file = encodeURIComponent(file);
            url_parts.push(file);
            url = url_parts.join("/");

            var class_name = 'tactic.ui.widget.EmbedWdg';
            var kwargs = {
                src: url
            }

            var parts = path.split("/");
            var filename = parts[parts.length-1];
            spt.tab.set_main_body_tab()
            spt.tab.add_new(filename, filename, class_name, kwargs);
            ''' % (asset_dir, web_dir)
            })
        else:
            top.add_relay_behavior({
                'type':
                'dblclick',
                'bvr_match_class':
                'spt_dir_list_item',
                'cbjs_action':
                '''
            var path = bvr.src_el.getAttribute("spt_path");
            if (path.indexOf('####') != -1) {
                spt.info('Cannot open the file sequence');
            } else {
                var asset_dir = '%s';
                var web_dir = '%s';
                var relative_dir = path.replace(asset_dir, "");
                var url = web_dir + "/" + relative_dir;

                // Encode the filename
                var url_parts = url.split("/");
                var filename = url_parts.pop();
                filename = encodeURIComponent(filename);
                url_parts.push(filename);
                url = url_parts.join("/");

                window.open(url);
            }
            ''' % (asset_dir, web_dir)
            })

        if use_applet:
            # add a top menu
            menu = Menu(width=180)
            menu_item = MenuItem(type='title', label='Actions')
            menu.add(menu_item)

            menu_item = MenuItem(type='action', label='Download to Folder')
            menu.add(menu_item)
            menu_item.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
                var activator = spt.smenu.get_activator(bvr);
                var applet = spt.Applet.get();
                var select_dir = true;
                var dir = applet.open_file_browser('', select_dir);
                if (!dir) {
                    dir = applet.get_current_dir();
                }
                if (!dir) {
                    spt.alert("No folder selected to copy to");
                    return;
                }
                
                var path = activator.getAttribute("spt_path");

                var asset_dir = '%s';
                var env = spt.Environment.get();
                var server_url = env.get_server_url();
                var url = server_url + "/assets/" + path.replace(asset_dir, "");
                var parts = path.split("/");
                var filename = parts[parts.length-1];
                spt.app_busy.show("Downloading file", filename);
                applet.download_file(url, dir + "/" + filename);
                spt.app_busy.hide();
                if (dir)
                    spt.notify.show_message("Download to '" + dir + "' completed.")
                ''' % asset_dir
            })
            #menu_item = MenuItem(type='action', label='Check-out To Sandbox')
            #menu.add(menu_item)
            #menu_item.add_behavior( {
            #'type': 'click_up',
            #'cbjs_action': '''spt.alert('Not implemented yet.')'''
            #} )
            menu_item = MenuItem(type='action', label='Copy to Clipboard')
            menu.add(menu_item)
            menu_item.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
            var activator = spt.smenu.get_activator(bvr);
            var path = activator.getAttribute("spt_path");

            var search_key = activator.getAttribute("spt_file_search_key");

            var server = TacticServerStub.get();
            var class_name = 'tactic.command.clipboard_cmd.ClipboardCopyCmd';
            var search_keys = [search_key];
            var kwargs = {
                search_keys: search_keys
            }
            try {
                spt.app_busy.show("Copy to Clipboard ...");
                server.execute_cmd(class_name, kwargs);
                spt.app_busy.hide();
                }
            catch(e) {
                spt.alert(spt.exception.handler(e));
            }
            '''
            })

            menu_item = MenuItem(type='action', label='View Metadata')
            menu.add(menu_item)
            menu_item.add_behavior({
                'type':
                'click_up',
                'cbjs_action':
                '''
            var activator = spt.smenu.get_activator(bvr);
            var path = activator.getAttribute("spt_path");

            var search_key = activator.getAttribute("spt_file_search_key");

            var server = TacticServerStub.get();
            var class_name = 'tactic.ui.checkin.SnapshotMetadataWdg';
            var kwargs = {
                search_key: search_key
            }
            spt.panel.load_popup("Metadata", class_name, kwargs);
            '''
            })

            menus_in = {
                'FILE_MENU_CTX': menu,
            }
            SmartMenu.attach_smart_context_menu(top, menus_in, False)

        self.add_selection(top)

        super(SnapshotDirListWdg, self).add_top_behaviors(top)
Exemple #31
0
    def get_display(my):

        alias = my.kwargs.get("alias")

        my.rel_path = my.kwargs.get("rel_path")
        if not my.rel_path:
            from tactic_client_lib import TacticServerStub
            server = TacticServerStub.get(protocol='local')
            my.rel_path = server.get_doc_link(alias)

        if not my.rel_path or my.rel_path == 'none_found':
            #raise TacticException("Help alias [%s] does not exist" % alias)
            layout = DivWdg()
            layout.add(HelpCreateWdg(alias=alias))
            layout.add(HelpDocFilterWdg(alias='main'))
            return layout 

        # special condition for plugins path
        if my.rel_path.startswith("/plugins/"):
            plugin_dir = Environment.get_plugin_dir()
            rel_path = my.rel_path.replace("/plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/builtin_plugins/"):
            plugin_dir = Environment.get_builtin_plugin_dir()
            rel_path = my.rel_path.replace("/builtin_plugins/", "")
            path = "%s/%s" % (plugin_dir,rel_path)
        elif my.rel_path.startswith("/assets/"):
            asset_dir = Environment.get_asset_dir()
            rel_path = my.rel_path.replace("/assets/", "")
            path = "%s/%s" % (asset_dir,rel_path)
        else:

            # see if there is an override
            doc_dir = os.environ.get("TACTIC_DOC_DIR") 
            if not doc_dir:
                doc_dir = Config.get_value("install", "doc_dir")
            if not doc_dir:
                install_dir = Environment.get_install_dir()
                doc_dir = "%s/doc" % install_dir

            path = "%s/%s" % (doc_dir, my.rel_path)

        html = []
        try:
            paths = path.split('#')
            anchor = ''
            if len(paths) > 1:
                anchor = paths[-1]
                path = paths[0]
                read = False
            else:
                read = True

            
            f = open(path, 'r')
            count = 0
            idx = 0 
            anchor_str = '<a id="%s"></a>'%anchor
            div_str = '<div class="titlepage">'
            strip_count = 0
            for line in f:
                if anchor and not read:
                    tmp_line = line.decode('utf-8','ignore')
                    div_idx = tmp_line.find(div_str)
                    idx = tmp_line.find(anchor_str)
                    if idx != -1:
                        # use the div above the anchor
                        line = line[div_idx:-1]
                        
                        # in case it doesn't get it right on
                        while strip_count < 30 and not line.startswith('<div class="titlepage">'):
                            line = line[1:-1]
                            strip_count +=  1

                        read = True
                
                if read:
                    line = my.filter_line(line, count)
                    html.append(line)
                    count += 1
            f.close()
        except Exception, e:
            print "Error processing: ", e
            html.append("Error processing document: %s<br/><br/>" % str(e))
Exemple #32
0
    def handle_file_mode(self, base_dir, transaction_code, paths, log, transaction_xml, ticket):
        # drop the transaction into a folder

        timestamp = log.get_value("timestamp")
        timestamp = parser.parse(timestamp)
        timestamp = timestamp.strftime("%Y%m%d_%H%M%S")

        asset_dir = Environment.get_asset_dir()

        # create the transactions dir if it does not exist
        if not os.path.exists("%s/transactions" % base_dir):
            os.makedirs("%s/transactions" % base_dir)

        base_dir = "%s/transactions/%s" % (base_dir, transaction_code)

        is_encrypted = True
        if is_encrypted == True:
            # put the transaction in a temp folder
            tmp_dir = Environment.get_tmp_dir(include_ticket=True)
            tmp_dir = "%s/%s-%s" % (tmp_dir, transaction_code, timestamp)

        else:
            tmp_dir = "%s/%s" % (base_dir, timestamp)

        if not os.path.exists(tmp_dir):
            os.makedirs(tmp_dir)


        from pyasm.common import EncryptUtil
        encrypt = EncryptUtil(ticket)

        # create a simple manifest file
        f = open("%s/manifest.xml" % tmp_dir, 'wb')
        f.write('''<manifest code='transaction_log' version='1'>\n''')
        f.write('''  <sobject search_type="sthpw/transaction_log"/>\n''')
        f.write('''</manifest>\n''')
        f.close()


        tpath = "%s/sthpw_transaction_log.spt" % tmp_dir

        from pyasm.search import TableDataDumper
        dumper = TableDataDumper()
        dumper.set_delimiter("#-- Start Entry --#", "#-- End Entry --#")
        dumper.set_include_id(False)
        dumper.set_sobjects([log])
        dumper.dump_tactic_inserts(tpath, mode='sobject')


        tpath = "%s/_transaction.xml" % tmp_dir
        #f = open(tpath, 'wb')
        f = codecs.getwriter('utf8')(open(tpath, 'wb'))
        f.write(transaction_xml.to_string())
        f.close()


        # copy the checked in files
        for path in paths:
            rel_path = path.replace(asset_dir, "")
            rel_path = rel_path.lstrip("/")
            to_path = "%s/%s" % (tmp_dir, rel_path)
            to_dir = os.path.dirname(to_path)
            if not os.path.exists(to_dir):
                os.makedirs(to_dir)

            shutil.copy(path, to_dir)


        # zip up and encrypt the transaction
        if is_encrypted:
            zip_path = "%s.zip" % (tmp_dir)
            from pyasm.common import ZipUtil
            zip = ZipUtil()
            zip.zip_dir("%s" % (tmp_dir), zip_path)

            encrypt.encrypt_file(zip_path)


            shutil.move("%s.enc" % zip_path, "%s-%s.zip.enc" % (base_dir, timestamp))
            rmdir = os.path.dirname(tmp_dir)
            shutil.rmtree(rmdir)
            #os.unlink("%s.zip" % tmp_dir)


        job = self.kwargs.get("job")
        job.set_value("error_log", "")
        job.commit()


        return
Exemple #33
0
    def get_display(my):

        my.sobject = my.kwargs.get("sobject")
        search_key = my.sobject.get_search_key()

        top = DivWdg()
        top.add_class("spt_checkin_publish")
        top.add_style("padding: 10px")

        margin_top = '60px'
        top.add_style("margin-top", margin_top)
        top.add_style("position: relative")

        current_changelist = WidgetSettings.get_value_by_key(
            "current_changelist")
        current_branch = WidgetSettings.get_value_by_key("current_branch")
        current_workspace = WidgetSettings.get_value_by_key(
            "current_workspace")

        top.add("Branch: %s<br/>" % current_branch)
        top.add("Changelist: %s<br/>" % current_changelist)
        top.add("Workspace: %s<br/>" % current_workspace)
        top.add("<br/>")

        checked_out_div = DivWdg()
        checkbox = CheckboxWdg("editable")
        top.add(checked_out_div)
        checkbox.add_class("spt_checkin_editable")
        checked_out_div.add(checkbox)
        checked_out_div.add("Leave files editable")

        top.add("<br/>")

        top.add("Publish Description<br/>")
        text = TextAreaWdg("description")
        # this needs to be set or it will stick out to the right
        text.add_style("width: 220px")
        text.add_class("spt_checkin_description")
        top.add(text)

        # add as a note
        note_div = DivWdg()
        top.add(note_div)
        note_div.add_class("spt_add_note")
        checkbox = CheckboxWdg("add_note")

        web = WebContainer.get_web()
        browser = web.get_browser()
        if browser in ['Qt']:
            checkbox.add_style("margin-top: -4px")
            checkbox.add_style("margin-right: 3px")
            note_div.add_style("margin-top: 3px")

        checkbox.add_class("spt_checkin_add_note")
        note_div.add(checkbox)
        note_div.add("Also add as note")

        top.add("<br/><br/>")

        button = ActionButtonWdg(title="Check-in",
                                 icon=IconWdg.PUBLISH,
                                 size='medium')
        top.add(button)

        my.repo_type = 'perforce'
        if my.repo_type == 'perforce':

            # the depot is set per project (unless overridden)
            project = my.sobject.get_project()
            depot = project.get_value("location", no_exception=True)
            if not depot:
                depot = project.get_code()

            asset_dir = Environment.get_asset_dir()
            sandbox_dir = Environment.get_sandbox_dir()

            changelist = WidgetSettings.get_value_by_key("current_changelist")
            button.add_behavior({
                'type':
                'click_up',
                'depot':
                depot,
                'changelist':
                changelist,
                'sandbox_dir':
                sandbox_dir,
                'search_key':
                search_key,
                'cbjs_action':
                '''

            var paths = spt.checkin.get_selected_paths();
            spt.app_busy.show("Checking in "+paths.length+" file/s into Perforce");
            var top = bvr.src_el.getParent(".spt_checkin_top");
            var description = top.getElement(".spt_checkin_description").value;
            var add_note = top.getElement(".spt_checkin_add_note").value;
            var editable = top.getElement(".spt_checkin_editable").value;

            if (editable == 'on') {
                editable = true;
            }
            else {
                editable = false;
            }

            var process = top.getElement(".spt_checkin_process").value;

            // check into TACTIC
            var server = TacticServerStub.get();

            var revisions = [];
            server.start({description: "File Check-in"});

            try {

            var top = bvr.src_el.getParent(".spt_checkin_top");
            var el = top.getElement(".spt_mode");
            var mode = el.value;

            // check-in the changelist
            var changelist = 'default';
            if (mode == 'changelist') {
                var scm_info = spt.scm.run("commit_changelist", [changelist, description]);

                for ( var i = 1; i < scm_info.length-1; i++) {
                    // the first item is the changelist number
                    //console.log(scm_info[i]);

                    var action = scm_info[i];
                    revision = action.rev;
                    revisions.push(revision);

                    // Do an inplace check-in into TACTIC
                    var path = action.depotFile;

                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    var context = process + "/" + filename;

                    var snapshot = server.simple_checkin(bvr.search_key, context, path, {description: description, mode: "perforce", version: revision} );
                }

            }
            else {

                // check in all of the files
                for ( var i = 0; i < paths.length; i++) {
                    var path = paths[i];
                    var scm_info = spt.scm.run("commit_file", [path, description, editable]);
                    // the first item is the changelist number
                    var action = scm_info[1];
                    revision = action.rev;
                    revisions.push(revision);

                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    var context = process + "/" + filename;

                    //path = path.replace(bvr.sandbox_dir, "//"+bvr.depot);
                    // NOTE: this assumes project == depot
                    path = path.replace(bvr.sandbox_dir, "//");

                    // Do an inplace check-in into TACTIC
                    var snapshot = server.simple_checkin(bvr.search_key, context, path, {description: description, mode: "perforce", version: revision} );
                }
            }


            if (add_note == 'on') {
                var note = [];
                note.push('CHECK-IN');
                for (var i = 0; i < paths.length; i++) { 
                    var parts = paths[i].split("/");
                    var filename = parts[parts.length-1];
                    note.push(filename+' (v'+revisions[i]+')');
                }
                note.push(': ');
                note.push(description);

                note = note.join(" ");
                server.create_note(bvr.search_key, note, {process: process});
            }
            server.finish({description: "File Check-in ["+paths.length+" file/s]"});
            spt.panel.refresh(top);

            }
            catch(e) {
              spt.error("Error detected: " + e.msg)
              //console.log(e);
              server.abort();
            }

            spt.app_busy.hide();
            '''
            })
        else:
            button.add_behavior(behavior)

        button.add_style("margin-right: auto")
        button.add_style("margin-left: auto")
        button.add_style("margin-top: 20px")
        button.add_style("margin-bottom: 20px")

        top.add("<br clear='all'/>")
        top.add("<hr/>")

        hidden = HiddenWdg("checkin_type")
        top.add(hidden)
        hidden.add_class("spt_checkin_type")

        grey_out_div = DivWdg()
        top.add(grey_out_div)
        grey_out_div.add_class("spt_publish_disable")
        grey_out_div.add_style("position: absolute")
        grey_out_div.add_style("left: 0px")
        grey_out_div.add_style("top: 10px")
        grey_out_div.add_style("opacity: 0.6")
        grey_out_div.add_color("background", "background")
        grey_out_div.add_style("height: 100%")
        grey_out_div.add_style("width: 100%")
        #grey_out_div.add_border()

        return top
Exemple #34
0
    def get_base_dir(my, protocol=None, alias="default"):
        '''get the default base directory for this sobject'''
        dirs = []
        base_dir = ''

        client_os = Environment.get_env_object().get_client_os()
        if client_os == 'nt':
            prefix = "win32"
        else:
            prefix = "linux"

        if not alias:
            alias = "default"


        if not protocol:
            protocol = my.protocol

        if protocol == "http":

            repo_handler = my.sobject.get_repo_handler(my.snapshot)
            if repo_handler.is_tactic_repo():
                base_dir = Environment.get_web_dir(alias=alias)
            else:
                alias_dict = Config.get_dict_value("perforce", "web_base_dir")
                base_dir = alias_dict.get(alias)

            if not base_dir:
                asset_alias_dict = Environment.get_asset_dirs()
                base_dir = asset_alias_dict.get(alias)
                base_dir = "/%s" % os.path.basename(base_dir)

            if not base_dir:
                base_dir = alias_dict.get("default")

            if not base_dir:
                base_dir = "/assets"


        elif protocol == "remote":
            # NOTE: currently needs web to get the full http base url
            base_dir = Environment.get_env_object().get_base_url().to_string()

       
            sub_dir = my.get_base_dir(protocol='http', alias=alias)
            base_dir = "%s%s" % (base_dir, sub_dir[0])

            
        elif protocol == "file":
            base_dir = Environment.get_asset_dir(alias=alias)

        elif protocol == "env":
            base_dir = "$TACTIC_ASSET_DIR"


        # This is the central repository as seen from the client
        elif protocol in ["client_lib", "client_repo"]:
            base_dir = my.get_custom_setting('%s_client_repo_dir' % prefix)
            if not base_dir:
                alias_dict = Config.get_dict_value("checkin", "%s_client_repo_dir" % prefix)
                base_dir = alias_dict.get(alias)

            if not base_dir:
                base_dir = Environment.get_asset_dir()


        # DEPRECATED: The local repo.  This one has logic to add "repo" dir
        # at the end.  Use local_repo which does not have this logic.
        # keeping this around for backward compatibility
        elif protocol == "local":
            remote_repo = my.get_remote_repo()
            if remote_repo:
                #base_dir = remote_repo.get_value("repo_base_dir")
                base_dir = Environment.get_asset_dir()
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_base_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_base_dir")
                base_dir += "/repo"

        # The local repo
        elif protocol == "local_repo":
            remote_repo = my.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("repo_base_dir")
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_repo_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_repo_dir")
                if not base_dir:
                    base_dir = Environment.get_asset_dir()


        elif protocol == "sandbox":

            remote_repo = my.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("sandbox_base_dir")
            else:
                if not base_dir:
                    base_dict = Config.get_dict_value("checkin","%s_sandbox_dir" % prefix)
                    base_dir = base_dict.get(alias)


        elif protocol == "relative":
            return []

        assert base_dir
        return [base_dir]
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,

                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
            }
            ,
            '/context': {'tools.staticdir.on': True,
                         'tools.staticdir.dir': context_path,
                         # Need to do this because on windows servers, jar files
                         # are served as text/html
                         'tools.staticdir.content_types': {
                             'jar': 'application/java-archive'
                         }
                        },
            '/assets':  {'tools.staticdir.on': True,
                         'tools.staticdir.dir': Environment.get_asset_dir()
                        },
            '/doc':     {'tools.staticdir.on': True,
                         'tools.staticdir.dir': doc_dir,
                         'tools.staticdir.index': "index.html"
                        },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/tactic/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/tactic/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        }
 

        }

      

        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount( cherrypy.root, config=config)



        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()


        # find out if one of the projects is the root
        root_initialized = False
        """
        for project in projects:
            project_code = project.get_code()
            if False:
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True
                break
        """

        if not root_initialized:
            project_code = Project.get_default_project()
            if project_code and project_code !='default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True


        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()


        for project in projects:
            project_code = project.get_code()
            my.register_site(project_code, config)
        my.register_site("default", config)

        return config
Exemple #36
0
    def get_base_dir(my, protocol=None):
        '''get the default base directory for this sobject'''
        dirs = []
        base_dir = ''
        
        if not protocol:
            protocol = my.protocol

        if protocol == "http":

            repo_handler = my.sobject.get_repo_handler(my.snapshot)
            if repo_handler.is_tactic_repo():
                base_dir = Config.get_value("checkin", "web_base_dir")
            else:
                base_dir = Config.get_value("perforce", "web_base_dir")


        elif protocol == "remote":
            # TODO: currently needs web to do this
            base_dir = Environment.get_env_object().get_base_url().to_string()

            repo_handler = my.sobject.get_repo_handler(my.snapshot)
            if repo_handler.is_tactic_repo():
                sub_dir = Config.get_value("checkin", "web_base_dir")
            else:
                sub_dir = Config.get_value("perforce", "web_base_dir")

            base_dir = "%s%s" % (base_dir, sub_dir)

        elif protocol == "file":
            #base_dir = Config.get_value("checkin", "asset_base_dir")
            base_dir = Environment.get_asset_dir(my._file_object)

        elif protocol == "env":
            base_dir = "$TACTIC_ASSET_DIR"

        # This is the central repository as seen from the client
        elif protocol in ["client_lib", "client_repo"]:
            
            if Environment.get_env_object().get_client_os() =='nt':
                base_dir = my.get_custom_setting('win32_client_repo_dir')
                if not base_dir:
                    if my._file_object:
                        base_dir_alias = my._file_object.get_value('base_dir_alias')
                        if base_dir_alias:
                            alias_dict = Config.get_value("checkin", "base_dir_alias", sub_key=base_dir_alias)
                            base_dir = alias_dict.get("win32_client_repo_dir")
                    if not base_dir:
                        base_dir = Config.get_value("checkin", "win32_client_repo_dir", no_exception=True)
            else:
                base_dir = my.get_custom_setting('linux_client_repo_dir')
                if not base_dir:
                    if my._file_object:
                        base_dir_alias = my._file_object.get_value('base_dir_alias')
                        if base_dir_alias:
                            alias_dict = Config.get_value("checkin", "base_dir_alias", sub_key=base_dir_alias)
                            base_dir = alias_dict.get("linux_client_repo_dir")
                        if not base_dir:
                            base_dir = Config.get_value("checkin", "linux_client_repo_dir", no_exception=True)
            if not base_dir:
                #base_dir = Config.get_value("checkin", "asset_base_dir")
                base_dir = Environment.get_asset_dir()

        # DEPRECATED: The local repo.  This one has logic to add "repo" dir
        # at the end.  Use local_repo which does not have this logic.
        # keeping this around for backward compatibility
        elif protocol == "local":
            remote_repo = my.get_remote_repo()
            if remote_repo:
                #base_dir = remote_repo.get_value("repo_base_dir")
                base_dir = Environment.get_asset_dir()
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_base_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_base_dir")
                base_dir += "/repo"

        # The local repo
        elif protocol == "local_repo":
            remote_repo = my.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("repo_base_dir")
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_repo_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_repo_dir")
                if not base_dir:
                    base_dir = Environment.get_asset_dir()


        elif protocol == "sandbox":
            remote_repo = my.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("sandbox_base_dir")
            else:

                base_dir = PrefSetting.get_value_by_key("sandbox_base_dir")
                if not base_dir:

                    if Environment.get_env_object().get_client_os() =='nt':
                        base_dir = Config.get_value("checkin","win32_sandbox_dir")
                        if base_dir == "":
                            base_dir = Config.get_value("checkin","win32_local_base_dir")
                            base_dir += "/sandbox"
                    else:
                        base_dir = Config.get_value("checkin","linux_sandbox_dir")
                        if base_dir == "":
                            base_dir = Config.get_value("checkin","linux_local_base_dir")
                            base_dir += "/sandbox"

        elif protocol == "relative":
            return []

        return [base_dir]
Exemple #37
0
    def execute(my):

        # DISABLING: this used to be needed for Repo Browser layout, but
        # is no longer needed
        return

        from pyasm.biz import Snapshot, Naming

        input = my.get_input()
        search_key = input.get("search_key")
        search_type = input.get('search_type')
        sobject = my.get_caller()
        assert search_type

        search_type_obj = SearchType.get(search_type)

        # FIXME: this should be in SearchType
        base_dir = Environment.get_asset_dir()

        root_dir = search_type_obj.get_value("root_dir", no_exception=True)
        if not root_dir:
            base_type = search_type_obj.get_base_key()
            parts = base_type.split("/")
            relative_dir = parts[1]


        # FIXME: need to use naming here
        file_type = 'main'
        snapshot_type = "file"
        process = "publish"

        virtual_snapshot = Snapshot.create_new()
        virtual_snapshot_xml = '<snapshot><file type=\'%s\'/></snapshot>' %(file_type)
        virtual_snapshot.set_value("snapshot", virtual_snapshot_xml)
        virtual_snapshot.set_value("snapshot_type", snapshot_type)

        # NOTE: keep these empty to produce a folder without process
        # or context ...
        # Another approach would be to find all the possible processes
        # and create folders for them

        # since it is a a file name based context coming in, use process
        #virtual_snapshot.set_value("process", process)
        #virtual_snapshot.set_value("context", process)

        # ???? Which is the correct one?
        virtual_snapshot.set_sobject(sobject)
        virtual_snapshot.set_parent(sobject)
        
        #naming = Naming.get(sobject, virtual_snapshot)
        #print "naming: ", naming.get_data()

        # Need to have a fake file because preallocated path also looks at
        # the file
        file_name = 'test.jpg'
        mkdirs = False
        ext = 'jpg'

        path = virtual_snapshot.get_preallocated_path(file_type, file_name, mkdirs, ext=ext, parent=sobject)
        dirname = os.path.dirname(path)

        if isinstance(path, unicode):
            path = path.encode('utf-8')
        else:
            path = unicode(path, errors='ignore').encode('utf-8')

        #dirname = "%s/%s/%s/" % (base_dir, project_code, root_dir)

        base_dir = Environment.get_asset_dir()
        relative_dir = dirname.replace(base_dir, "")
        relative_dir = relative_dir.strip("/")

        # create a file object
        file_obj = SearchType.create("sthpw/file")
        file_obj.set_sobject_value(sobject)
        file_obj.set_value("file_name", "")
        file_obj.set_value("relative_dir", relative_dir)
        file_obj.set_value("type", "main")
        file_obj.set_value("base_type", "sobject_directory")
        file_obj.commit(triggers=False)

        from pyasm.search import FileUndo
        if not os.path.exists(dirname):
            FileUndo.mkdir(dirname)
Exemple #38
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            'global': {
                'server.socket_host': 'localhost',
                'server.socket_port': 80,
                'server.log_to_screen': False,
                'server.environment': 'production',
                'server.show_tracebacks': True,
                'server.log_request_headers': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,
                'log_debug_info_filter.on': False,

                #'encoding_filter.on': True,
                #'decoding_filter.on': True,
            },
            '/context': {
                'static_filter.on': True,
                'static_filter.dir': context_path
            },
            '/assets': {
                'static_filter.on': True,
                'static_filter.dir': Environment.get_asset_dir()
            },
            '/doc': {
                'static_filter.on': True,
                'static_filter.dir': doc_dir
            },
            '/doc/': {
                'static_filter.on': True,
                'static_filter.file': "%s/index.html" % doc_dir
            },
        }

        # set up the root directory
        cherrypy.root = Root()
        from tactic_sites.default.context.TitlePage import TitlePage
        cherrypy.root.tactic = TitlePage()
        cherrypy.root.projects = TitlePage()

        sites = []

        # add the tactic projects
        install_dir = Environment.get_install_dir().replace("\\", "/")
        site_dir = "%s/src/tactic_sites" % install_dir
        for context_dir in os.listdir(site_dir):
            if context_dir.startswith(".svn"):
                continue

            full_path = "%s/%s" % (site_dir, context_dir)

            if os.path.isdir(full_path):
                sites.append(context_dir)

        # add all the custom projects
        site_dir = Environment.get_site_dir().replace("\\", "/")
        site_dir = "%s/sites" % site_dir
        for context_dir in os.listdir(site_dir):
            if context_dir.startswith(".svn"):
                continue

            full_path = "%s/%s" % (site_dir, context_dir)

            if os.path.isdir(full_path):
                sites.append(context_dir)

        for site in sites:
            my.register_site(site, config)

            # set up the images directory
            for subdir in ['images', 'doc']:
                config["/tactic/%s/%s/" % (site,subdir)] = {
                    'static_filter.on': True,
                    'static_filter.dir': '%s/sites/%s/context/%s/' % \
                        (site_dir,site, subdir)
                }

        return config
Exemple #39
0
            print
            sys.exit(2)

        my.update_tactic_configs()

        # check modules
        try:
            import tacticenv
        except ImportError:
            print 'Error: Failed to "import tacticenv"'
            return
        my.check_modules(install_db)

        # create the asset_dir
        from pyasm.common import Environment
        asset_dir = Environment.get_asset_dir()
        if not os.path.exists(asset_dir):
            os.makedirs(asset_dir)



        # check that the main directories exists
        install_dir = os.getenv("TACTIC_INSTALL_DIR")
        data_dir = os.getenv("TACTIC_DATA_DIR")
        if not os.path.exists(install_dir):
            print "Environment variable TACTIC_INSTALL_DIR '%s' does not exist" % install_dir
            return
        if not os.path.exists(data_dir):
            print "Environment variable TACTIC_DATA_DIR '%s' does not exist" % data_dir
            return
Exemple #40
0
    def execute(self):

        mode = self.kwargs.get("mode")
        # modes are either naming based or file object based
        #mode = "naming"
        #mode = "file"
        assert mode in ['naming', 'file']

        search_type = self.kwargs.get("search_type")
        search_keys = self.kwargs.get("search_keys")
        assert search_type or search_keys

        if search_type:
            print "@SOBJECT(%s)" % search_type
            sobjects = Search.eval("@SOBJECT(%s)" % search_type)
        else:
            sobjects = Search.get_by_search_keys(search_keys)

        if not sobjects:
            print "No sobjects to process"
            return
        snapshots = Search.eval("@SOBJECT(sthpw/snapshot)", sobjects)

        # set an arbitrary limit for now
        limit = 1000

        base_dir = Environment.get_asset_dir()

        num_found = 0
        errors = []
        for i, snapshot in enumerate(snapshots):
            if i > limit:
                break
            print "Processing: %s of %s" % (i, len(snapshots))

            file_types = snapshot.get_all_file_types()
            for file_type in file_types:
                files = snapshot.get_files_by_type(file_type)

                # FIXME: not sure why we have this limitation, although it is
                # a pretty rare occurance
                if len(files) > 1:
                    raise Exception(
                        "More than one file with type [%s] in snapshot [%s]" %
                        (file_type, snapshot.get_code()))

                file = files[0]
                file_name = file.get_value("file_name")

                # check-in dir is not subject to changes in asset_dir
                checkin_dir = file.get_value("checkin_dir")
                old_path = "%s/%s" % (checkin_dir, file_name)

                try:

                    if mode == "naming":
                        # preallocated path is used to align a file to the
                        # current naming convention

                        # FIXME:
                        # there is a behavior in naming to add "_web" and
                        # "_icon" on the file name.  In this case, we don't
                        # want that, so ask for main
                        if file_type in ['icon', 'web']:
                            path = snapshot.get_preallocated_path(
                                'main', file_name)
                        else:
                            path = snapshot.get_preallocated_path(
                                file_type, file_name)

                    elif mode == "file":
                        # relative_dir is used to align a file to the current
                        # place pointed to by the "file" object
                        relative_dir = file.get_value("relative_dir")
                        path = "%s/%s/%s" % (base_dir, relative_dir, file_name)
                    else:
                        raise Exception("Invalid mode [%s]" % mode)

                except Exception as e:
                    error = "Snapshot [%s] has an error getting preallocated path: [%s]" % (
                        snapshot.get_code(), e.message)
                    errors.append(error)
                    continue

                if old_path == path:
                    continue

                num_found += 1

                print("snapshot: ", snapshot.get_value("code"))
                print("old: ", old_path)
                print("new: ", path)

                print("-" * 20)

                new_dir = os.path.dirname(path)
                new_filename = os.path.basename(path)
                new_relative_dir = new_dir.replace(base_dir, '')
                new_relative_dir = new_relative_dir.strip("/")

                xml = snapshot.get_xml_value("snapshot")
                node = xml.get_node("snapshot/file[@type='%s']" % file_type)
                Xml.set_attribute(node, "name", new_filename)

                # update all of the file
                file.set_value("file_name", new_filename)
                file.set_value("checkin_dir", new_dir)
                file.set_value("relative_dir", new_relative_dir)
                snapshot.set_value("snapshot", xml.to_string())

                dirname = os.path.dirname(path)
                if not os.path.exists(dirname):
                    FileUndo.mkdir(dirname)

                exists = False
                if os.path.islink(old_path):
                    exists = os.path.lexists(old_path)
                else:
                    exists = os.path.exists(old_path)

                if not exists:
                    print '... old does not exist'
                    continue

                FileUndo.move(old_path, path)
                file.commit()
                snapshot.commit()

                # try to remove the old folder (if it's empty, it will be removed)
                dirname = os.path.dirname(old_path)
                while 1:
                    try:
                        os.rmdir(dirname)
                        dirname = os.path.dirname(dirname)
                    except:
                        break

        if errors:
            print "Errors:"
            for error in errors:
                print error
            print "-" * 20
        print "Found %s of %s snapshots which have paths different from naming" % (
            num_found, len(snapshots))
Exemple #41
0
    def get_shelf_wdg(self):

        process = self.get_value("process")
        versions = self.get_value("versions")

        div = DivWdg()

        filter_table = Table()
        div.add(filter_table)
        filter_table.add_row()

        button = SingleButtonWdg(title="Refresh", icon=IconWdg.REFRESH)
        filter_table.add_cell(button)
        filter_table.add_cell("&nbsp;" * 5)
        button.add_behavior({
            'type':
            'click_up',
            'cbjs_action':
            '''
            spt.panel.refresh(bvr.src_el);
            '''
        })

        # get all of the pipelnes for this search type
        pipeline_code = self.sobject.get_value("pipeline_code",
                                               no_exception=True)
        processes = []
        if pipeline_code:
            pipeline = Pipeline.get_by_code(pipeline_code)
            if pipeline:
                process_names = pipeline.get_process_names()
                processes.extend(process_names)

        processes.insert(0, "all")

        filter_table.add_cell("Process: ")
        select = SelectWdg("process")
        select.add_style("width: 200px")
        if process != 'all':
            select.set_value(process)

        select.set_option("values", processes)

        filter_table.add_cell(select)

        filter_table.add_cell("&nbsp;" * 10)

        filter_table.add_cell("Versions: ")
        select = SelectWdg("versions")
        select.add_style("width: 200px")
        select.set_option("values", "latest|current|today|last 10|all")
        if versions:
            select.set_value(versions)
        filter_table.add_cell(select)

        asset_dir = Environment.get_asset_dir()

        select = IconButtonWdg(tip="Toggle Selection",
                               icon=IconWdg.SELECT,
                               show_arrow=False)
        div.add(select)
        select.add_style("float: right")
        select.add_behavior({
            'type':
            'click_up',
            'cbjs_action':
            '''
            var top_class = 'spt_sobject_dir_list_top'
            var toggle_state = bvr.src_el.getAttribute('toggle');
            if (toggle_state && toggle_state=='true')
                bvr.src_el.setAttribute('toggle','false');
            else
                bvr.src_el.setAttribute('toggle','true');

            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            
            toggle_state = bvr.src_el.getAttribute('toggle');
            if (toggle_state == 'true')
                spt.selection.select_all_items();
            else
                spt.selection.unselect_all_items();

            '''
        })

        show = IconButtonWdg(tip="Switch View",
                             icon=IconWdg.VIEW,
                             show_arrow=False)
        div.add(show)
        show.add_style("float: right")
        show.add_behavior({
            'type':
            'click_up',
            'cbjs_action':
            '''
            var top_class = 'spt_sobject_dir_list_top'
            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            var els = top.getElements(".spt_file_dir_item");
            for (var i = 0; i < els.length; i++) {
                var el = els[i];
                if (el.getStyle("display") == "none") {
                    els[i].setStyle("display", "");
                }
                else {
                    els[i].setStyle("display", "none");
                }
            }
            var els = top.getElements(".spt_file_item");
            for (var i = 0; i < els.length; i++) {
                var el = els[i];
                if (el.getStyle("padding-left") == "6px") {
                    var padding = el.getAttribute("spt_padding_left");
                    el.setStyle("padding-left", padding);
                }
                else {
                    el.setStyle("padding-left", "6px");
                }

            }


            '''
        })

        gear = IconButtonWdg(tip="Download",
                             icon=IconWdg.DOWNLOAD,
                             show_arrow=False)
        div.add(gear)
        gear.add_style("float: right")
        gear.add_behavior({
            'type':
            'click_up',
            'cbjs_action':
            '''
            spt.app_busy.show('Select a folder to download to...','');
            var top_class = 'spt_sobject_dir_list_top';
            var top = bvr.src_el.getParent("."+top_class);
            spt.selection.set_top(top);
            var items = spt.selection.get_selected();
            
       
            setTimeout( function() {
                var applet = spt.Applet.get();
                var select_dir =true;
                var dir = applet.open_file_browser('', select_dir);
                if (dir.length == 0)
                    dir = applet.get_current_dir();
                else 
                    dir = dir[0];

                if (!dir) {
                    spt.alert("No folder selected to copy to.");
                    spt.app_busy.hide();
                    return;
                }
                if (items.length == 0){
                    spt.alert("Please select at least one file to download.");
                    spt.app_busy.hide();
                    return;
                }
                

                var asset_dir = '%s';
                for (var i = 0; i < items.length; i++) {
                    var path = items[i].getAttribute("spt_path");
                    var env = spt.Environment.get();
                    var server_url = env.get_server_url();
                    var url = server_url + "/assets/" + path.replace(asset_dir, "");
                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    spt.app_busy.show("Downloading file", filename);
                    applet.download_file(url, dir + "/" + filename);
                }
                spt.app_busy.hide();
                if (dir)
                    spt.notify.show_message("Download to '" + dir + "' completed.")
            }, 100);

            ''' % asset_dir
        })

        return div
Exemple #42
0
    def get_base_dir(self, protocol=None, alias="default"):
        '''get the default base directory for this sobject'''
        dirs = []
        base_dir = ''

        client_os = Environment.get_env_object().get_client_os()
        if client_os == 'nt':
            prefix = "win32"
        else:
            prefix = "linux"

        if not alias:
            alias = "default"


        if not protocol:
            protocol = self.protocol

        if protocol == "http":

            repo_handler = self.sobject.get_repo_handler(self.snapshot)
            if repo_handler.is_tactic_repo():
                base_dir = Environment.get_web_dir(alias=alias)
            else:
                alias_dict = Config.get_dict_value("perforce", "web_base_dir")
                base_dir = alias_dict.get(alias)

            if not base_dir:
                asset_alias_dict = Environment.get_asset_dirs()
                base_dir = asset_alias_dict.get(alias)
                base_dir = "/%s" % os.path.basename(base_dir)

            if not base_dir:
                base_dir = alias_dict.get("default")

            if not base_dir:
                base_dir = "/assets"


        elif protocol == "remote":
            # NOTE: currently needs web to get the full http base url
            base_dir = Environment.get_env_object().get_base_url().to_string()

       
            sub_dir = self.get_base_dir(protocol='http', alias=alias)
            base_dir = "%s%s" % (base_dir, sub_dir[0])

            
        elif protocol == "file":
            base_dir = Environment.get_asset_dir(alias=alias)

        elif protocol == "env":
            base_dir = "$TACTIC_ASSET_DIR"


        # This is the central repository as seen from the client
        elif protocol in ["client_lib", "client_repo"]:
            base_dir = self.get_custom_setting('%s_client_repo_dir' % prefix)
            if not base_dir:
                alias_dict = Config.get_dict_value("checkin", "%s_client_repo_dir" % prefix)
                base_dir = alias_dict.get(alias)

            if not base_dir:
                base_dir = Environment.get_asset_dir()


        # DEPRECATED: The local repo.  This one has logic to add "repo" dir
        # at the end.  Use local_repo which does not have this logic.
        # keeping this around for backward compatibility
        elif protocol == "local":
            remote_repo = self.get_remote_repo()
            if remote_repo:
                #base_dir = remote_repo.get_value("repo_base_dir")
                base_dir = Environment.get_asset_dir()
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_base_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_base_dir")
                base_dir += "/repo"

        # The local repo
        elif protocol == "local_repo":
            remote_repo = self.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("repo_base_dir")
            else:
                if Environment.get_env_object().get_client_os() =='nt':
                    base_dir = Config.get_value("checkin","win32_local_repo_dir")
                else:
                    base_dir = Config.get_value("checkin","linux_local_repo_dir")
                if not base_dir:
                    base_dir = Environment.get_asset_dir()


        elif protocol == "sandbox":

            remote_repo = self.get_remote_repo()
            if remote_repo:
                base_dir = remote_repo.get_value("sandbox_base_dir")
            else:
                if not base_dir:
                    base_dict = Config.get_dict_value("checkin","%s_sandbox_dir" % prefix)
                    base_dir = base_dict.get(alias)


        elif protocol == "relative":
            return []

        assert base_dir
        return [base_dir]
Exemple #43
0
    def execute(self):
        project_code = self.kwargs.get("project_code")
        transaction_code = self.kwargs.get("transaction_code")
        login = self.kwargs.get("login")

        session = self.kwargs.get("session")
        start_time = session.get("start_time")
        end_time = session.get("end_time")

        search_keys = session.get("search_keys")
        if search_keys != None:
            if search_keys == '':
                raise TacticException("No search keys passed in")
            search_keys = search_keys.split("|")
            if not search_keys:
                raise TacticException("No search keys passed in")

            transactions = Search.get_by_search_keys(search_keys)
            codes = [x.get_code() for x in transactions]
            assert len(search_keys) == len(codes)
            expr = '''@SOBJECT(sthpw/transaction_log['code','in','%s']['@ORDER_BY','code asc'])''' % ("|".join(codes))
        else:
            expr = '''@SOBJECT(sthpw/transaction_log['login','%s']['namespace','%s']['timestamp','&gt;','%s']['timestamp','&lt;','%s']['@ORDER_BY','code asc'])''' % (login, project_code, start_time, end_time)

        manifest_xml = '''
<manifest code='transaction_log' version='1'>
<sobject expression="%s" search_type="sthpw/transaction_log"/>
</manifest>
        ''' % (expr)


        plugin = SearchType.create("sthpw/plugin")
        plugin.set_value("code", "transaction_log")
        plugin.set_value("version", "1.0")

        creator = PluginCreator(manifest=manifest_xml, plugin=plugin)
        creator.execute()

        plugin_path = creator.get_plugin_path()

        plugin_dir = creator.get_plugin_dir()

        # find all the logs (again!!!)
        # FIXME: should get from plugin
        expr = expr.replace("&gt;", ">")
        expr = expr.replace("&lt;", "<")
        logs = Search.eval(expr)

        asset_dir = Environment.get_asset_dir()

        for log in logs:
            transaction_xml = log.get_xml_value("transaction").to_string()
            cmd = TransactionFilesCmd(transaction_xml=transaction_xml)
            paths = cmd.execute()
            for path in paths:
                rel_path = path.replace(asset_dir, "")
                rel_path = rel_path.lstrip("/")
                new_path = "%s/assets/%s" % (plugin_dir, rel_path)
                dirname = os.path.dirname(new_path)

                if not os.path.exists(dirname):
                    os.makedirs(dirname)

                print("adding: [%s]" % new_path)
                shutil.copy(path, new_path)
Exemple #44
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            'global':   {'server.socket_host': 'localhost',
                         'server.socket_port': 80,
                         'server.log_to_screen': False,
                         'server.environment': 'production',
                         'server.show_tracebacks': True,
                         'server.log_request_headers': True,
                         'server.log_file': "%s/tactic_log" % log_dir,
                         'server.max_request_body_size': 0,
                         #'server.socket_timeout': 60,
                         'response.timeout': 3600,
                         'log_debug_info_filter.on': False,

                         #'encoding_filter.on': True,
                         #'decoding_filter.on': True,
                        },
            '/context': {'static_filter.on': True,
                         'static_filter.dir': context_path
                        },
            '/assets':  {'static_filter.on': True,
                         'static_filter.dir': Environment.get_asset_dir()
                        },
            '/doc':     {'static_filter.on': True,
                         'static_filter.dir': doc_dir
                        },
            '/doc/':    {'static_filter.on': True,
                         'static_filter.file': "%s/index.html" % doc_dir
                        },
        }


        # set up the root directory
        cherrypy.root = Root()
        from tactic_sites.default.context.TitlePage import TitlePage
        cherrypy.root.tactic = TitlePage()
        cherrypy.root.projects = TitlePage()


       
        sites = []

        # add the tactic projects
        install_dir = Environment.get_install_dir().replace("\\", "/")
        site_dir = "%s/src/tactic_sites" % install_dir
        for context_dir in os.listdir(site_dir):
            if context_dir.startswith(".svn"):
                continue
                
            full_path  = "%s/%s" % (site_dir, context_dir)
            
            if os.path.isdir(full_path):
                sites.append(context_dir)



        # add all the custom projects
        site_dir = Environment.get_site_dir().replace("\\", "/")
        site_dir = "%s/sites" % site_dir
        for context_dir in os.listdir(site_dir):
            if context_dir.startswith(".svn"):
                continue
                
            full_path  = "%s/%s" % (site_dir, context_dir)
            
            if os.path.isdir(full_path):
                sites.append(context_dir)

        for site in sites:
            my.register_project(site, config)

            # set up the images directory
            for subdir in ['images', 'doc']:
                config["/tactic/%s/%s/" % (site,subdir)] = {
                    'static_filter.on': True,
                    'static_filter.dir': '%s/sites/%s/context/%s/' % \
                        (site_dir,site, subdir)
                }

        return config
Exemple #45
0
    def get_files(my):

        paths = []

        # remember this here for now
        my.files = {}
        my.snapshots = {}


        search_key = my.kwargs.get("search_key")
        sobject = SearchKey.get_by_search_key(search_key)
        # if it is deleted, return
        if not sobject:
            return []
    
        if isinstance(sobject, Snapshot):
            snapshots = [sobject]
        else:
            snapshots = Snapshot.get_by_sobject(sobject, "publish")

        for snapshot in snapshots:
            snapshot_paths = snapshot.get_all_lib_paths()

            files = snapshot.get_all_file_objects()

            for path, file in zip(snapshot_paths, files):

                # if the path is a directory, get all of the files
                if os.path.isdir(path):
                    for root, dirnames, filenames in os.walk(path):

                        for filename in filenames:
                            item_path = "%s/%s" % (root, filename)
                            paths.append(item_path)
                            my.files[item_path] = file
                            my.snapshots[item_path] = snapshot

                        for dirname in dirnames:
                            item_path = "%s/%s/" % (root, dirname)
                            paths.append(item_path)
                            my.files[item_path] = file
                            my.snapshots[item_path] = snapshot


                    """
                    dirlist = os.listdir(path)
                    for item in dirlist:
                        item_path = "%s%s" % (path, item)
                        if os.path.isdir(path):
                            item_path = "%s/" % item_path
                        paths.append(item_path)
                        my.files[path] = file
                    """

                else:
                    paths.append(path)
                    my.files[path] = file
                    base_dir_alias =  file.get_value('base_dir_alias')
                    if not my.base_dir and base_dir_alias:
                        my.base_dir = Environment.get_asset_dir(alias=base_dir_alias)

        return paths
Exemple #46
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()

        config = {
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,
                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
            },
            '/context': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': context_path,
                # Need to do this because on windows servers, jar files
                # are served as text/html
                'tools.staticdir.content_types': {
                    'jar': 'application/java-archive'
                }
            },
            '/assets': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': Environment.get_asset_dir()
            },
            '/doc': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': doc_dir,
                'tools.staticdir.index': "index.html"
            },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': plugin_dir,
            },
            '/tactic/builtin_plugins': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': builtin_plugin_dir,
            },
            '/tactic/dist': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': dist_dir,
            }
        }

        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount(cherrypy.root, config=config)

        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()

        # find out if one of the projects is the root
        root_initialized = False
        for project in projects:
            project_code = project.get_code()
            if False:
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True
                break

        if not root_initialized:
            project_code = Config.get_value("install", "default_project")
            if project_code and project_code != 'default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True

        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()

        for project in projects:
            project_code = project.get_code()
            my.register_site(project_code, config)
        my.register_site("default", config)

        return config
Exemple #47
0
    def setup_sites(my):

        context_path = "%s/src/context" % my.install_dir
        doc_dir = "%s/doc" % my.install_dir
        plugin_dir = Environment.get_plugin_dir()
        builtin_plugin_dir = Environment.get_builtin_plugin_dir()
        dist_dir = Environment.get_dist_dir()

        log_dir = "%s/log" % Environment.get_tmp_dir()



        def CORS():
            #cherrypy.response.headers["Access-Control-Allow-Origin"] = "http://192.168.0.15:8100"
            cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
            cherrypy.response.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Accept"
        cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)


        config = {
            
            'global': {
                'server.socket_host': '127.0.0.1',
                'server.socket_port': 80,
                'log.screen': False,
                'request.show_tracebacks': True,
                'tools.log_headers.on': True,
                'server.log_file': "%s/tactic_log" % log_dir,
                'server.max_request_body_size': 0,
                #'server.socket_timeout': 60,
                'response.timeout': 3600,

                'tools.encode.on': True,
                'tools.encode.encoding': 'utf-8',
                'tools.decode.on': True,
                'tools.decode.encoding': 'utf-8',
                #'encoding_filter.on': True,
                #'decoding_filter.on': True
                'tools.CORS.on': True

                },
            '/context': {'tools.staticdir.on': True,
                         'tools.staticdir.dir': context_path,
                         # Need to do this because on windows servers, jar files
                         # are served as text/html
                         'tools.staticdir.content_types': {
                             'jar': 'application/java-archive'
                         }
                        },
            '/assets':  {'tools.staticdir.on': True,
                         'tools.staticdir.dir': Environment.get_asset_dir()
                        },
            '/doc':     {'tools.staticdir.on': True,
                         'tools.staticdir.dir': doc_dir,
                         'tools.staticdir.index': "index.html"
                        },
            # NOTE: expose the entire plugins directory
            '/tactic/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/tactic/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/tactic/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        },
             '/plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': plugin_dir,
                        },
            '/builtin_plugins': {
                         'tools.staticdir.on': True,
                         'tools.staticdir.dir': builtin_plugin_dir,
                        },
            '/dist': {
                        'tools.staticdir.on': True,
                        'tools.staticdir.dir': dist_dir,
                        },
 

 

        }


        # set up the root directory
        cherrypy.root = Root()
        cherrypy.tree.mount( cherrypy.root, config=config)



        from pyasm.search import Search
        search = Search("sthpw/project")
        search.add_filter("type", "resource", op="!=")
        projects = search.get_sobjects()


        # find out if one of the projects is the root
        root_initialized = False

        if not root_initialized:
            project_code = Project.get_default_project()
            if project_code and project_code !='default':
                from tactic.ui.app import SitePage
                cherrypy.root.tactic = SitePage(project_code)
                cherrypy.root.projects = SitePage(project_code)
                root_initialized = True


        if not root_initialized:
            # load in the base site at root
            from tactic_sites.default.context.Index import Index
            cherrypy.root.tactic = Index()
            cherrypy.root.projects = Index()


        for project in projects:
            project_code = project.get_code()
            my.register_project(project_code, config)
        my.register_project("default", config)

        print


        from pyasm.security import Site
        site_obj = Site.get()
        site_obj.register_sites(my, config)
 

        #my.register_project("vfx", config, site="vfx_demo")
        #my.register_project("default", config, site="vfx_demo")
        return config
Exemple #48
0
    def _test_file_naming_manual_version(my):
       
        my.clear_naming()

        naming = SearchType.create('config/naming')
        naming.set_value('search_type','unittest/person')
        naming.set_value('context', 'naming_test')
        naming.set_value('dir_naming', '{project.code}/cut/{sobject.code}')
        naming.set_value('file_naming', '{sobject.code}_v{snapshot.version}.{ext}')
        naming.commit()

        from pyasm.common import Environment
        base_dir = Environment.get_asset_dir()
        
        preallocated = my.snapshot.get_preallocated_path(file_type='maya', file_name='what_v005.ma',ext='ma')
        my.assertEquals('%s/unittest/cut/phil/phil_v001.ma'%base_dir, preallocated)

        # now turn on manual_version
        naming.set_value('manual_version', True)
        naming.commit()

        my.clear_naming()
        preallocated = my.snapshot.get_preallocated_path(file_type='maya', file_name='what_v005.ma',ext='ma')
        my.assertEquals('%s/unittest/cut/phil/phil_v005.ma'%base_dir, preallocated)
        
        # Uppercase V and more digits
        preallocated = my.snapshot.get_preallocated_path(file_type='maya', file_name='what_V0010.ma',ext='ma')
        my.assertEquals('%s/unittest/cut/phil/phil_v010.ma'%base_dir, preallocated)
        #my.snapshot.commit()

        # zero or negative version is ignored
        # create a new manual version test.txt file
        file_path = "./naming_v0000_test.txt"
        for i in range(0,4):
            file = open(file_path, 'w')
            file.write("whatever")
            file.close()
        checkin = FileCheckin(my.person, file_path, "main", context='naming_test')
        checkin.execute()
        my.snapshot = checkin.get_snapshot()
        my.assertEquals(11, my.snapshot.get_version())

        # zero or negative version is ignored
        # create a new manual version test.txt file
        file_path = "./naming_v-23_test.txt"
        for i in range(0,4):
            file = open(file_path, 'w')
            file.write("whatever")
            file.close()
        checkin = FileCheckin(my.person, file_path, "main", context='naming_test')
        checkin.execute()
        my.snapshot = checkin.get_snapshot()
        my.assertEquals(12, my.snapshot.get_version())
        file_path = "./naming_v025_test.txt"
        for i in range(0,4):
            file = open(file_path, 'w')
            file.write("whatever")
            file.close()
        checkin = FileCheckin(my.person, file_path, "main", context='naming_test')
        checkin.execute()
        my.snapshot = checkin.get_snapshot()
        my.assertEquals(25, my.snapshot.get_version())


        naming.delete()

        my.clear_naming()
    def copy_start(my):
        #import pdb; pdb.set_trace()
        data_dir = Environment.get_data_dir(manual=True)

        # check to see if the data folder already exists
        print
        print "Data Directory [%s]" % data_dir
        install_dir = Environment.get_install_dir()

        # find criteria for initializing
        initialize = False
        if data_dir and not os.path.exists(data_dir):
            initialize = True

        if data_dir and not os.path.exists("%s/config" % data_dir):
            initialize = True


        if initialize:
            # copy the template over.  This should exist even if it is not used
            print "... not found: initializing\n"
            install_data_path = "%s/src/install/start" % (install_dir)
            if os.path.exists(install_data_path):
                dirnames = os.listdir(install_data_path)
                for dirname in dirnames:
                    to_dir = "%s/%s" % (data_dir, dirname)
                    if os.path.exists(to_dir):
                        print "WARNING: path [%s] exists ... skipping copying" % to_dir
                        continue
                    print "Copying to [%s]" % to_dir
                    from_dir = "%s/%s" % (install_data_path, dirname)
                    shutil.copytree(from_dir, to_dir)
            else:
                shutil.copytree(install_data_path, data_dir)


            #import pdb; pdb.set_trace()

            # copy the appropriate config file
            if os.name == 'nt':
                filename = 'standalone_win32-conf.xml'
            else:
                filename = 'standalone_linux-conf.xml'
            install_config_path = "%s/src/install/config/%s" % (install_dir,filename)
            to_config_path = "%s/config/tactic-conf.xml" % data_dir

            if not os.path.exists(to_config_path):
                dirname = os.path.dirname(to_config_path)
                if not os.path.exists(dirname):
                    os.makedirs(dirname)
                shutil.copy(install_config_path, to_config_path)

        # some backwards compatibility issues
        old_config_path = "%s/config/tactic_linux-conf.xml" % data_dir
        if os.path.exists(old_config_path):
            new_config_path = "%s/config/tactic-conf.xml" % data_dir
            shutil.move(old_config_path, new_config_path)



        config_path = Config.get_config_path()
        config_exists = False
        if os.path.exists(config_path):
            config_exists = True


        #import pdb; pdb.set_trace()
        asset_dir = Environment.get_asset_dir()
        print "Asset Directory [%s]" % asset_dir

        tmp_dir = Environment.get_tmp_dir()
        print "Temp Directory [%s]" % tmp_dir

        # check if there is a config path already exists. If it does,
        # then don't do anything further.  This is likely a previous
        # installation
        if config_exists:
            print "Config_path [%s]" % config_path
            return
        else:
            # if there is no config, retrieve data_dir in non-manual mode
            data_dir = Environment.get_data_dir()
            f = open("%s/first_run" % data_dir, 'w')
            f.write("")
            f.close()

        return
Exemple #50
0
    def get_display(my):

        my.sobject = my.kwargs.get("sobject")
        search_key = my.sobject.get_search_key()

        top = DivWdg()
        top.add_class("spt_checkin_publish")
        top.add_style("padding: 10px")

        margin_top = '60px'
        top.add_style("margin-top", margin_top)
        top.add_style("position: relative")


        current_changelist = WidgetSettings.get_value_by_key("current_changelist")
        current_branch = WidgetSettings.get_value_by_key("current_branch")
        current_workspace = WidgetSettings.get_value_by_key("current_workspace")

        top.add("Branch: %s<br/>" % current_branch)
        top.add("Changelist: %s<br/>" % current_changelist)
        top.add("Workspace: %s<br/>" % current_workspace)
        top.add("<br/>")


        checked_out_div = DivWdg()
        checkbox = CheckboxWdg("editable")
        top.add(checked_out_div)
        checkbox.add_class("spt_checkin_editable")
        checked_out_div.add(checkbox)
        checked_out_div.add("Leave files editable")

        top.add("<br/>")

        top.add("Publish Description<br/>")
        text = TextAreaWdg("description")
        # this needs to be set or it will stick out to the right
        text.add_style("width: 220px")
        text.add_class("spt_checkin_description")
        top.add(text)


        # add as a note
        note_div = DivWdg()
        top.add(note_div)
        note_div.add_class("spt_add_note")
        checkbox = CheckboxWdg("add_note")

        web = WebContainer.get_web()
        browser = web.get_browser()
        if browser in ['Qt']:
            checkbox.add_style("margin-top: -4px")
            checkbox.add_style("margin-right: 3px")
            note_div.add_style("margin-top: 3px")



        checkbox.add_class("spt_checkin_add_note")
        note_div.add(checkbox)
        note_div.add("Also add as note")

        top.add("<br/><br/>")


        button = ActionButtonWdg(title="Check-in", icon=IconWdg.PUBLISH, size='medium')
        top.add(button)

        my.repo_type = 'perforce'
        if my.repo_type == 'perforce':

            # the depot is set per project (unless overridden)
            project = my.sobject.get_project()
            depot = project.get_value("location", no_exception=True)
            if not depot:
                depot = project.get_code()

            asset_dir = Environment.get_asset_dir()
            sandbox_dir = Environment.get_sandbox_dir()
           
            changelist = WidgetSettings.get_value_by_key("current_changelist")
            button.add_behavior( {
            'type': 'click_up',
            'depot': depot,
            'changelist': changelist,
            'sandbox_dir': sandbox_dir,
            'search_key': search_key,
            'cbjs_action': '''

            var paths = spt.checkin.get_selected_paths();
            spt.app_busy.show("Checking in "+paths.length+" file/s into Perforce");
            var top = bvr.src_el.getParent(".spt_checkin_top");
            var description = top.getElement(".spt_checkin_description").value;
            var add_note = top.getElement(".spt_checkin_add_note").value;
            var editable = top.getElement(".spt_checkin_editable").value;

            if (editable == 'on') {
                editable = true;
            }
            else {
                editable = false;
            }

            var process = top.getElement(".spt_checkin_process").value;

            // check into TACTIC
            var server = TacticServerStub.get();

            var revisions = [];
            server.start({description: "File Check-in"});

            try {

            var top = bvr.src_el.getParent(".spt_checkin_top");
            var el = top.getElement(".spt_mode");
            var mode = el.value;

            // check-in the changelist
            var changelist = 'default';
            if (mode == 'changelist') {
                var scm_info = spt.scm.run("commit_changelist", [changelist, description]);

                for ( var i = 1; i < scm_info.length-1; i++) {
                    // the first item is the changelist number
                    //console.log(scm_info[i]);

                    var action = scm_info[i];
                    revision = action.rev;
                    revisions.push(revision);

                    // Do an inplace check-in into TACTIC
                    var path = action.depotFile;

                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    var context = process + "/" + filename;

                    var snapshot = server.simple_checkin(bvr.search_key, context, path, {description: description, mode: "perforce", version: revision} );
                }

            }
            else {

                // check in all of the files
                for ( var i = 0; i < paths.length; i++) {
                    var path = paths[i];
                    var scm_info = spt.scm.run("commit_file", [path, description, editable]);
                    // the first item is the changelist number
                    var action = scm_info[1];
                    revision = action.rev;
                    revisions.push(revision);

                    var parts = path.split("/");
                    var filename = parts[parts.length-1];
                    var context = process + "/" + filename;

                    //path = path.replace(bvr.sandbox_dir, "//"+bvr.depot);
                    // NOTE: this assumes project == depot
                    path = path.replace(bvr.sandbox_dir, "//");

                    // Do an inplace check-in into TACTIC
                    var snapshot = server.simple_checkin(bvr.search_key, context, path, {description: description, mode: "perforce", version: revision} );
                }
            }


            if (add_note == 'on') {
                var note = [];
                note.push('CHECK-IN');
                for (var i = 0; i < paths.length; i++) { 
                    var parts = paths[i].split("/");
                    var filename = parts[parts.length-1];
                    note.push(filename+' (v'+revisions[i]+')');
                }
                note.push(': ');
                note.push(description);

                note = note.join(" ");
                server.create_note(bvr.search_key, note, {process: process});
            }
            server.finish({description: "File Check-in ["+paths.length+" file/s]"});
            spt.panel.refresh(top);

            }
            catch(e) {
              spt.error("Error detected: " + e.msg)
              //console.log(e);
              server.abort();
            }

            spt.app_busy.hide();
            '''
            } )
        else:
            button.add_behavior(behavior)





        button.add_style("margin-right: auto")
        button.add_style("margin-left: auto")
        button.add_style("margin-top: 20px")
        button.add_style("margin-bottom: 20px")



        top.add("<br clear='all'/>")
        top.add("<hr/>")
 
        hidden = HiddenWdg("checkin_type")
        top.add(hidden)
        hidden.add_class("spt_checkin_type")


        grey_out_div = DivWdg()
        top.add(grey_out_div)
        grey_out_div.add_class("spt_publish_disable")
        grey_out_div.add_style("position: absolute")
        grey_out_div.add_style("left: 0px")
        grey_out_div.add_style("top: 10px")
        grey_out_div.add_style("opacity: 0.6")
        grey_out_div.add_color("background", "background")
        grey_out_div.add_style("height: 100%")
        grey_out_div.add_style("width: 100%")
        #grey_out_div.add_border()



        return top