@@ -303,22 +303,63 @@ std::string Project::GetToolset()
303303//
304304// Adds files to the project.
305305//
306- void Project::AddFiles (std::initializer_list<std::string > fileList)
306+ void Project::AddFiles (std::initializer_list<std::wstring > fileList)
307307{
308- wstring projDir = GetSaveDirectory ();
309- path pprojDir (projDir);
310- error_code ec;
308+ for (wstring f : fileList)
309+ AddFile (f.c_str ());
310+ }
311+
312+ void Project::AddFile (const wchar_t * file)
313+ {
314+ wstring projectDir = GetSaveDirectory ();
315+ path pathFile (file);
316+ if ( !pathFile.is_absolute () )
317+ pathFile = path (projectDir).append (file);
318+
319+ pathFile = weakly_canonical (pathFile);
320+ wstring relativePath = relative (pathFile, projectDir);
321+
322+ auto it = find_if (files.begin (), files.end (), [relativePath](ProjectFile& f) { return f.relativePath == relativePath; } );
323+ if ( it != files.end () )
324+ return ;
325+
326+ xml_node proj = project ();
327+ xml_node markInsert = markForPropertyGroup;
328+ wstring name;
329+
330+ while ( (name = markInsert.next_sibling ().name ()) == L" Import" || name == L" PropertyGroup" || name == L" PropertyGroup" || name == L" ItemDefinitionGroup" )
331+ markInsert = markInsert.next_sibling ();
332+
333+ ItemType newType = ProjectFile::GetFromPath (relativePath.c_str ());
334+ xml_node itemGroup;
311335
312- for ( auto f : fileList )
336+ for (xml_node next = markInsert. next_sibling () ; (name = next. name () ) == L" ItemGroup " ; )
313337 {
314- path fp (f);
315- if (!fp.is_absolute ())
316- fp = path (projDir).append (f);
338+ ItemType type;
317339
318- fp = canonical (fp);
340+ if ( StringToEnum ( as_utf8 (next.first_child ().name ()).c_str () , type))
341+ {
342+ if (newType > type)
343+ {
344+ markInsert = next; next = next.next_sibling ();
345+ continue ;
346+ }
319347
320- wstring relativePath = relative (fp, pprojDir);
348+ if (type == newType)
349+ itemGroup = next;
350+ }
351+
352+ break ;
321353 }
354+
355+ if (itemGroup.empty ())
356+ itemGroup = proj.insert_child_after (L" ItemGroup" , markInsert);
357+
358+ ProjectFile p;
359+ p.relativePath = relativePath;
360+ p.node = itemGroup.append_child (as_wide (EnumToString (newType)).c_str ());
361+ p.node .append_attribute (L" Include" ).set_value (relativePath.c_str ());
362+ files.push_back (p);
322363}
323364
324365
@@ -398,9 +439,9 @@ pugi::xml_node Project::project()
398439 // Specify utf-8 encoding.
399440 pugi::xml_node decl;
400441
401- for (auto n : children ())
402- if (n .type () == pugi::node_declaration)
403- decl = n ;
442+ for (auto markInsert : children ())
443+ if (markInsert .type () == pugi::node_declaration)
444+ decl = markInsert ;
404445
405446 // Xml declaration
406447 if (decl.empty ())
0 commit comments