rustsf 0.1.1

Salesforce SDK for Rust, supports the latest API version 68.0, (Winter 2026)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! # Salesforce Metadata Deployer
//!
//! The Metadata Deployer is responsible for packaging the metadata
//! so that it is ready to be deployed to Salesforce.
//!
//! It handles the creation of the deployment zip file, as well as the generation of the
//! package.xml files.
//!
//! ## Supported Endpoints:
//! - **/services/data/vXX.X/metadata/deployRequest**, for deployments, status checks, and cancellation
//!

use crate::errors::Error;
use crate::metadata_api::responses::deploy_options::DeployOptions;
use crate::metadata_api::responses::deploy_request::DeployRequest;
use crate::metadata_api::{add_file_to_package, generate_package_xml};
use s_zip::{SZipError, StreamingZipWriter};
use std::collections::HashMap;
use std::io::Cursor;
use log::debug;

/**
fix me refactor s-zip into zip

use std::io::Write;
use zip::write::SimpleFileOptions;
use zip::ZipWriter;
use std::io::Cursor;

fn create_zip_in_memory() -> Vec<u8> {
	// 1. Create an in-memory buffer
	let mut buf = Cursor::new(Vec::new());

	// 2. Initialize the ZipWriter
	let mut zip = ZipWriter::new(&mut buf);

	// 3. Add a file with options (e.g., compression method)
	let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflate);
	zip.start_file("hello.txt", options).unwrap();

	// 4. Write the in-memory data to the zip entry
	zip.write_all(b"Hello, World!").unwrap();

	// 5. Finalize the archive
	zip.finish().unwrap();

	// 6. Retrieve the resulting bytes
	buf.into_inner()
}
*/

/// A `RestApi` struct that represents the core component for reparing a deployment
pub struct MetadataDeployer {
	options: DeployOptions,
	writer: StreamingZipWriter<Cursor<Vec<u8>>>,
	package: HashMap<String, Vec<String>>,
	pre_destructive: HashMap<String, Vec<String>>,
	post_destructive: HashMap<String, Vec<String>>,
}

impl MetadataDeployer {
	///
	/// Creates a new instance of `MetadataDeployer`.
	///
	/// # Arguments
	///
	/// * `client` - A reference to a `Client` instance used for initializing the `MetadataDeployer`.
	///   The `Client` provides the Salesforce version number through its `version_number` method.
	///
	/// # Returns
	///
	/// Returns a newly instantiated `MetadataDeployer` object.
	/// The following components are initialized:
	/// - `version`: The version number retrieved from the client. Defaults to `"67.0"` if unable to fetch the version.
	/// - `options`: A new instance of `DeployOptions`.
	/// - `writer`: A `StreamingZipWriter` with a cursor-based underlying buffer for writing deployment packages.
	/// - `package`, `pre_destructive`, `post_destructive`: Empty `HashMap` instances to hold deployment metadata.
	///
	/// # Example
	///
	/// ```
	/// let client= Client::new(Credentials::new()).await?;
	/// let deployer = MetadataDeployer::new(&client);
	/// ```
	pub fn new() -> Self {
		MetadataDeployer {
			options: DeployOptions::new(),
			writer: StreamingZipWriter::from_writer(Cursor::new(Vec::new())).unwrap(),
			package: HashMap::new(),
			pre_destructive: HashMap::new(),
			post_destructive: HashMap::new(),
		}
	}

	/// Sets the deployment options for the current instance.
	///
	/// This method allows you to configure the deployment behavior by updating the
	/// `options` field with the provided `DeployOptions` instance.
	///
	/// # Arguments
	///
	/// * `options` - A `DeployOptions` struct containing the desired configuration
	///               for deployment.
	///
	/// # Example
	///
	/// ```rust
	/// let mut deploy_instance = DeployManager::new();
	/// let new_options = DeployOptions::default();
	/// deploy_instance.set_options(new_options);
	/// ```
	///
	/// After calling this method, the instance will use the newly provided
	/// deployment options.
	///
	/// # Notes
	///
	/// This method requires a mutable reference to the instance, as it modifies
	/// the internal state.
	pub fn set_options(&mut self, options: DeployOptions) {
		self.options = options;
	}

