Salesforce CLI is a very powerful tool to develop and deploy applications on the Salesforce platform.
Have you just moved your project to SFDX or recently started using Salesforce CLI? Do you find it complicated to deploy and retrieve metadata in non-scratch orgs using Salesforce CLI?
If yes, then you must know these handly commands.
Using "MDAPI" for metadata deploy and retrieve
You can retrieve metadata using the metadata API (mdapi topic commands) in Salesforce CLI. However, mdapi commands work with metadata format components, where SFDX only understands source format components.
This means if you are using mdapi commands for metadata retrieval, then you need to convert the components to source format later on. Below is a simple example:
sfdx force:mdapi:retrieve --unpackaged metadata/package.xml --retrievetargetdir mdapi_contents/
The above example would retrieve all the metadata defined in package.xml file and put inside a folder named mdapi_contents. Now you need to unzip this folder and the convert these components in source format.
sfdx force:mdapi:convert --rootdir mdapi_contents/ --outputdir force-app/
Now, if you want to deploy your components to Salesforce org from local project, then you first need to convert your source format components to metadata format and then only you can deploy it. Example:
sfdx force:source:convert --rootdir force-app --outputdir metadata_contents/ -n 'My Package'
sfdx force:mdapi:deploy --deploydir metadata_contents/
This can be very challenging when you are developing an application in your Salesforce org and frequently need to retrieve and deploy metadata (apex classes, lightning components etc).
What is the alternative or better approach?
Instead of using mdapi topic to retrieve and deploy metadata components, you can also use deploy and retrieve commands from “source” topic, which would convert your metadata format contents to source format, and convert source format to metadata format ON THE FLY. This means no need to run the convert commands.
For example, if you want to deploy your metadata to Salesforce org, then you can simply run:
sfdx force:source:deploy --sourcepath path/to/source
Or if you want to retrieve components, then you can run:
sfdx force:source:retrieve --sourcepath path/to/source
Not only this, you get more granular control over the metadata that you want to retrieve or deploy. Below are some examples:
To retrieve all Apex classes: sfdx force:source:retrieve -m ApexClass
To retrieve a specific Apex class: sfdx force:source:retrieve -m ApexClass:MyApexClass
To retrieve all custom objects and Apex classes: sfdx force:source:retrieve -m CustomObject,ApexClass
To retrieve all Apex classes and two specific profiles (one of which has a space in its name): sfdx force:source:retrieve -m "ApexClass, Profile:My Profile, Profile:AnotherProfile"
To retrieve all metadata components listed in a manifest: sfdx force:source:retrieve -x path/to/package.xml