Example #1
0
File: debug.py Project: azam/mm
 def execute(self):
     debug_users = config.project.get_debug_users()
     debug_settings = config.project.get_debug_settings()
     if self.params.get('running_user_only', False):
         payload = {}
         payload["debug_categories"] = debug_settings["levels"]
         payload["expiration"]       = debug_settings["expiration"]
         payload["user_id"]          = config.sfdc_client.user_id
         payload["type"]             = "user"
         response = NewTraceFlagCommand(params=payload).execute()
         response = json.loads(response)
         if "success" in response and response["success"] == False:
             return util.generate_error_response(response["errors"][0])
         return util.generate_success_response('Logging for runner user setup successfully')
     else:
         for u in debug_users:
             payload = {}
             payload["debug_categories"] = debug_settings["levels"]
             payload["expiration"]       = debug_settings["expiration"]
             payload["user_id"]          = u
             payload["type"]             = "user"
             response = NewTraceFlagCommand(params=payload).execute()
             response = json.loads(response)
             if "success" in response and response["success"] == False:
                 return util.generate_error_response(response["errors"][0])
         return util.generate_success_response('{0} Log(s) created successfully'.format(str(len(debug_users))))
Example #2
0
 def execute(self):
     debug_users = config.project.get_debug_users()
     debug_settings = config.project.get_debug_settings()
     if self.params.get('running_user_only', False):
         payload = {}
         payload["debug_categories"] = debug_settings["levels"]
         payload["expiration"] = debug_settings["expiration"]
         payload["user_id"] = config.sfdc_client.user_id
         payload["type"] = "user"
         response = NewTraceFlagCommand(params=payload).execute()
         response = json.loads(response)
         if "success" in response and response["success"] == False:
             return util.generate_error_response(response["errors"][0])
         return util.generate_success_response(
             'Logging for runner user setup successfully')
     else:
         for u in debug_users:
             payload = {}
             payload["debug_categories"] = debug_settings["levels"]
             payload["expiration"] = debug_settings["expiration"]
             payload["user_id"] = u
             payload["type"] = "user"
             response = NewTraceFlagCommand(params=payload).execute()
             response = json.loads(response)
             if "success" in response and response["success"] == False:
                 return util.generate_error_response(response["errors"][0])
         return util.generate_success_response(
             '{0} Log(s) created successfully'.format(str(
                 len(debug_users))))
Example #3
0
File: deploy.py Project: azam/mm
    def run(self):
        try:
            if 'password' not in self.destination:
                self.destination['password'] = util.get_password_by_key(self.destination['id'])
            deploy_client = MavensMateClient(credentials={
                "username":self.destination['username'],
                "password":self.destination['password'],
                "org_type":self.destination['org_type']
            })    

            # Check testRequired to find out if this is a production org.
            # This is a bit of a misnomer as runAllTests=True will run managed package tests, other 
            # tests are *always* run so we should honor the UI, however Production orgs do require 
            # rollbackOnError=True so we should override it here
            describe_result = deploy_client.describeMetadata(retXml=False)
            if describe_result.testRequired == True:
                self.params['rollback_on_error'] = True

            self.params['zip_file'] = self.deploy_metadata.zipFile      
            deploy_result = deploy_client.deploy(self.params)
            deploy_result['username'] = self.destination['username']
            debug('>>>>>> DEPLOY RESULT >>>>>>')
            debug(deploy_result)
            self.result = deploy_result
        except BaseException, e:
            result = util.generate_error_response(e.message, False)
            result['username'] = self.destination['username']
            self.result = result
Example #4
0
    def run(self):
        try:
            if 'password' not in self.destination:
                self.destination['password'] = util.get_password_by_key(
                    self.destination['id'])
            deploy_client = MavensMateClient(
                credentials={
                    "username": self.destination['username'],
                    "password": self.destination['password'],
                    "org_type": self.destination['org_type']
                })

            # Check testRequired to find out if this is a production org.
            # This is a bit of a misnomer as runAllTests=True will run managed package tests, other
            # tests are *always* run so we should honor the UI, however Production orgs do require
            # rollbackOnError=True so we should override it here
            describe_result = deploy_client.describeMetadata(retXml=False)
            if describe_result.testRequired == True:
                self.params['rollback_on_error'] = True

            self.params['zip_file'] = self.deploy_metadata.zipFile
            deploy_result = deploy_client.deploy(self.params)
            deploy_result['username'] = self.destination['username']
            debug('>>>>>> DEPLOY RESULT >>>>>>')
            debug(deploy_result)
            self.result = deploy_result
        except BaseException, e:
            result = util.generate_error_response(e.message, False)
            result['username'] = self.destination['username']
            self.result = result