	/// Adds a file and its corresponding metadata file to the deployment zip
	/// and registers the file in the deployment package.
	///
	/// # Parameters
	/// - `metadata_type`: The type of Salesforce metadata (e.g., `"ApexClass"`).
	/// - `folder`: The directory where the file should be stored (e.g., `"classes"`).
	/// - `file_name`: The name of the file to add (e.g., `"MyClass.cls"`).
	/// - `content`: The content of the file being added.
	/// - `file_name_xml`: (optional) The name of an associated XML metadata file (e.g., `"MyClass.cls-meta.xml"`).
	/// - `content_xml`: (optional) The content of the associated XML metadata file.
	///
	/// # Returns
	/// - `Result<(), Error>`: Returns `Ok(())` on success, or an `Error` variant if any operation (e.g., writing to the zip) fails.
	///
	/// # Behavior
	/// - Adds the main file to the deployment zip in the specified folder.
	/// - Optionally adds the corresponding XML metadata file to the deployment zip if both `file_name_xml` and `content_xml` are provided.
	/// - Registers the file name (without the extension) in the deployment package under the specified `metadata_type`.
	///
	/// # Example
	///
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///     let mut request = api.new_deployment_request();
	///     request.add(
	///         "ApexClass",
	///         "classes",
	///         "MyClass.cls",
	///         b"public class MyClass {}",
	///         Some("MyClass.cls-meta.xml"),
	///         Some(r#"<?xml version="1.0" encoding="UTF-8"?>
	/// <ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
	///     <apiVersion>68.0</apiVersion>
	///     <status>Active</status>
	/// </ApexClass>
	/// "#.as_bytes()))?;
	///
	///     let response = api.deploy(request).await?;
	///     println!("Deploy response {:?}", response);
	/// }
	/// ```
	///
	/// **Note:**
	/// - The folder structure (`folder`) should coincide with Salesforce metadata conventions.
	/// - The code assumes that the file name has an extension and leverages `split(".").next()`—a `fixme` note is included as this could panic if the file name is incorrectly formatted.
	///
	pub fn add(
		&mut self,
		metadata_type: &str,         // e.g. "ApexClass"
		folder: &str,                // e.g. "classes"  todo - should should be queried from salesforce
		file_name: &str,             // e.g. "MyClass.cls"
		content: &[u8],              //
		file_name_xml: Option<&str>, // e.g. "MyClass.cls-meta.xml"
		content_xml: Option<&[u8]>,  //
	) -> Result<&mut Self, Error> {
		self.add_file_to_zip(folder, file_name, content)
			.map_err(|e| Error::CompressionError(e.to_string()))?;

		// Optionally add the xml file to the zip
		match (file_name_xml, content_xml) {
			(Some(file_name_xml), Some(content_xml)) => {
				self.add_file_to_zip(folder, file_name, content)
					.map_err(|e| Error::CompressionError(e.to_string()))?;

				self.add_file_to_zip(folder, file_name_xml, content_xml)
					.map_err(|e| Error::CompressionError(e.to_string()))?;
			}
			_ => {}
		}

		add_file_to_package(&mut self.package, metadata_type, file_name);

		Ok(self)
	}

	/// Deletes one or more metadata objects after the deplopment is completed,
	/// by adding them to a "destructive" package file.
	///
	/// # Parameters
	/// * `metadata_type`: The type of metadata (e.g., "CustomObject", "ApexClass") that is being deleted.
	/// * `objects`: The names of the metadata objects to be deleted.
	///
	/// # Returns
	/// A mutable reference to `self`, allowing for method chaining.
	///
	/// # Behavior
	/// For each object name provided in the `objects` vector, this function adds
	/// the object to a "post-destructive" package file using the `add_file_to_package`
	/// helper function. This is commonly used in deployment processes to specify
	/// metadata components to be removed.
	///
	/// # Example
	///
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///     let mut request = api.new_deployment_request();
	///     request.delete_post("ApexClass", vec!["MyClass.cls"]);
	///
	///     let response = api.deploy(request).await?;
	///     println!("Deploy response {:?}", response);
	/// }
	/// ```
	pub fn delete_post(&mut self, metadata_type: &str, objects: Vec<&str>) -> &mut Self {
		for file_name in objects {
			add_file_to_package(&mut self.post_destructive, metadata_type, file_name);
		}
		self
	}

	/// Deletes one or more metadata objects before the deplopment is started,
	/// by adding them to a "destructive" package file.
	///
	/// # Parameters
	/// * `metadata_type`: The type of metadata (e.g., "CustomObject", "ApexClass") that is being deleted.
	/// * `objects`: The names of the metadata objects to be deleted.
	///
	/// # Returns
	/// A mutable reference to `self`, allowing for method chaining.
	///
	/// # Behavior
	/// For each object name provided in the `objects` vector, this function adds
	/// the object to a "post-destructive" package file using the `add_file_to_package`
	/// helper function. This is commonly used in deployment processes to specify
	/// metadata components to be removed.
	///
	/// # Example
	///
	/// ```rust
	/// use rustsf::{Client, Credentials, MetadataApi};
	///
	/// #[tokio::main]
	/// async fn main() {
	///     let client= Client::new(Credentials::new()).await?;
	///     // Authentication logic...
	///
	///     let mut api = MetadataApi::new(client);
	///     let mut request = api.new_deployment_request();
	///     request.delete_pre("ApexClass", vec!["MyClass.cls"]);
	///
	///     let response = api.deploy(request).await?;
	///     println!("Deploy response {:?}", response);
	/// }
	/// ```
	pub fn delete_pre(&mut self, metadata_type: &str, objects: Vec<&str>) -> &mut Self {
		for file_name in objects {
			add_file_to_package(&mut self.pre_destructive, metadata_type, file_name);
		}
		self
	}

