forked from microsoft/winget-cli
/
ConfigurationFlow.cpp
1422 lines (1212 loc) · 63.4 KB
/
ConfigurationFlow.cpp
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "ConfigurationFlow.h"
#include "PromptFlow.h"
#include "Public/ConfigurationSetProcessorFactoryRemoting.h"
#include <AppInstallerDownloader.h>
#include <AppInstallerErrors.h>
#include <AppInstallerStrings.h>
#include <winrt/Microsoft.Management.Configuration.h>
#include <winget/SelfManagement.h>
#include "ConfigurationCommon.h"
#include "ConfigurationWingetDscModuleUnitValidation.h"
using namespace AppInstaller::CLI::Execution;
using namespace winrt::Microsoft::Management::Configuration;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::Storage;
using namespace AppInstaller::Utility::literals;
using namespace AppInstaller::SelfManagement;
namespace AppInstaller::CLI::Workflow
{
#ifndef AICLI_DISABLE_TEST_HOOKS
IConfigurationSetProcessorFactory s_override_IConfigurationSetProcessorFactory;
void SetTestConfigurationSetProcessorFactory(IConfigurationSetProcessorFactory factory)
{
s_override_IConfigurationSetProcessorFactory = std::move(factory);
}
#endif
namespace
{
constexpr std::wstring_view s_Directive_Description = L"description";
constexpr std::wstring_view s_Directive_Module = L"module";
constexpr std::wstring_view s_Directive_AllowPrerelease = L"allowPrerelease";
Logging::Level ConvertLevel(DiagnosticLevel level)
{
switch (level)
{
case DiagnosticLevel::Verbose: return Logging::Level::Verbose;
case DiagnosticLevel::Informational: return Logging::Level::Info;
case DiagnosticLevel::Warning: return Logging::Level::Warning;
case DiagnosticLevel::Error: return Logging::Level::Error;
case DiagnosticLevel::Critical: return Logging::Level::Crit;
}
return Logging::Level::Info;
}
DiagnosticLevel ConvertLevel(Logging::Level level)
{
switch (level)
{
case Logging::Level::Verbose: return DiagnosticLevel::Verbose;
case Logging::Level::Info: return DiagnosticLevel::Informational;
case Logging::Level::Warning: return DiagnosticLevel::Warning;
case Logging::Level::Error: return DiagnosticLevel::Error;
case Logging::Level::Crit: return DiagnosticLevel::Critical;
}
return DiagnosticLevel::Informational;
}
Resource::StringId ToResource(ConfigurationUnitIntent intent)
{
switch (intent)
{
case ConfigurationUnitIntent::Assert: return Resource::String::ConfigurationAssert;
case ConfigurationUnitIntent::Inform: return Resource::String::ConfigurationInform;
case ConfigurationUnitIntent::Apply: return Resource::String::ConfigurationApply;
default: return Resource::StringId::Empty();
}
}
IConfigurationSetProcessorFactory CreateConfigurationSetProcessorFactory(Execution::Context& context)
{
#ifndef AICLI_DISABLE_TEST_HOOKS
// Test could override the entire workflow task, but that may require keeping more in sync than simply setting the factory.
if (s_override_IConfigurationSetProcessorFactory)
{
return s_override_IConfigurationSetProcessorFactory;
}
#endif
auto factory = ConfigurationRemoting::CreateOutOfProcessFactory();
Configuration::SetModulePath(context, factory);
return factory;
}
std::optional<Utility::LocIndString> GetValueSetString(const ValueSet& valueSet, std::wstring_view value)
{
if (valueSet.HasKey(value))
{
auto object = valueSet.Lookup(value);
IPropertyValue property = object.try_as<IPropertyValue>();
if (property && property.Type() == PropertyType::String)
{
return Utility::LocIndString{ Utility::ConvertToUTF8(property.GetString()) };
}
}
return {};
}
std::optional<bool> GetValueSetBool(const ValueSet& valueSet, std::wstring_view value)
{
if (valueSet.HasKey(value))
{
auto object = valueSet.Lookup(value);
IPropertyValue property = object.try_as<IPropertyValue>();
if (property && property.Type() == PropertyType::Boolean)
{
return property.GetBoolean();
}
}
return {};
}
void OutputPropertyValue(OutputStream& out, const IPropertyValue property)
{
switch (property.Type())
{
case PropertyType::String:
out << ' ' << Utility::ConvertToUTF8(property.GetString()) << '\n';
break;
case PropertyType::Boolean:
out << ' ' << (property.GetBoolean() ? Utility::LocIndView("true") : Utility::LocIndView("false")) << '\n';
break;
case PropertyType::Int64:
out << ' ' << property.GetInt64() << '\n';
break;
default:
out << " [Debug:PropertyType="_liv << property.Type() << "]\n"_liv;
break;
}
}
void OutputValueSet(OutputStream& out, const ValueSet& valueSet, size_t indent);
void OutputValueSetAsArray(OutputStream& out, const ValueSet& valueSetArray, size_t indent)
{
Utility::LocIndString indentString{ std::string(indent, ' ') };
std::vector<std::pair<int, winrt::Windows::Foundation::IInspectable>> arrayValues;
for (const auto& arrayValue : valueSetArray)
{
if (arrayValue.Key() != L"treatAsArray")
{
arrayValues.emplace_back(std::make_pair(std::stoi(arrayValue.Key().c_str()), arrayValue.Value()));
}
}
std::sort(
arrayValues.begin(),
arrayValues.end(),
[](const std::pair<int, winrt::Windows::Foundation::IInspectable>& a, const std::pair<int, winrt::Windows::Foundation::IInspectable>& b)
{
return a.first < b.first;
});
for (const auto& arrayValue : arrayValues)
{
auto arrayObject = arrayValue.second;
IPropertyValue arrayProperty = arrayObject.try_as<IPropertyValue>();
out << indentString << "-";
if (arrayProperty)
{
OutputPropertyValue(out, arrayProperty);
}
else
{
ValueSet arraySubset = arrayObject.as<ValueSet>();
auto size = arraySubset.Size();
if (size > 0)
{
// First one is special.
auto first = arraySubset.First().Current();
out << ' ' << Utility::ConvertToUTF8(first.Key()) << ':';
auto object = first.Value();
IPropertyValue property = object.try_as<IPropertyValue>();
if (property)
{
OutputPropertyValue(out, property);
}
else
{
// If not an IPropertyValue, it must be a ValueSet
ValueSet subset = object.as<ValueSet>();
out << '\n';
OutputValueSet(out, subset, indent + 4);
}
if (size > 1)
{
arraySubset.Remove(first.Key());
OutputValueSet(out, arraySubset, indent + 2);
arraySubset.Insert(first.Key(), first.Value());
}
}
}
}
}
void OutputValueSet(OutputStream& out, const ValueSet& valueSet, size_t indent)
{
Utility::LocIndString indentString{ std::string(indent, ' ') };
for (const auto& value : valueSet)
{
out << indentString << Utility::ConvertToUTF8(value.Key()) << ':';
auto object = value.Value();
IPropertyValue property = object.try_as<IPropertyValue>();
if (property)
{
OutputPropertyValue(out, property);
}
else
{
// If not an IPropertyValue, it must be a ValueSet
ValueSet subset = object.as<ValueSet>();
out << '\n';
if (subset.HasKey(L"treatAsArray"))
{
OutputValueSetAsArray(out, subset, indent + 2);
}
else
{
OutputValueSet(out, subset, indent + 2);
}
}
}
}
// Converts a string from the configuration API surface for output.
// All strings coming from the API are external data and not localizable by us.
Utility::LocIndString ConvertForOutput(const winrt::hstring& input)
{
return Utility::LocIndString{ Utility::ConvertToUTF8(input) };
}
void OutputConfigurationUnitHeader(OutputStream& out, const ConfigurationUnit& unit, const winrt::hstring& name)
{
out << ConfigurationIntentEmphasis << ToResource(unit.Intent()) << " :: "_liv << ConfigurationUnitEmphasis << ConvertForOutput(name);
winrt::hstring identifier = unit.Identifier();
if (!identifier.empty())
{
out << " ["_liv << ConvertForOutput(identifier) << ']';
}
out << '\n';
}
void OutputConfigurationUnitInformation(OutputStream& out, const ConfigurationUnit& unit)
{
IConfigurationUnitProcessorDetails details = unit.Details();
ValueSet metadata = unit.Metadata();
if (details)
{
// -- Sample output when IConfigurationUnitProcessorDetails present --
// Intent :: UnitType <from details> [Identifier]
// UnitDocumentationUri <if present>
// Description <from details first, directives second>
// "Module": ModuleName "by" Author / Publisher (IsLocal / ModuleSource)
// "Signed by": SigningCertificateChain (leaf subject CN)
// PublishedModuleUri / ModuleDocumentationUri <if present>
// ModuleDescription
OutputConfigurationUnitHeader(out, unit, details.UnitType());
auto unitDocumentationUri = details.UnitDocumentationUri();
if (unitDocumentationUri)
{
out << " "_liv << ConvertForOutput(unitDocumentationUri.DisplayUri()) << '\n';
}
winrt::hstring unitDescriptionFromDetails = details.UnitDescription();
if (!unitDescriptionFromDetails.empty())
{
out << " "_liv << ConvertForOutput(unitDescriptionFromDetails) << '\n';
}
else
{
auto unitDescriptionFromDirectives = GetValueSetString(metadata, s_Directive_Description);
if (unitDescriptionFromDirectives && !unitDescriptionFromDirectives.value().empty())
{
out << " "_liv << unitDescriptionFromDirectives.value() << '\n';
}
}
auto author = ConvertForOutput(details.Author());
if (author.empty())
{
author = ConvertForOutput(details.Publisher());
}
if (details.IsLocal())
{
out << " "_liv << Resource::String::ConfigurationModuleWithDetails(ConvertForOutput(details.ModuleName()), author, Resource::String::ConfigurationLocal) << '\n';
}
else
{
out << " "_liv << Resource::String::ConfigurationModuleWithDetails(ConvertForOutput(details.ModuleName()), author, ConvertForOutput(details.ModuleSource())) << '\n';
}
// TODO: Currently the signature information is only for the top files. Maybe each item should be tagged?
// TODO: Output signing information with additional details (like whether the certificate is trusted). Doing this with the validate command
// seems like a good time, as that will also need to do the check in order to inform the user on the validation.
// Just saying "Signed By: Foo" is going to lead to a false sense of trust if the signature is valid but not actually trusted.
auto moduleUri = details.PublishedModuleUri();
if (!moduleUri)
{
moduleUri = details.ModuleDocumentationUri();
}
if (moduleUri)
{
out << " "_liv << ConvertForOutput(moduleUri.DisplayUri()) << '\n';
}
winrt::hstring moduleDescription = details.ModuleDescription();
if (!moduleDescription.empty())
{
out << " "_liv << ConvertForOutput(moduleDescription) << '\n';
}
}
else
{
// -- Sample output when no IConfigurationUnitProcessorDetails present --
// Intent :: Type <from unit> [identifier]
// Description (from directives)
// "Module": module <directive>
OutputConfigurationUnitHeader(out, unit, unit.Type());
auto description = GetValueSetString(metadata, s_Directive_Description);
if (description && !description.value().empty())
{
out << " "_liv << description.value() << '\n';
}
auto module = GetValueSetString(metadata, s_Directive_Module);
if (module && !module.value().empty())
{
out << " "_liv << Resource::String::ConfigurationModuleNameOnly(module.value()) << '\n';
}
}
// -- Sample output footer --
// Dependencies: dep1, dep2, ...
// Settings:
// <... settings splat>
auto dependencies = unit.Dependencies();
if (dependencies.Size() > 0)
{
std::ostringstream allDependencies;
for (const winrt::hstring& dependency : dependencies)
{
allDependencies << ' ' << Utility::ConvertToUTF8(dependency);
}
out << " "_liv << Resource::String::ConfigurationDependencies(Utility::LocIndString{ std::move(allDependencies).str() }) << '\n';
}
ValueSet settings = unit.Settings();
if (settings.Size() > 0)
{
out << " "_liv << Resource::String::ConfigurationSettings << '\n';
OutputValueSet(out, settings, 4);
}
}
void LogFailedGetConfigurationUnitDetails(const ConfigurationUnit& unit, const IConfigurationUnitResultInformation& resultInformation)
{
if (FAILED(resultInformation.ResultCode()))
{
AICLI_LOG(Config, Error, << "Failed to get unit details for " << Utility::ConvertToUTF8(unit.Type()) << " : 0x" <<
Logging::SetHRFormat << resultInformation.ResultCode() << '\n' << Utility::ConvertToUTF8(resultInformation.Description()) << '\n' <<
Utility::ConvertToUTF8(resultInformation.Details()));
}
}
struct UnitFailedMessageData
{
Utility::LocIndString Message;
bool ShowDescription = true;
};
// TODO: We may need a detailed result code to enable the internal error to be exposed.
// Additionally, some of the processor exceptions that generate these errors should be enlightened to produce better, localized descriptions.
UnitFailedMessageData GetUnitFailedData(const ConfigurationUnit& unit, const IConfigurationUnitResultInformation& resultInformation)
{
int32_t resultCode = resultInformation.ResultCode();
switch (resultCode)
{
case WINGET_CONFIG_ERROR_DUPLICATE_IDENTIFIER: return { Resource::String::ConfigurationUnitHasDuplicateIdentifier(Utility::LocIndString{ Utility::ConvertToUTF8(unit.Identifier()) }), false };
case WINGET_CONFIG_ERROR_MISSING_DEPENDENCY: return { Resource::String::ConfigurationUnitHasMissingDependency(Utility::LocIndString{ Utility::ConvertToUTF8(resultInformation.Details()) }), false };
case WINGET_CONFIG_ERROR_ASSERTION_FAILED: return { Resource::String::ConfigurationUnitAssertHadNegativeResult(), false };
case WINGET_CONFIG_ERROR_UNIT_NOT_INSTALLED: return { Resource::String::ConfigurationUnitNotFoundInModule(), false };
case WINGET_CONFIG_ERROR_UNIT_NOT_FOUND_REPOSITORY: return { Resource::String::ConfigurationUnitNotFound(), false };
case WINGET_CONFIG_ERROR_UNIT_MULTIPLE_MATCHES: return { Resource::String::ConfigurationUnitMultipleMatches(), false };
case WINGET_CONFIG_ERROR_UNIT_INVOKE_GET: return { Resource::String::ConfigurationUnitFailedDuringGet(), true };
case WINGET_CONFIG_ERROR_UNIT_INVOKE_TEST: return { Resource::String::ConfigurationUnitFailedDuringTest(), true };
case WINGET_CONFIG_ERROR_UNIT_INVOKE_SET: return { Resource::String::ConfigurationUnitFailedDuringSet(), true };
case WINGET_CONFIG_ERROR_UNIT_MODULE_CONFLICT: return { Resource::String::ConfigurationUnitModuleConflict(), false };
case WINGET_CONFIG_ERROR_UNIT_IMPORT_MODULE: return { Resource::String::ConfigurationUnitModuleImportFailed(), false };
case WINGET_CONFIG_ERROR_UNIT_INVOKE_INVALID_RESULT: return { Resource::String::ConfigurationUnitReturnedInvalidResult(), false };
case WINGET_CONFIG_ERROR_UNIT_SETTING_CONFIG_ROOT: return { Resource::String::ConfigurationUnitSettingConfigRoot(), false };
case WINGET_CONFIG_ERROR_UNIT_IMPORT_MODULE_ADMIN: return { Resource::String::ConfigurationUnitImportModuleAdmin(), false };
}
switch (resultInformation.ResultSource())
{
case ConfigurationUnitResultSource::ConfigurationSet: return { Resource::String::ConfigurationUnitFailedConfigSet(resultCode), true };
case ConfigurationUnitResultSource::Internal: return { Resource::String::ConfigurationUnitFailedInternal(resultCode), true };
case ConfigurationUnitResultSource::Precondition: return { Resource::String::ConfigurationUnitFailedPrecondition(resultCode), true };
case ConfigurationUnitResultSource::SystemState: return { Resource::String::ConfigurationUnitFailedSystemState(resultCode), true };
case ConfigurationUnitResultSource::UnitProcessing: return { Resource::String::ConfigurationUnitFailedUnitProcessing(resultCode), true };
}
// All other errors use a generic message
return { Resource::String::ConfigurationUnitFailed(resultCode), true };
}
Utility::LocIndString GetUnitSkippedMessage(const IConfigurationUnitResultInformation& resultInformation)
{
int32_t resultCode = resultInformation.ResultCode();
switch (resultInformation.ResultCode())
{
case WINGET_CONFIG_ERROR_MANUALLY_SKIPPED: return Resource::String::ConfigurationUnitManuallySkipped();
case WINGET_CONFIG_ERROR_DEPENDENCY_UNSATISFIED: return Resource::String::ConfigurationUnitNotRunDueToDependency();
case WINGET_CONFIG_ERROR_ASSERTION_FAILED: return Resource::String::ConfigurationUnitNotRunDueToFailedAssert();
}
// If new cases arise and are not handled here, at least have a generic backstop message.
return Resource::String::ConfigurationUnitSkipped(resultCode);
}
void OutputUnitRunFailure(Context& context, const ConfigurationUnit& unit, const IConfigurationUnitResultInformation& resultInformation)
{
std::string description = Utility::Trim(Utility::ConvertToUTF8(resultInformation.Description()));
AICLI_LOG_LARGE_STRING(Config, Error, << "Configuration unit " << Utility::ConvertToUTF8(unit.Type()) << "[" << Utility::ConvertToUTF8(unit.Identifier()) << "] failed with code 0x"
<< Logging::SetHRFormat << resultInformation.ResultCode() << " and error message:\n" << description, Utility::ConvertToUTF8(resultInformation.Details()));
UnitFailedMessageData messageData = GetUnitFailedData(unit, resultInformation);
auto error = context.Reporter.Error();
error << " "_liv << messageData.Message << std::endl;
if (messageData.ShowDescription && !description.empty())
{
constexpr size_t maximumDescriptionLines = 3;
size_t consoleWidth = GetConsoleWidth();
std::vector<std::string> lines = Utility::SplitIntoLines(description, maximumDescriptionLines + 1);
bool wasLimited = Utility::LimitOutputLines(lines, consoleWidth, maximumDescriptionLines);
for (const auto& line : lines)
{
error << line << std::endl;
}
if (wasLimited || !resultInformation.Details().empty())
{
error << Resource::String::ConfigurationDescriptionWasTruncated << std::endl;
}
}
}
// Coordinates an active progress scope and cancellation of the operation.
template<typename OperationT>
struct ProgressCancellationUnification
{
ProgressCancellationUnification(std::unique_ptr<Reporter::AsyncProgressScope>&& progressScope, const OperationT& operation) :
m_progressScope(std::move(progressScope)), m_operation(operation)
{
SetCancellationFunction();
}
void Reset()
{
m_cancelScope.reset();
m_progressScope.reset();
}
Reporter::AsyncProgressScope& Progress() const { return *m_progressScope; }
void Progress(std::unique_ptr<Reporter::AsyncProgressScope>&& progressScope)
{
m_cancelScope.reset();
m_progressScope = std::move(progressScope);
SetCancellationFunction();
}
OperationT& Operation() const { return m_operation; }
private:
void SetCancellationFunction()
{
if (m_progressScope)
{
m_cancelScope = m_progressScope->Callback().SetCancellationFunction([this]() { m_operation.Cancel(); });
}
}
std::unique_ptr<Reporter::AsyncProgressScope> m_progressScope;
OperationT m_operation;
IProgressCallback::CancelFunctionRemoval m_cancelScope;
};
template<typename Operation>
ProgressCancellationUnification<Operation> CreateProgressCancellationUnification(
std::unique_ptr<Reporter::AsyncProgressScope>&& progressScope,
const Operation& operation)
{
return { std::move(progressScope), operation };
}
// The base type for progress reporting
template<typename ResultType, typename ProgressType>
struct ConfigurationSetProgressOutputBase
{
using Operation = IAsyncOperationWithProgress<ResultType, ProgressType>;
ConfigurationSetProgressOutputBase(Context& context, const Operation& operation) :
m_context(context), m_unification({}, operation)
{
operation.Progress([&](const Operation& operation, const ProgressType& data)
{
Progress(operation, data);
});
}
virtual void Progress(const Operation& operation, const ProgressType& data) = 0;
protected:
void MarkCompleted(const ConfigurationUnit& unit)
{
winrt::guid unitInstance = unit.InstanceIdentifier();
m_unitsCompleted.insert(unitInstance);
}
bool UnitHasPreviouslyCompleted(const ConfigurationUnit& unit)
{
winrt::guid unitInstance = unit.InstanceIdentifier();
return m_unitsCompleted.count(unitInstance) != 0;
}
// Sends VT progress to the console
void OutputUnitCompletionProgress()
{
// TODO: Change progress reporting to enable separation of spinner and VT progress reporting
// Preferably we want to be able to have:
// 1. Spinner with indefinite progress VT before set application begins
// 2. 1/N VT progress reporting for configuration units while also showing a spinner for the unit itself
}
void BeginProgress()
{
m_unification.Progress(m_context.Reporter.BeginAsyncProgress(true));
}
void EndProgress()
{
m_unification.Reset();
}
Context& m_context;
private:
ProgressCancellationUnification<Operation> m_unification;
std::set<winrt::guid> m_unitsCompleted;
};
// Helper to handle progress callbacks from ApplyConfigurationSetAsync
struct ApplyConfigurationSetProgressOutput final : public ConfigurationSetProgressOutputBase<ApplyConfigurationSetResult, ConfigurationSetChangeData>
{
using Operation = ConfigurationSetProgressOutputBase<ApplyConfigurationSetResult, ConfigurationSetChangeData>::Operation;
ApplyConfigurationSetProgressOutput(Context& context, const Operation& operation) :
ConfigurationSetProgressOutputBase(context, operation)
{
}
void Progress(const Operation& operation, const ConfigurationSetChangeData& data) override
{
auto threadContext = m_context.SetForCurrentThread();
if (m_isFirstProgress)
{
HandleUnreportedProgress(operation.GetResults());
}
switch (data.Change())
{
case ConfigurationSetChangeEventType::SetStateChanged:
{
switch (data.SetState())
{
case ConfigurationSetState::Pending:
m_context.Reporter.Info() << Resource::String::ConfigurationWaitingOnAnother << std::endl;
BeginProgress();
break;
case ConfigurationSetState::InProgress:
EndProgress();
break;
case ConfigurationSetState::Completed:
EndProgress();
break;
}
}
break;
case ConfigurationSetChangeEventType::UnitStateChanged:
HandleUnitProgress(data.Unit(), data.UnitState(), data.ResultInformation());
break;
}
}
// If no progress has been reported, this function will report the given results
void HandleUnreportedProgress(const ApplyConfigurationSetResult& result)
{
if (m_isFirstProgress)
{
m_isFirstProgress = false;
for (const ApplyConfigurationUnitResult& unitResult : result.UnitResults())
{
HandleUnitProgress(unitResult.Unit(), unitResult.State(), unitResult.ResultInformation());
}
}
}
private:
void HandleUnitProgress(const ConfigurationUnit& unit, ConfigurationUnitState state, const IConfigurationUnitResultInformation& resultInformation)
{
if (UnitHasPreviouslyCompleted(unit))
{
return;
}
switch (state)
{
case ConfigurationUnitState::Pending:
// The unreported progress handler may send pending units, just ignore them
break;
case ConfigurationUnitState::InProgress:
OutputUnitInProgressIfNeeded(unit);
BeginProgress();
break;
case ConfigurationUnitState::Completed:
OutputUnitInProgressIfNeeded(unit);
EndProgress();
if (SUCCEEDED(resultInformation.ResultCode()))
{
m_context.Reporter.Info() << " "_liv << Resource::String::ConfigurationSuccessfullyApplied << std::endl;
}
else
{
OutputUnitRunFailure(m_context, unit, resultInformation);
}
MarkCompleted(unit);
OutputUnitCompletionProgress();
break;
case ConfigurationUnitState::Skipped:
OutputUnitInProgressIfNeeded(unit);
AICLI_LOG(Config, Warning, << "Configuration unit " << Utility::ConvertToUTF8(unit.Type()) << "[" << Utility::ConvertToUTF8(unit.Identifier()) << "] was skipped with code 0x"
<< Logging::SetHRFormat << resultInformation.ResultCode());
m_context.Reporter.Warn() << " "_liv << GetUnitSkippedMessage(resultInformation) << std::endl;
MarkCompleted(unit);
OutputUnitCompletionProgress();
break;
}
}
void OutputUnitInProgressIfNeeded(const ConfigurationUnit& unit)
{
winrt::guid unitInstance = unit.InstanceIdentifier();
if (m_unitsSeen.count(unitInstance) == 0)
{
m_unitsSeen.insert(unitInstance);
OutputStream out = m_context.Reporter.Info();
OutputConfigurationUnitHeader(out, unit, unit.Details() ? unit.Details().UnitType() : unit.Type());
}
}
std::set<winrt::guid> m_unitsSeen;
bool m_isFirstProgress = true;
};
// Helper to handle progress callbacks from TestConfigurationSetAsync
struct TestConfigurationSetProgressOutput final : public ConfigurationSetProgressOutputBase<TestConfigurationSetResult, TestConfigurationUnitResult>
{
using Operation = ConfigurationSetProgressOutputBase<TestConfigurationSetResult, TestConfigurationUnitResult>::Operation;
TestConfigurationSetProgressOutput(Context& context, const Operation& operation) :
ConfigurationSetProgressOutputBase(context, operation)
{
// Start the spinner for the first unit being tested since we only receive completions
BeginProgress();
}
void Progress(const Operation& operation, const TestConfigurationUnitResult& data) override
{
auto threadContext = m_context.SetForCurrentThread();
if (m_isFirstProgress)
{
HandleUnreportedProgress(operation.GetResults());
}
HandleUnitProgress(data.Unit(), data.TestResult(), data.ResultInformation());
}
// If no progress has been reported, this function will report the given results
void HandleUnreportedProgress(const TestConfigurationSetResult& result)
{
if (m_isFirstProgress)
{
m_isFirstProgress = false;
for (const TestConfigurationUnitResult& unitResult : result.UnitResults())
{
HandleUnitProgress(unitResult.Unit(), unitResult.TestResult(), unitResult.ResultInformation());
}
}
}
private:
void HandleUnitProgress(const ConfigurationUnit& unit, ConfigurationTestResult testResult, const IConfigurationUnitResultInformation& resultInformation)
{
if (UnitHasPreviouslyCompleted(unit))
{
return;
}
EndProgress();
{
OutputStream info = m_context.Reporter.Info();
OutputConfigurationUnitHeader(info, unit, unit.Details() ? unit.Details().UnitType() : unit.Type());
}
switch (testResult)
{
case ConfigurationTestResult::Failed:
OutputUnitRunFailure(m_context, unit, resultInformation);
break;
case ConfigurationTestResult::Negative:
m_context.Reporter.Warn() << " "_liv << Resource::String::ConfigurationNotInDesiredState << std::endl;
break;
case ConfigurationTestResult::NotRun:
m_context.Reporter.Warn() << " "_liv << Resource::String::ConfigurationNoTestRun << std::endl;
break;
case ConfigurationTestResult::Positive:
m_context.Reporter.Info() << " "_liv << Resource::String::ConfigurationInDesiredState << std::endl;
break;
default: // ConfigurationTestResult::Unknown
m_context.Reporter.Error() << " "_liv << Resource::String::ConfigurationUnexpectedTestResult(ToIntegral(testResult)) << std::endl;
break;
}
MarkCompleted(unit);
OutputUnitCompletionProgress();
BeginProgress();
}
bool m_isFirstProgress = true;
};
std::string GetNormalizedIdentifier(const winrt::hstring& identifier)
{
return Utility::FoldCase(Utility::NormalizedString{ identifier });
}
// Get unit validation order. Make sure dependency units are before units depending on them.
std::vector<uint32_t> GetConfigurationSetUnitValidationOrder(winrt::Windows::Foundation::Collections::IVectorView<ConfigurationUnit> units)
{
// Create id to index map for easier processing.
std::map<std::string, uint32_t> idToUnitIndex;
for (uint32_t i = 0; i < units.Size(); ++i)
{
auto id = GetNormalizedIdentifier(units.GetAt(i).Identifier());
if (!id.empty())
{
idToUnitIndex.emplace(std::move(id), i);
}
}
// We do not need to worry about duplicate id, missing dependency or loops
// since dependency integrity is already validated in earlier semantic checks.
std::vector<uint32_t> validationOrder;
std::function<void(const ConfigurationUnit&, uint32_t)> addUnitToValidationOrder =
[&](const ConfigurationUnit& unit, uint32_t index)
{
if (std::find(validationOrder.begin(), validationOrder.end(), index) == validationOrder.end())
{
for (auto const& dependencyId : unit.Dependencies())
{
auto dependencyIndex = idToUnitIndex.find(GetNormalizedIdentifier(dependencyId))->second;
addUnitToValidationOrder(units.GetAt(dependencyIndex), dependencyIndex);
}
validationOrder.emplace_back(index);
}
};
for (uint32_t i = 0; i < units.Size(); ++i)
{
addUnitToValidationOrder(units.GetAt(i), i);
}
THROW_HR_IF(E_UNEXPECTED, units.Size() != validationOrder.size());
return validationOrder;
}
}
void CreateConfigurationProcessor(Context& context)
{
auto progressScope = context.Reporter.BeginAsyncProgress(true);
progressScope->Callback().SetProgressMessage(Resource::String::ConfigurationInitializing());
ConfigurationProcessor processor{ CreateConfigurationSetProcessorFactory(context)};
// Set the processor to the current level of the logging.
processor.MinimumLevel(ConvertLevel(Logging::Log().GetLevel()));
processor.Caller(L"winget");
// Use same activity as the overall winget command
processor.ActivityIdentifier(*Logging::Telemetry().GetActivityId());
// Apply winget telemetry setting to configuration
processor.GenerateTelemetryEvents(!Settings::User().Get<Settings::Setting::TelemetryDisable>());
// Route the configuration diagnostics into the context's diagnostics logging
processor.Diagnostics([&context](const winrt::Windows::Foundation::IInspectable&, const IDiagnosticInformation& diagnostics)
{
context.GetThreadGlobals().GetDiagnosticLogger().Write(Logging::Channel::Config, ConvertLevel(diagnostics.Level()), Utility::ConvertToUTF8(diagnostics.Message()));
});
ConfigurationContext configurationContext;
configurationContext.Processor(std::move(processor));
context.Add<Data::ConfigurationContext>(std::move(configurationContext));
}
void OpenConfigurationSet(Context& context)
{
auto progressScope = context.Reporter.BeginAsyncProgress(true);
progressScope->Callback().SetProgressMessage(Resource::String::ConfigurationReadingConfigFile());
std::string argPath{ context.Args.GetArg(Args::Type::ConfigurationFile) };
std::wstring argPathWide = Utility::ConvertToUTF16(argPath);
bool isRemote = Utility::IsUrlRemote(argPath);
std::filesystem::path absolutePath;
Streams::IInputStream inputStream = nullptr;
if (isRemote)
{
std::ostringstream stringStream;
ProgressCallback emptyCallback;
Utility::DownloadToStream(argPath, stringStream, Utility::DownloadType::ConfigurationFile, emptyCallback);
auto strContent = stringStream.str();
std::vector<BYTE> byteContent{ strContent.begin(), strContent.end() };
Streams::InMemoryRandomAccessStream memoryStream;
Streams::DataWriter streamWriter{ memoryStream };
streamWriter.WriteBytes(byteContent);
streamWriter.StoreAsync().get();
streamWriter.DetachStream();
memoryStream.Seek(0);
inputStream = memoryStream;
}
else
{
absolutePath = std::filesystem::weakly_canonical(std::filesystem::path{ argPathWide });
auto openAction = Streams::FileRandomAccessStream::OpenAsync(absolutePath.wstring(), FileAccessMode::Read);
auto cancellationScope = progressScope->Callback().SetCancellationFunction([&]() { openAction.Cancel(); });
inputStream = openAction.get();
}
OpenConfigurationSetResult openResult = nullptr;
{
auto openAction = context.Get<Data::ConfigurationContext>().Processor().OpenConfigurationSetAsync(inputStream);
auto cancellationScope = progressScope->Callback().SetCancellationFunction([&]() { openAction.Cancel(); });
openResult = openAction.get();
}
progressScope.reset();
if (FAILED_LOG(static_cast<HRESULT>(openResult.ResultCode().value)))
{
AICLI_LOG(Config, Error, << "Failed to open configuration set at " << (isRemote ? argPath : absolutePath.u8string()) << " with error 0x" << Logging::SetHRFormat << static_cast<HRESULT>(openResult.ResultCode().value));
switch (openResult.ResultCode())
{
case WINGET_CONFIG_ERROR_INVALID_FIELD_TYPE:
context.Reporter.Error() << Resource::String::ConfigurationFieldInvalidType(Utility::LocIndString{ Utility::ConvertToUTF8(openResult.Field()) }) << std::endl;
break;
case WINGET_CONFIG_ERROR_INVALID_FIELD_VALUE:
context.Reporter.Error() << Resource::String::ConfigurationFieldInvalidValue(Utility::LocIndString{ Utility::ConvertToUTF8(openResult.Field()) }, Utility::LocIndString{ Utility::ConvertToUTF8(openResult.Value()) }) << std::endl;
break;
case WINGET_CONFIG_ERROR_MISSING_FIELD:
context.Reporter.Error() << Resource::String::ConfigurationFieldMissing(Utility::LocIndString{ Utility::ConvertToUTF8(openResult.Field()) }) << std::endl;
break;
case WINGET_CONFIG_ERROR_UNKNOWN_CONFIGURATION_FILE_VERSION:
context.Reporter.Error() << Resource::String::ConfigurationFileVersionUnknown(Utility::LocIndString{ Utility::ConvertToUTF8(openResult.Value()) }) << std::endl;
break;
case WINGET_CONFIG_ERROR_INVALID_CONFIGURATION_FILE:
case WINGET_CONFIG_ERROR_INVALID_YAML:
default:
context.Reporter.Error() << Resource::String::ConfigurationFileInvalidYAML << std::endl;
break;
}
if (openResult.Line() != 0)
{
context.Reporter.Error() << Resource::String::SeeLineAndColumn(openResult.Line(), openResult.Column()) << std::endl;
}
AICLI_TERMINATE_CONTEXT(openResult.ResultCode());
}
ConfigurationSet result = openResult.Set();
// Temporary block on using schema 0.3 while experimental
if (result.SchemaVersion() == L"0.3")
{
AICLI_RETURN_IF_TERMINATED(context << EnsureFeatureEnabled(Settings::ExperimentalFeature::Feature::Configuration03));
}
// Fill out the information about the set based on it coming from a file.
if (isRemote)
{
result.Name(Utility::GetFileNameFromURI(argPath).wstring());
result.Origin(argPathWide);
// Do not set path. This means ${WinGetConfigRoot} not supported in remote configs.
}
else
{
// TODO: Consider how to properly determine a good value for name and origin.
result.Name(absolutePath.filename().wstring());
result.Origin(absolutePath.parent_path().wstring());
result.Path(absolutePath.wstring());
}
context.Get<Data::ConfigurationContext>().Set(result);
}
void ShowConfigurationSet(Context& context)
{
ConfigurationContext& configContext = context.Get<Data::ConfigurationContext>();
if (configContext.Set().Units().Size() == 0)
{
context.Reporter.Warn() << Resource::String::ConfigurationFileEmpty << std::endl;
// This isn't an error termination, but there is no reason to proceed.
AICLI_TERMINATE_CONTEXT(S_FALSE);
}
auto gettingDetailString = Resource::String::ConfigurationGettingDetails();
auto progressScope = context.Reporter.BeginAsyncProgress(true);
progressScope->Callback().SetProgressMessage(gettingDetailString);
auto getDetailsOperation = configContext.Processor().GetSetDetailsAsync(configContext.Set(), ConfigurationUnitDetailFlags::ReadOnly);
auto unification = CreateProgressCancellationUnification(std::move(progressScope), getDetailsOperation);
OutputStream out = context.Reporter.Info();
uint32_t unitsShown = 0;
getDetailsOperation.Progress([&](const IAsyncOperationWithProgress<GetConfigurationSetDetailsResult, GetConfigurationUnitDetailsResult>& operation, const GetConfigurationUnitDetailsResult&)
{
auto threadContext = context.SetForCurrentThread();
unification.Reset();
auto unitResults = operation.GetResults().UnitResults();
for (unitsShown; unitsShown < unitResults.Size(); ++unitsShown)
{
GetConfigurationUnitDetailsResult unitResult = unitResults.GetAt(unitsShown);
LogFailedGetConfigurationUnitDetails(unitResult.Unit(), unitResult.ResultInformation());
OutputConfigurationUnitInformation(out, unitResult.Unit());
}
progressScope = context.Reporter.BeginAsyncProgress(true);
progressScope->Callback().SetProgressMessage(gettingDetailString);
unification.Progress(std::move(progressScope));
});
HRESULT hr = S_OK;
GetConfigurationSetDetailsResult result = nullptr;