Example #5
0
    def execute(self):
        debug('------> ')
        debug(self.params)
        try:
            if 'username' not in self.params or self.params['username'] == '':
                raise MMException('Please specify a username')
            if 'password' not in self.params or self.params['password'] == '':
                raise MMException('Please specify a password')
            if 'project_name' not in self.params or self.params['project_name'] == '':
                raise MMException('Please specify a project name')

            if ('action' in self.params and self.params['action'] == 'new') or 'action' not in self.params:
                if 'package' not in self.params or self.params['package'] == []:
                    self.params['package'] = {
                        'ApexClass'         : '*',
                        'ApexComponent'     : '*',
                        'ApexPage'          : '*',
                        'ApexTrigger'       : '*',
                        'StaticResource'    : '*'
                    }
                config.project = MavensMateProject(self.params)
                result = config.project.retrieve_and_write_to_disk()
            elif 'action' in self.params and self.params['action'] == 'existing':
                config.project = MavensMateProject(self.params)
                result = config.project.retrieve_and_write_to_disk('existing')

            if json.loads(result)['success'] == True and config.connection.get_plugin_client_setting('mm_open_project_on_create', True):
                #opens project based on the client
                client_location = config.connection.get_plugin_client_setting('mm_plugin_client_location')
                plugin_app_name = config.connection.get_plugin_client_setting('mm_osx_plugin_client_app_name') 
                if client_location == None:
                    client_location = '/Applications'
                if plugin_app_name == None:
                    plugin_app_name = 'Sublime Text 3.app'
                if config.connection.plugin_client == config.connection.PluginClients.SUBLIME_TEXT_2:
                    if sys.platform == 'darwin':
                        os.system("'{0}/Sublime Text 2.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(client_location,config.project.location+"/"+config.project.project_name+".sublime-project"))
                elif config.connection.plugin_client == config.connection.PluginClients.SUBLIME_TEXT_3:
                    if sys.platform == 'darwin':
                        if os.path.exists(os.path.join('{0}/{1}'.format(client_location, plugin_app_name))):
                            os.system("'{0}/{1}/Contents/SharedSupport/bin/subl' --project '{2}'".format(client_location,plugin_app_name,config.project.location+"/"+config.project.project_name+".sublime-project"))
                        elif os.path.exists(os.path.join('{0}/Sublime Text 3.app'.format(client_location))):
                            os.system("'{0}/Sublime Text 3.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(client_location,config.project.location+"/"+config.project.project_name+".sublime-project"))
                        else:
                            os.system("'{0}/Sublime Text.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(client_location,config.project.location+"/"+config.project.project_name+".sublime-project"))
                    elif 'linux' in sys.platform:
                        subl_location = config.connection.get_plugin_client_setting('mm_subl_location', '/usr/local/bin/subl')
                        os.system("'{0}' --project '{1}'".format(subl_location,os.path.join(config.project.location,config.project.project_name+".sublime-project")))
                    else:
                        subl_location = config.connection.get_plugin_client_setting('mm_windows_subl_location')
                        if not os.path.isfile(subl_location) and "x86" not in subl_location:
                            subl_location = subl_location.replace("Program Files", "Program Files (x86)")
                        cmd = '"{0}" --project "{1}"'.format(subl_location,os.path.join(config.project.location,config.project.project_name+".sublime-project"))
                        subprocess.call(cmd)
            return result
        except BaseException, e:
            return util.generate_error_response(e.message)
Example #6
0
    def execute(self):
        if 'package' not in self.params:
            raise MMException('"package" definition required in JSON body')
        package = self.params['package']

        #intercept and overwrite customobject retrieve to include standard objects
        if 'CustomObject' in package:
            for member in package['CustomObject']:
                if member == "*":
                    pass
                    #TODO

        clean_result = json.loads(config.project.clean(package=package,overwrite_package_xml=True))
        if clean_result['success'] == True:
            return util.generate_success_response('Project Edited Successfully')
        else:
            return util.generate_error_response(clean_result['body'])
Example #7
0
    def execute(self):
        if 'package' not in self.params:
            raise MMException('"package" definition required in JSON body')
        package = self.params['package']

        #intercept and overwrite customobject retrieve to include standard objects
        if 'CustomObject' in package:
            for member in package['CustomObject']:
                if member == "*":
                    pass
                    #TODO

        clean_result = config.project.clean(package=package,overwrite_package_xml=True)
        if clean_result['success'] == True:
            return util.generate_success_response('Project Edited Successfully')
        else:
            return util.generate_error_response(clean_result['body'])
Example #8
0
    def execute(self):
        if "package" not in self.params:
            raise MMException('"package" definition required in JSON body')
        package = self.params["package"]

        # intercept and overwrite customobject retrieve to include standard objects
        if "CustomObject" in package:
            for member in package["CustomObject"]:
                if member == "*":
                    pass
                    # TODO

        clean_result = json.loads(config.project.clean(package=package, overwrite_package_xml=True))
        if clean_result["success"] == True:
            return util.generate_success_response("Project Edited Successfully")
        else:
            return util.generate_error_response(clean_result["body"])
Example #9
0
    def run(self):
        try:
            if 'password' not in self.destination:
                self.destination['password'] = util.get_password_by_key(self.destination['id'])
            deploy_client = MavensMateClient(credentials={
                "username":self.destination['username'],
                "password":self.destination['password'],
                "org_type":self.destination['org_type']
            })    

            retrieve_result = deploy_client.retrieve(package=self.package)
            retrieve_result['username'] = self.destination['username']
            debug('>>>>>> RETRIEVE RESULT >>>>>>')
            debug(retrieve_result)
            self.result = retrieve_result
        except BaseException, e:
            result = util.generate_error_response(e.message, False)
            result['username'] = self.destination['username']
            self.result = result
Example #10
0
    def run(self):
        try:
            if 'password' not in self.destination:
                self.destination['password'] = util.get_password_by_key(
                    self.destination['id'])
            deploy_client = MavensMateClient(
                credentials={
                    "username": self.destination['username'],
                    "password": self.destination['password'],
                    "org_type": self.destination['org_type']
                })

            retrieve_result = deploy_client.retrieve(package=self.package)
            retrieve_result['username'] = self.destination['username']
            debug('>>>>>> RETRIEVE RESULT >>>>>>')
            debug(retrieve_result)
            self.result = retrieve_result
        except BaseException, e:
            result = util.generate_error_response(e.message, False)
            result['username'] = self.destination['username']
            self.result = result
Example #11
0
    def execute(self):
        project = config.project
        sfdc_client = config.sfdc_client
        if "files" in self.params:
            if "type" in self.params: 
                open_type = self.params.get("type", None) 
            else:
                open_type = "edit"
            files = self.params.get("files", None)
            if len(files) > 0:
                apex_file_properties = util.parse_json_from_file(os.path.join(project.location,"config",".local_store"))
                opened = []
                for fileabs in files:
                    basename = os.path.basename(fileabs)

                    if basename not in apex_file_properties: 
                        # make sure we have meta data and then get the object type
                        if os.path.isfile(fileabs+"-meta.xml"):
                            xmldoc = minidom.parse(fileabs+"-meta.xml")
                            root = xmldoc.firstChild
                            object_type = root.nodeName
                        else:
                            continue

                        object_id = sfdc_client.get_apex_entity_id_by_name(object_type=object_type, name=basename)
                        if not object_id: 
                            continue
                    else:
                        props = apex_file_properties[basename]
                        object_type = props['type']
                        object_id = props['id']

                    # only ApexClasses that are global and have webservice scope have WSDL files
                    if open_type == "wsdl":
                        if object_type != "ApexClass":
                            continue
                        with open(fileabs, 'r') as content_file:
                            content = content_file.read()
                            p = re.compile("global\s+(abstract\s+)?class\s", re.I + re.M)
                            if not p.search(content):
                                continue
                            p = re.compile("\swebservice\s", re.I + re.M)
                            if not p.search(content): 
                                continue

                    # get the server instance url and set the redirect url
                    frontdoor = "https://" + sfdc_client.server_url.split('/')[2] + "/secur/frontdoor.jsp?sid=" + sfdc_client.sid + "&retURL="
                    if open_type == "wsdl":
                        f, e = os.path.splitext(basename)
                        ret_url = "/services/wsdl/class/" + f
                    else:
                        f, ext = os.path.splitext(basename)
                        if object_type == "CustomObject" and not f.endswith('__c'):
                            # standard object?
                            ret_url = "/p/setup/layout/LayoutFieldList?type=" + f + "%23CustomFieldRelatedList_target"                             
                        else:
                            ret_url = "/" + object_id

                    # open the browser window for this file and track it
                    webbrowser.open(frontdoor+ret_url, new=2)
                    opened.append(basename)
                if len(opened) == 0:
                    return util.generate_error_response("There were no valid files to open.")
                return util.generate_success_response("Opened "+(", ".join(opened))+" on server.")
            return util.generate_error_response("Unable to open file on server.")
        else:
            raise MMException("To open on Salesforce, you must provide an array of 'files'")
Example #12
0
    def execute(self):
        debug("------> ")
        debug(self.params)
        try:
            if "username" not in self.params or self.params["username"] == "":
                raise MMException("Please specify a username")
            if "password" not in self.params or self.params["password"] == "":
                raise MMException("Please specify a password")
            if "project_name" not in self.params or self.params["project_name"] == "":
                raise MMException("Please specify a project name")

            if ("action" in self.params and self.params["action"] == "new") or "action" not in self.params:
                if "package" not in self.params or self.params["package"] == []:
                    self.params["package"] = {
                        "ApexClass": "*",
                        "ApexComponent": "*",
                        "ApexPage": "*",
                        "ApexTrigger": "*",
                        "StaticResource": "*",
                    }
                config.project = MavensMateProject(self.params)
                result = config.project.retrieve_and_write_to_disk()
            elif "action" in self.params and self.params["action"] == "existing":
                config.project = MavensMateProject(self.params)
                result = config.project.retrieve_and_write_to_disk("existing")

            if json.loads(result)["success"] == True and config.connection.get_plugin_client_setting(
                "mm_open_project_on_create", True
            ):
                # opens project based on the client
                client_location = config.connection.get_plugin_client_setting("mm_plugin_client_location")
                plugin_app_name = config.connection.get_plugin_client_setting("mm_osx_plugin_client_app_name")
                if client_location == None:
                    client_location = "/Applications"
                if plugin_app_name == None:
                    plugin_app_name = "Sublime Text 3.app"
                if config.connection.plugin_client == config.connection.PluginClients.SUBLIME_TEXT_2:
                    if sys.platform == "darwin":
                        os.system(
                            "'{0}/Sublime Text 2.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(
                                client_location,
                                config.project.location + "/" + config.project.project_name + ".sublime-project",
                            )
                        )
                elif config.connection.plugin_client == config.connection.PluginClients.SUBLIME_TEXT_3:
                    if sys.platform == "darwin":
                        if os.path.exists(os.path.join("{0}/{1}".format(client_location, plugin_app_name))):
                            os.system(
                                "'{0}/{1}/Contents/SharedSupport/bin/subl' --project '{2}'".format(
                                    client_location,
                                    plugin_app_name,
                                    config.project.location + "/" + config.project.project_name + ".sublime-project",
                                )
                            )
                        elif os.path.exists(os.path.join("{0}/Sublime Text 3.app".format(client_location))):
                            os.system(
                                "'{0}/Sublime Text 3.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(
                                    client_location,
                                    config.project.location + "/" + config.project.project_name + ".sublime-project",
                                )
                            )
                        else:
                            os.system(
                                "'{0}/Sublime Text.app/Contents/SharedSupport/bin/subl' --project '{1}'".format(
                                    client_location,
                                    config.project.location + "/" + config.project.project_name + ".sublime-project",
                                )
                            )
                    elif "linux" in sys.platform:
                        subl_location = config.connection.get_plugin_client_setting(
                            "mm_subl_location", "/usr/local/bin/subl"
                        )
                        os.system(
                            "'{0}' --project '{1}'".format(
                                subl_location,
                                os.path.join(config.project.location, config.project.project_name + ".sublime-project"),
                            )
                        )
                    else:
                        subl_location = config.connection.get_plugin_client_setting("mm_windows_subl_location")
                        if not os.path.isfile(subl_location) and "x86" not in subl_location:
                            subl_location = subl_location.replace("Program Files", "Program Files (x86)")
                        cmd = '"{0}" --project "{1}"'.format(
                            subl_location,
                            os.path.join(config.project.location, config.project.project_name + ".sublime-project"),
                        )
                        subprocess.call(cmd)
            return result
        except BaseException, e:
            return util.generate_error_response(e.message)
Example #13
0
File: metadata.py Project: azam/mm
    def execute(self):        
        project = config.project

        files = self.params.get('files', None)
        use_tooling_api = config.connection.get_plugin_client_setting('mm_compile_with_tooling_api', False)
        check_for_conflicts = config.connection.get_plugin_client_setting('mm_compile_check_conflicts', False)

        compiling_apex_metadata = True
        for f in files:
            if f.split('.')[-1] not in util.TOOLING_API_EXTENSIONS:
                #cannot use tooling api
                compiling_apex_metadata = False
                break

        #when compiling apex metadata, check to see if it is newer on the server
        if check_for_conflicts and compiling_apex_metadata:
            if 'action' not in self.params or self.params['action'] != 'overwrite':
                has_conflict, msg = config.project.conflict_manager.check_for_conflicts(files)
                if has_conflict:
                    return msg
     
        #use tooling api here, if possible
        if use_tooling_api == True and compiling_apex_metadata and int(float(util.SFDC_API_VERSION)) >= 27:
            if 'metadata_container' not in project.settings or project.settings['metadata_container'] == None:
                container_id = project.sfdc_client.get_metadata_container_id()
                new_settings = project.settings
                new_settings['metadata_container'] = container_id
                project.put_settings_file(new_settings)
            else:
                container_id = project.settings['metadata_container']
            
            file_ext = files[0].split('.')[-1]
            try:
                result = project.sfdc_client.compile_with_tooling_api(files, container_id)
            except MetadataContainerException as e:
                project.sfdc_client.delete_mavensmate_metadatacontainers_for_this_user()
                response = project.sfdc_client.new_metadatacontainer_for_this_user()
                project.update_setting("metadata_container",response["id"])
                return CompileSelectedMetadataCommand(params=self.params,args=self.args).execute()

            if 'Id' in result and 'State' in result:
                if result['State'] == 'Completed':
                    project.conflict_manager.refresh_local_store(files=files)
                return util.generate_response(result)

        #the user has either chosen not to use the tooling api, or it's non apex metadata
        else:
            try:
                for f in files:
                    if '-meta.xml' in f:
                        corresponding_file = f.split('-meta.xml')[0]
                        if corresponding_file not in files:
                            files.append(corresponding_file)
                for f in files:
                    if '-meta.xml' in f:
                        continue
                    file_ext = f.split('.')[-1]
                    metadata_type = util.get_meta_type_by_suffix(file_ext)
                    if metadata_type == None:
                        if sys.platform == "win32":
                            dir_parts = f.split("\\")
                        else:
                            dir_parts = f.split("/")
                        if 'documents' in dir_parts:
                            metadata_type = util.get_meta_type_by_name("Document") 
                    if metadata_type != None and 'metaFile' in metadata_type and metadata_type['metaFile'] == True:
                        corresponding_file = f + '-meta.xml'
                        if corresponding_file not in files:
                            files.append(corresponding_file)

                metadata_package_dict = util.get_metadata_hash(files)
                #debug(metadata_package_dict)
                tmp = util.put_tmp_directory_on_disk()
                os.makedirs(os.path.join(tmp,"unpackaged"))
                #copy files from project directory to tmp
                for full_file_path in files:
                    if 'package.xml' in full_file_path:
                        continue
                    if config.is_windows: 
                        destination = os.path.join(tmp,'unpackaged',full_file_path.split('\src\\')[1])
                    else:
                        destination = os.path.join(tmp,'unpackaged',full_file_path.split('/src/')[1])
                    destination_directory = os.path.dirname(destination)
                    if not os.path.exists(destination_directory):
                        os.makedirs(destination_directory)
                    shutil.copy2(full_file_path, destination_directory)

                package_xml = util.get_package_xml_contents(metadata_package_dict)
                util.put_package_xml_in_directory(os.path.join(tmp,"unpackaged"), package_xml)
                zip_file = util.zip_directory(tmp, tmp)
                deploy_params = {
                    "zip_file"          : zip_file,
                    "rollback_on_error" : True,
                    "ret_xml"           : True
                }
                deploy_result = project.sfdc_client.deploy(deploy_params)

                d = xmltodict.parse(deploy_result,postprocessor=util.xmltodict_postprocessor)
                result = d["soapenv:Envelope"]["soapenv:Body"]['checkDeployStatusResponse']['result']
                shutil.rmtree(tmp)

                # Get new properties for the files we just compiled
                if result['success'] == True:
                    project.conflict_manager.refresh_local_store(files=files)

                return json.dumps(result)

            except Exception, e:
                try:
                    shutil.rmtree(tmp)
                except:
                    pass
                return util.generate_error_response(e.message)
Example #14
0
File: metadata.py Project: azam/mm
    def execute(self):
        project = config.project
        sfdc_client = config.sfdc_client

        metadata_type                   = self.params.get('metadata_type', None)
        api_name                        = self.params.get('api_name', None)
        apex_class_type                 = self.params.get('apex_class_type', None)
        apex_trigger_object_api_name    = self.params.get('apex_trigger_object_api_name', None)
        apex_trigger_object_api_name    = self.params.get('apex_trigger_object_api_name', None)
        github_template                 = self.params.get('github_template', None)

        if metadata_type == 'ApexClass' and apex_class_type == None:
            apex_class_type = 'default'

        if api_name == None:
            return util.generate_error_response("You must provide a name for the new metadata.")

        if sfdc_client.does_metadata_exist(object_type=metadata_type, name=api_name) == True:
            mt = util.get_meta_type_by_name(metadata_type)
            filepath = os.path.join(project.location, 'src', mt['directoryName'], api_name+'.'+mt['suffix'])
            fetched = ""
            if not os.path.exists(filepath):
                self.params['files'] = [filepath]
                refresh_selected_metadata(self.params)
                fetched = ", fetched metadata file from server"
            raise MMException("This API name is already in use in your org" + fetched + ".")      

        tmp, tmp_unpackaged = util.put_tmp_directory_on_disk(True)
        
        util.put_skeleton_files_on_disk(metadata_type, api_name, tmp_unpackaged, apex_class_type, apex_trigger_object_api_name, github_template)
        package_xml_body = util.get_package_xml_contents({metadata_type : [ api_name ]})
        util.put_package_xml_in_directory(tmp_unpackaged, package_xml_body)
        zip_file = util.zip_directory(tmp, tmp)
        deploy_params = {
            "zip_file"          : zip_file,
            "rollback_on_error" : True,
            "ret_xml"           : True
        }
        deploy_result = sfdc_client.deploy(deploy_params)
        d = xmltodict.parse(deploy_result,postprocessor=util.xmltodict_postprocessor)
        meta_dir = ""
        files = []
        path = None
        for dirname, dirnames, filenames in os.walk(tmp_unpackaged):
            for filename in filenames:
                if 'package.xml' in filename:
                    continue
                full_file_path = os.path.join(dirname, filename)
                if '-meta.xml' in filename:
                    extension = filename.replace('-meta.xml','').split(".")[-1]
                else:
                    extension = filename.split(".")[-1]
                mt = util.get_meta_type_by_suffix(extension)
                if mt != None: 
                    meta_dir = mt['directoryName']
                    path = os.path.join(project.location, 'src', meta_dir)
                    if not os.path.exists(path):
                        os.makedirs(path)
                    files.append(os.path.join(path, filename))
                elif extension != "xml":
                    continue;
                # only apex files and meta.xml files should make it to here
                shutil.copy(full_file_path, path)
        shutil.rmtree(tmp)
        
        project.update_package_xml_with_metadata(metadata_type, api_name)
        project.conflict_manager.refresh_local_store(files=files)

        return json.dumps(d["soapenv:Envelope"]["soapenv:Body"]['checkDeployStatusResponse']['result'])
Example #15
0
File: metadata.py Project: azam/mm
    def execute(self):
        project = config.project
        sfdc_client = config.sfdc_client
        if "files" in self.params:
            if "type" in self.params: 
                open_type = self.params.get("type", None) 
            else:
                open_type = "edit"
            files = self.params.get("files", None)
            if len(files) > 0:
                apex_file_properties = util.parse_json_from_file(os.path.join(project.location,"config",".local_store"))
                opened = []
                for fileabs in files:
                    basename = os.path.basename(fileabs)

                    if basename not in apex_file_properties: 
                        # make sure we have meta data and then get the object type
                        if os.path.isfile(fileabs+"-meta.xml"):
                            xmldoc = minidom.parse(fileabs+"-meta.xml")
                            root = xmldoc.firstChild
                            object_type = root.nodeName
                        else:
                            continue

                        object_id = sfdc_client.get_apex_entity_id_by_name(object_type=object_type, name=basename)
                        if not object_id: 
                            continue
                    else:
                        props = apex_file_properties[basename]
                        object_type = props['type']
                        object_id = props['id']

                    # only ApexClasses that are global and have webservice scope have WSDL files
                    if open_type == "wsdl":
                        if object_type != "ApexClass":
                            continue
                        with open(fileabs, 'r') as content_file:
                            content = content_file.read()
                            p = re.compile("global\s+(abstract\s+)?class\s", re.I + re.M)
                            if not p.search(content):
                                continue
                            p = re.compile("\swebservice\s", re.I + re.M)
                            if not p.search(content): 
                                continue

                    # get the server instance url and set the redirect url
                    frontdoor = "https://" + sfdc_client.server_url.split('/')[2] + "/secur/frontdoor.jsp?sid=" + sfdc_client.sid + "&retURL="
                    if open_type == "wsdl":
                        f, e = os.path.splitext(basename)
                        ret_url = "/services/wsdl/class/" + f
                    else:
                        f, ext = os.path.splitext(basename)
                        if object_type == "CustomObject" and not f.endswith('__c'):
                            # standard object?
                            ret_url = "/p/setup/layout/LayoutFieldList?type=" + f + "%23CustomFieldRelatedList_target"                             
                        else:
                            ret_url = "/" + object_id

                    # open the browser window for this file and track it
                    webbrowser.open(frontdoor+ret_url, new=2)
                    opened.append(basename)
                if len(opened) == 0:
                    return util.generate_error_response("There were no valid files to open.")
                return util.generate_success_response("Opened "+(", ".join(opened))+" on server.")
            return util.generate_error_response("Unable to open file on server.")
        else:
            raise MMException("To open on Salesforce, you must provide an array of 'files'")
Example #16
0
    def execute(self):
        project = config.project
        sfdc_client = config.sfdc_client

        metadata_type                   = self.params.get('metadata_type', None)
        github_template                 = self.params.get('github_template', None)
        params                          = self.params.get('params', None)

        if params == None:
            raise MMException('The payload to create metadata has recently changed. If you are using Sublime Text, you likely need to update your MavensMate plugin to 3.4.8+')

        if "api_name" not in params or params["api_name"] == None:
            return util.generate_error_response("You must provide a name for the new metadata.")

        api_name = params.get('api_name')

        if sfdc_client.does_metadata_exist(object_type=metadata_type, name=api_name) == True:
            mt = util.get_meta_type_by_name(metadata_type)
            filepath = os.path.join(project.location, 'src', mt['directoryName'], api_name+'.'+mt['suffix'])
            fetched = ""
            if not os.path.exists(filepath):
                self.params['files'] = [filepath]
                RefreshSelectedMetadataCommand(params=self.params,args=self.args).execute()
                fetched = ", fetched metadata file from server"
            raise MMException("This API name is already in use in your org" + fetched + ".")      

        tmp, tmp_unpackaged = util.put_tmp_directory_on_disk(True)
        
        util.put_skeleton_files_on_disk(metadata_type, tmp_unpackaged, github_template, params)
        package_xml_body = util.get_package_xml_contents({metadata_type : [ api_name ]})
        util.put_package_xml_in_directory(tmp_unpackaged, package_xml_body)
        zip_file = util.zip_directory(tmp, tmp)
        deploy_params = {
            "zip_file"          : zip_file,
            "rollback_on_error" : True,
            "ret_xml"           : True
        }
        deploy_result = sfdc_client.deploy(deploy_params)
        d = xmltodict.parse(deploy_result,postprocessor=util.xmltodict_postprocessor)
        meta_dir = ""
        files = []
        path = None
        for dirname, dirnames, filenames in os.walk(tmp_unpackaged):
            for filename in filenames:
                if 'package.xml' in filename:
                    continue
                full_file_path = os.path.join(dirname, filename)
                if '-meta.xml' in filename:
                    extension = filename.replace('-meta.xml','').split(".")[-1]
                else:
                    extension = filename.split(".")[-1]
                mt = util.get_meta_type_by_suffix(extension)
                if mt != None: 
                    meta_dir = mt['directoryName']
                    path = os.path.join(project.location, 'src', meta_dir)
                    if not os.path.exists(path):
                        os.makedirs(path)
                    files.append(os.path.join(path, filename))
                elif extension != "xml":
                    continue;
                # only apex files and meta.xml files should make it to here
                shutil.copy(full_file_path, path)
        shutil.rmtree(tmp)
        
        project.update_package_xml_with_metadata(metadata_type, api_name)
        project.conflict_manager.refresh_local_store(files=files)

        return json.dumps(d["soapenv:Envelope"]["soapenv:Body"]['checkDeployStatusResponse']['result'])
Example #17
0
    def execute(self):        
        project = config.project

        files = self.params.get('files', None)
        use_tooling_api = config.connection.get_plugin_client_setting('mm_compile_with_tooling_api', False)
        check_for_conflicts = config.connection.get_plugin_client_setting('mm_compile_check_conflicts', False)

        compiling_apex_metadata = True
        for f in files:
            if f.split('.')[-1] not in util.TOOLING_API_EXTENSIONS:
                #cannot use tooling api
                compiling_apex_metadata = False
                break

        #when compiling apex metadata, check to see if it is newer on the server
        if check_for_conflicts and compiling_apex_metadata:
            if 'action' not in self.params or self.params['action'] != 'overwrite':
                has_conflict, msg = config.project.conflict_manager.check_for_conflicts(files)
                if has_conflict:
                    return msg
     
        #use tooling api here, if possible
        if use_tooling_api == True and compiling_apex_metadata and int(float(util.SFDC_API_VERSION)) >= 27:
            if 'metadata_container' not in project.settings or project.settings['metadata_container'] == None:
                container_id = project.sfdc_client.get_metadata_container_id()
                new_settings = project.settings
                new_settings['metadata_container'] = container_id
                project.put_settings_file(new_settings)
            else:
                container_id = project.settings['metadata_container']
            
            file_ext = files[0].split('.')[-1]
            try:
                result = project.sfdc_client.compile_with_tooling_api(files, container_id)
            except MetadataContainerException as e:
                project.sfdc_client.delete_mavensmate_metadatacontainers_for_this_user()
                response = project.sfdc_client.new_metadatacontainer_for_this_user()
                project.update_setting("metadata_container",response["id"])
                #return CompileSelectedMetadataCommand(params=self.params,args=self.args).execute()
                #ensure only a single retry
                result = project.sfdc_client.compile_with_tooling_api(files, response["id"])

            if 'Id' in result and 'State' in result:
                if result['State'] == 'Completed':
                    project.conflict_manager.refresh_local_store(files=files)
                return util.generate_response(result)

        #the user has either chosen not to use the tooling api, or it's non apex metadata
        else:
            try:
                for f in files:
                    if '-meta.xml' in f:
                        corresponding_file = f.split('-meta.xml')[0]
                        if corresponding_file not in files:
                            files.append(corresponding_file)
                for f in files:
                    if '-meta.xml' in f:
                        continue
                    file_ext = f.split('.')[-1]
                    metadata_type = util.get_meta_type_by_suffix(file_ext)
                    if metadata_type == None:
                        if sys.platform == "win32":
                            dir_parts = f.split("\\")
                        else:
                            dir_parts = f.split("/")
                        if 'documents' in dir_parts:
                            metadata_type = util.get_meta_type_by_name("Document") 
                    if metadata_type != None and 'metaFile' in metadata_type and metadata_type['metaFile'] == True:
                        corresponding_file = f + '-meta.xml'
                        if corresponding_file not in files:
                            files.append(corresponding_file)

                metadata_package_dict = util.get_metadata_hash(files)
                #debug(metadata_package_dict)
                tmp = util.put_tmp_directory_on_disk()
                os.makedirs(os.path.join(tmp,"unpackaged"))
                #copy files from project directory to tmp
                for full_file_path in files:
                    if 'package.xml' in full_file_path:
                        continue
                    if config.is_windows: 
                        destination = os.path.join(tmp,'unpackaged',full_file_path.split('\src\\')[1])
                    else:
                        destination = os.path.join(tmp,'unpackaged',full_file_path.split('/src/')[1])
                    destination_directory = os.path.dirname(destination)
                    if not os.path.exists(destination_directory):
                        os.makedirs(destination_directory)
                    shutil.copy2(full_file_path, destination_directory)

                package_xml = util.get_package_xml_contents(metadata_package_dict)
                util.put_package_xml_in_directory(os.path.join(tmp,"unpackaged"), package_xml)
                zip_file = util.zip_directory(tmp, tmp)
                deploy_params = {
                    "zip_file"          : zip_file,
                    "rollback_on_error" : True,
                    "ret_xml"           : True
                }
                deploy_result = project.sfdc_client.deploy(deploy_params)

                d = xmltodict.parse(deploy_result,postprocessor=util.xmltodict_postprocessor)
                result = d["soapenv:Envelope"]["soapenv:Body"]['checkDeployStatusResponse']['result']
                shutil.rmtree(tmp)

                # Get new properties for the files we just compiled
                if result['success'] == True:
                    project.conflict_manager.refresh_local_store(files=files)

                return json.dumps(result)

            except Exception, e:
                try:
                    shutil.rmtree(tmp)
                except:
                    pass
                return util.generate_error_response(e.message)