	/// Adds a file to the zip-file used in the deployment
	///
	/// # Parameters
	/// - `folder`: The name of the folder (e.g. "classes")
	/// - `file_name`: The name of the file (e.g. "MyClass.cls")
	/// - `content`: The content of the file
	///
	/// # Returns
	/// - `Ok(())` on success, indicating that the package was successfully added.
	/// - `Err(Error)`: Returns an error if writing to the storage fails during entry creation or data writing.
	///
	/// # Errors
	/// This method returns an `SZipError` if something went wrong writing the file to the zip-file
	///
	fn add_file_to_zip(&mut self, folder: &str, file_name: &str, content: &[u8]) -> Result<(), SZipError> {
		let filename = format!("{}/{}", folder, file_name);
		self.writer.start_entry(filename.as_str())?;
		self.writer.write_data(content)?;
		Ok(())
	}

	/// Adds a package to the storage by generating its metadata and writing it to the output stream.
	///
	/// # Parameters
	/// - `name`: A string slice representing the name of the package (e.g., the file name or package identifier).
	/// - `content`: A reference to a `HashMap` where keys are `String` values representing metadata categories or types,
	///              and values are `Vec<String>` representing the associated data for those categories.
	///
	/// # Returns
	/// - `Ok(())` on success, indicating that the package was successfully added.
	/// - `Err(Error)`: Returns an error if writing to the storage fails during entry creation or data writing.
	///
	/// # Errors
	/// This method returns an `Error::RequestError` if either of the following operations fail:
	/// - `start_entry`: An error occurs while starting the entry creation process for the package.
	/// - `write_data`: An error occurs while writing the generated package metadata to the output stream.
	///
	fn add_package(&mut self, name: &str, content: HashMap<String, Vec<String>>) -> Result<(), Error> {
		let package = generate_package_xml(crate::client::DEFAULT_API_VERSION, &content);
		debug!("Adding package: {}\n{}", name, package);

		self.writer
			.start_entry(name)
			.map_err(|e| Error::CompressionError(e.to_string()))?;

		self.writer
			.write_data(package.as_bytes())
			.map_err(|e| Error::CompressionError(e.to_string()))?;

		Ok(())
	}

	/// Generates a JSON representation of the `DeployRequest`.
	///
	/// # Returns
	/// - `Ok(String)`: A string containing the JSON-encoded `DeployRequest`.
	/// - `Err(Error)`: An error if serialization fails.
	///
	/// # Errors
	/// This function will return an `Error::RequestError` if the `DeployRequest`
	/// struct cannot be serialized to JSON.
	///
	/// # Example
	/// ```rust
	/// let deploy_request_json = instance.get_deploy_request_json();
	/// match deploy_request_json {
	///     Ok(json) => println!("DeployRequest JSON: {}", json),
	///     Err(e) => eprintln!("Error generating JSON: {}", e),
	/// }
	/// ```
	pub(crate) fn get_deploy_request_json(&self) -> Result<String, Error> {
		let request = DeployRequest {
			options: self.options.clone(),
		};
		serde_json::to_string(&request).map_err(|e| Error::Json(e))
	}

	/// Generates a ZIP file containing the specified package files and returns it as a `Vec<u8>`.
	///
	/// # Functionality
	/// This method creates a ZIP file by adding a package XML file (`package.xml`)
	/// and optionally including pre- and post-destructive change XML files (`destructiveChangesPre.xml`
	/// and `destructiveChangesPost.xml`) if they are present. It finalizes the ZIP writer
	/// and returns the resulting ZIP file as a byte vector.
	///
	/// # Parameters
	/// - `self`: Consumes the struct instance, giving ownership of the struct's data to the method.
	///
	/// # Returns
	/// - `Ok(Vec<u8>)`: A `Vec<u8>` containing the bytes of the generated ZIP file upon successful
	///   creation and finalization of the ZIP writer.
	/// - `Err(Error)`: An error of type `Error` if there is a failure during the ZIP construction process.
	///
	/// # Errors
	/// - `Error::RequestError`: Returned when the ZIP writer encounters an error during the finalization process.
	///
	/// # Usage Example
	/// ```rust
	/// let zip_file = my_instance.get_zip_file()?;
	/// // Use the generated `zip_file` (a `Vec<u8>`) as needed
	/// ```
	///
	/// # Notes
	/// - The function assumes that `self.add_package` properly adds the specified files to the ZIP.
	/// - If `pre_destructive` or `post_destructive` is empty, the corresponding file will not be added to the ZIP.
	/// - The `finish` method on the ZIP writer is expected to finalize the ZIP and produce a writable result.
	///
	pub(crate) fn get_zip_file(mut self) -> Result<Vec<u8>, Error> {
		// Add the package.xml files to the zip
		self.add_package("package.xml", self.package.clone())?;
		if !self.pre_destructive.is_empty() {
			self.add_package("destructiveChangesPre.xml", self.pre_destructive.clone())?;
		}
		if !self.post_destructive.is_empty() {
			self.add_package("destructiveChangesPost.xml", self.post_destructive.clone())?;
		}

		Ok(self
			.writer
			.finish()
			.map_err(|e| Error::CompressionError(e.to_string()))?
			.into_inner())
	}
}