33// SPDX-License-Identifier: MIT
44
55use std:: {
6- collections:: BTreeMap ,
6+ collections:: { BTreeMap , BTreeSet } ,
77 fmt,
88 path:: { Path , PathBuf } ,
99} ;
@@ -21,6 +21,7 @@ pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
2121 xc_build_configuration : BTreeMap :: new ( ) ,
2222 xc_configuration_list : BTreeMap :: new ( ) ,
2323 additions : BTreeMap :: new ( ) ,
24+ removed_lines : BTreeSet :: new ( ) ,
2425 has_changes : false ,
2526 } ;
2627
@@ -47,6 +48,7 @@ pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
4748 id. clone ( ) ,
4849 XCBuildConfiguration {
4950 build_settings : Vec :: new ( ) ,
51+ build_settings_end_line_number : None ,
5052 } ,
5153 ) ;
5254 state = State :: XCBuildConfigurationObject { id } ;
@@ -62,14 +64,21 @@ pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
6264 State :: XCBuildConfigurationObjectBuildSettings { id } => {
6365 if let Some ( ( identation, token) ) = split_at_identation ( line) {
6466 if token == "};" {
67+ proj
68+ . xc_build_configuration
69+ . get_mut ( id)
70+ . unwrap ( )
71+ . build_settings_end_line_number = Some ( line_number) ;
6572 state = State :: XCBuildConfigurationObject { id : id. clone ( ) } ;
6673 } else {
6774 let assignment = token. trim_end_matches ( ';' ) ;
6875 if let Some ( ( key, value) ) = assignment. split_once ( " = " ) {
76+ let mut end_line_number = line_number;
6977 // multiline value
7078 let value = if value == "(" {
7179 let mut value = value. to_string ( ) ;
72- for ( _next_line_number, next_line) in iter. by_ref ( ) {
80+ for ( next_line_number, next_line) in iter. by_ref ( ) {
81+ end_line_number = next_line_number;
7382 value. push_str ( next_line) ;
7483 value. push ( '\n' ) ;
7584
@@ -91,7 +100,10 @@ pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
91100 . build_settings
92101 . push ( BuildSettings {
93102 identation : identation. into ( ) ,
94- line_number,
103+ location : BuildSettingLocation :: Existing {
104+ line_number,
105+ end_line_number,
106+ } ,
95107 key : key. trim ( ) . into ( ) ,
96108 value,
97109 } ) ;
@@ -151,6 +163,34 @@ pub fn parse<P: AsRef<Path>>(path: P) -> crate::Result<Pbxproj> {
151163 Ok ( proj)
152164}
153165
166+ /// Quotes a value so it can be used as a string in a pbxproj file.
167+ pub fn quote ( value : & str ) -> String {
168+ format ! ( "\" {}\" " , value. replace( '\\' , "\\ \\ " ) . replace( '"' , "\\ \" " ) )
169+ }
170+
171+ /// Reverts [`quote`], returning the raw value of a (possibly quoted) pbxproj string.
172+ pub fn unquote ( value : & str ) -> String {
173+ let Some ( inner) = value
174+ . strip_prefix ( '"' )
175+ . and_then ( |value| value. strip_suffix ( '"' ) )
176+ else {
177+ return value. to_string ( ) ;
178+ } ;
179+
180+ let mut unquoted = String :: with_capacity ( inner. len ( ) ) ;
181+ let mut chars = inner. chars ( ) ;
182+ while let Some ( c) = chars. next ( ) {
183+ if c == '\\' {
184+ if let Some ( next) = chars. next ( ) {
185+ unquoted. push ( next) ;
186+ }
187+ } else {
188+ unquoted. push ( c) ;
189+ }
190+ }
191+ unquoted
192+ }
193+
154194fn split_at_identation ( s : & str ) -> Option < ( & str , & str ) > {
155195 s. chars ( )
156196 . position ( |c| !c. is_ascii_whitespace ( ) )
@@ -175,8 +215,10 @@ pub struct Pbxproj {
175215 pub xc_build_configuration : BTreeMap < String , XCBuildConfiguration > ,
176216 pub xc_configuration_list : BTreeMap < String , XCConfigurationList > ,
177217
178- // maps the line number to the line to add
179- additions : BTreeMap < usize , String > ,
218+ // maps the line number to the lines to add before it, in order
219+ additions : BTreeMap < usize , Vec < String > > ,
220+ // lines that were replaced by a new value (continuation of multiline values)
221+ removed_lines : BTreeSet < usize > ,
180222
181223 has_changes : bool ,
182224}
@@ -200,9 +242,15 @@ impl Pbxproj {
200242 let last_line_number = self . raw_lines . len ( ) - 1 ;
201243
202244 for ( number, line) in self . raw_lines . iter ( ) . enumerate ( ) {
203- if let Some ( new) = self . additions . get ( & number) {
204- proj. push_str ( new) ;
205- proj. push ( '\n' ) ;
245+ if let Some ( additions) = self . additions . get ( & number) {
246+ for new in additions {
247+ proj. push_str ( new) ;
248+ proj. push ( '\n' ) ;
249+ }
250+ }
251+
252+ if self . removed_lines . contains ( & number) {
253+ continue ;
206254 }
207255
208256 proj. push_str ( line) ;
@@ -230,34 +278,70 @@ impl Pbxproj {
230278 . find ( |s| s. key == key)
231279 {
232280 if build_setting. value != value {
233- let Some ( line) = self . raw_lines . get_mut ( build_setting. line_number ) else {
234- return ;
235- } ;
236-
237- * line = format ! ( "{}{key} = {value};" , build_setting. identation) ;
281+ let new_line = format ! ( "{}{key} = {value};" , build_setting. identation) ;
282+ match build_setting. location {
283+ BuildSettingLocation :: Existing {
284+ line_number,
285+ end_line_number,
286+ } => {
287+ let Some ( line) = self . raw_lines . get_mut ( line_number) else {
288+ return ;
289+ } ;
290+ * line = new_line;
291+ // drop the remaining lines of a multiline value
292+ self . removed_lines . extend ( line_number + 1 ..=end_line_number) ;
293+ }
294+ BuildSettingLocation :: Added { anchor, index } => {
295+ let Some ( line) = self
296+ . additions
297+ . get_mut ( & anchor)
298+ . and_then ( |additions| additions. get_mut ( index) )
299+ else {
300+ return ;
301+ } ;
302+ * line = new_line;
303+ }
304+ }
305+ build_setting. value = value. to_string ( ) ;
238306 self . has_changes = true ;
239307 }
240308 } else {
241- let Some ( last_build_setting) = build_configuration. build_settings . last ( ) . cloned ( ) else {
309+ // new settings are added right before the buildSettings closing brace
310+ let Some ( anchor) = build_configuration. build_settings_end_line_number else {
242311 return ;
243312 } ;
313+ let identation = match build_configuration. build_settings . last ( ) {
314+ Some ( last_build_setting) => last_build_setting. identation . clone ( ) ,
315+ None => {
316+ let closing_brace = self . raw_lines . get ( anchor) . map ( String :: as_str) ;
317+ let closing_identation = closing_brace
318+ . and_then ( split_at_identation)
319+ . map ( |( identation, _) | identation)
320+ . unwrap_or_default ( ) ;
321+ format ! ( "{closing_identation}\t " )
322+ }
323+ } ;
324+
325+ let additions = self . additions . entry ( anchor) . or_default ( ) ;
326+ additions. push ( format ! ( "{identation}{key} = {value};" ) ) ;
244327 build_configuration. build_settings . push ( BuildSettings {
245- identation : last_build_setting. identation . clone ( ) ,
246- line_number : last_build_setting. line_number + 1 ,
328+ identation,
329+ location : BuildSettingLocation :: Added {
330+ anchor,
331+ index : additions. len ( ) - 1 ,
332+ } ,
247333 key : key. to_string ( ) ,
248334 value : value. to_string ( ) ,
249335 } ) ;
250- self . additions . insert (
251- last_build_setting. line_number + 1 ,
252- format ! ( "{}{key} = {value};" , last_build_setting. identation) ,
253- ) ;
254336 }
255337 }
256338}
257339
258340#[ derive( Debug ) ]
259341pub struct XCBuildConfiguration {
260342 build_settings : Vec < BuildSettings > ,
343+ // line number of the buildSettings closing brace
344+ build_settings_end_line_number : Option < usize > ,
261345}
262346
263347impl XCBuildConfiguration {
@@ -269,11 +353,22 @@ impl XCBuildConfiguration {
269353#[ derive( Debug , Clone ) ]
270354pub struct BuildSettings {
271355 identation : String ,
272- line_number : usize ,
356+ location : BuildSettingLocation ,
273357 pub key : String ,
274358 pub value : String ,
275359}
276360
361+ #[ derive( Debug , Clone , Copy ) ]
362+ enum BuildSettingLocation {
363+ /// A setting present in the parsed file, spanning `line_number..=end_line_number`.
364+ Existing {
365+ line_number : usize ,
366+ end_line_number : usize ,
367+ } ,
368+ /// A setting added by [`Pbxproj::set_build_settings`], stored in `additions[anchor][index]`.
369+ Added { anchor : usize , index : usize } ,
370+ }
371+
277372#[ derive( Debug , Clone ) ]
278373pub struct XCConfigurationList {
279374 pub comment : String ,
@@ -324,4 +419,100 @@ mod tests {
324419
325420 insta:: assert_snapshot!( "project-modified.pbxproj" , pbxproj. serialize( ) ) ;
326421 }
422+
423+ const RELEASE : & str = "DB_0E254D0FD84970B57F6410" ;
424+
425+ fn fixture ( ) -> super :: Pbxproj {
426+ let manifest_dir = std:: path:: Path :: new ( env ! ( "CARGO_MANIFEST_DIR" ) ) ;
427+ super :: parse (
428+ manifest_dir
429+ . join ( "tests" )
430+ . join ( "fixtures" )
431+ . join ( "pbxproj" )
432+ . join ( "project.pbxproj" ) ,
433+ )
434+ . expect ( "failed to parse pbxproj" )
435+ }
436+
437+ /// Returns the trimmed lines of the buildSettings dictionary of the given build configuration.
438+ fn build_settings_lines ( serialized : & str , build_configuration_id : & str ) -> Vec < String > {
439+ serialized
440+ . lines ( )
441+ . skip_while ( |l| !l. trim_start ( ) . starts_with ( build_configuration_id) )
442+ . skip_while ( |l| !l. contains ( "buildSettings = {" ) )
443+ . skip ( 1 )
444+ . take_while ( |l| l. trim ( ) != "};" )
445+ . map ( |l| l. trim ( ) . to_string ( ) )
446+ . collect ( )
447+ }
448+
449+ #[ test]
450+ fn add_multiple_settings ( ) {
451+ let mut pbxproj = fixture ( ) ;
452+ pbxproj. set_build_settings ( RELEASE , "NEW_A" , "a" ) ;
453+ pbxproj. set_build_settings ( RELEASE , "NEW_B" , "b" ) ;
454+ pbxproj. set_build_settings ( RELEASE , "NEW_C" , "c" ) ;
455+
456+ let serialized = pbxproj. serialize ( ) ;
457+ let lines = build_settings_lines ( & serialized, RELEASE ) ;
458+ assert_eq ! (
459+ & lines[ lines. len( ) - 4 ..] ,
460+ [
461+ "VALID_ARCHS = \" arm64\" ;" ,
462+ "NEW_A = a;" ,
463+ "NEW_B = b;" ,
464+ "NEW_C = c;"
465+ ]
466+ ) ;
467+ // the new settings stay inside the buildSettings dictionary
468+ assert ! ( serialized. contains( "\t \t \t \t NEW_C = c;\n \t \t \t };\n \t \t \t name = release;\n \t \t };" ) ) ;
469+ }
470+
471+ #[ test]
472+ fn update_added_setting ( ) {
473+ let mut pbxproj = fixture ( ) ;
474+ pbxproj. set_build_settings ( RELEASE , "NEW_A" , "a" ) ;
475+ pbxproj. set_build_settings ( RELEASE , "NEW_B" , "b" ) ;
476+ pbxproj. set_build_settings ( RELEASE , "NEW_A" , "a2" ) ;
477+
478+ let serialized = pbxproj. serialize ( ) ;
479+ let lines = build_settings_lines ( & serialized, RELEASE ) ;
480+ assert_eq ! ( & lines[ lines. len( ) - 2 ..] , [ "NEW_A = a2;" , "NEW_B = b;" ] ) ;
481+ assert ! ( serialized. contains( "\t \t \t \t NEW_B = b;\n \t \t \t };\n \t \t \t name = release;\n \t \t };" ) ) ;
482+ assert_eq ! (
483+ serialized. lines( ) . count( ) ,
484+ fixture( ) . serialize( ) . lines( ) . count( ) + 2
485+ ) ;
486+ }
487+
488+ #[ test]
489+ fn update_multiline_setting ( ) {
490+ let mut pbxproj = fixture ( ) ;
491+ pbxproj. set_build_settings ( RELEASE , "ARCHS" , "arm64" ) ;
492+
493+ let serialized = pbxproj. serialize ( ) ;
494+ let lines = build_settings_lines ( & serialized, RELEASE ) ;
495+ assert_eq ! ( lines[ 1 ] , "ARCHS = arm64;" ) ;
496+ assert_eq ! ( lines[ 2 ] , "ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;" ) ;
497+ assert_eq ! (
498+ serialized. lines( ) . count( ) ,
499+ fixture( ) . serialize( ) . lines( ) . count( ) - 2
500+ ) ;
501+ }
502+
503+ #[ test]
504+ fn quote ( ) {
505+ let product_name = r#"My "App" \ Name"# ;
506+ let quoted = super :: quote ( product_name) ;
507+ assert_eq ! ( quoted, r#""My \"App\" \\ Name""# ) ;
508+ assert_eq ! ( super :: unquote( & quoted) , product_name) ;
509+
510+ let mut pbxproj = fixture ( ) ;
511+ pbxproj. set_build_settings ( RELEASE , "PRODUCT_NAME" , & quoted) ;
512+ assert ! (
513+ pbxproj
514+ . serialize( )
515+ . contains( r#"PRODUCT_NAME = "My \"App\" \\ Name";"# )
516+ ) ;
517+ }
327518}
0 commit comments