Exemplo n.º 1
0
        /// <summary>
        /// Dumps the <see cref="Solutions"/> order by their index along with optional details.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="current">The current solution (a star will precede its name).</param>
        /// <param name="solutionLineDetail">Optional details to be appended on the information, header, line.</param>
        /// <param name="solutionDetail">
        /// Optional detailed log generator.
        /// When not null, a group is opened by solution and this is called.
        /// </param>
        public void LogSolutions(
            IActivityMonitor m,
            DependentSolution current = null,
            Func <DependentSolution, string> solutionLineDetail         = null,
            Action <IActivityMonitor, DependentSolution> solutionDetail = null)
        {
            int rank = -1;

            foreach (var s in Solutions)
            {
                if (rank != s.Rank)
                {
                    rank = s.Rank;
                    m.Info($" -- Rank {rank}");
                }
                if (solutionDetail != null)
                {
                    using (m.OpenInfo($"{(s == current ? '*' : ' ')}   {s.Index} - {s} {solutionLineDetail?.Invoke( s )}"))
                    {
                        solutionDetail(m, s);
                    }
                }
                else
                {
                    m.Info($"{(s == current ? '*' : ' ')}   {s.Index} - {s} {solutionLineDetail?.Invoke( s )}");
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Method to call to set the credentials of nuget.
        /// </summary>
        /// <param name="m"></param>
        /// <param name="url"></param>
        /// <param name="secret"></param>
        internal static void EnsureVSSFeedEndPointCredentials(IActivityMonitor m, string url, string secret)
        {
            lock ( _secretKeysLock )
            {
                bool newRepo        = !_secretAzureKeys.ContainsKey(url);
                bool updateExisitng = !newRepo && _secretAzureKeys[url] != secret;

                if (newRepo || updateExisitng)
                {
                    if (newRepo)
                    {
                        m.Info($"Registering credential for '{url}' access.");
                        _secretAzureKeys.Add(url, secret);
                    }
                    else
                    {
                        m.Info($"Updating credential for '{url}' access.");
                        _secretAzureKeys[url] = secret;
                    }
                    GenerateNuGetCredentialsEnvironmentVariable(m);
                    // Clears the credential service.
                    HttpHandlerResourceV3.CredentialService = null;
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns true it the definition has been added or updated.
        /// False if nothing changed.
        /// </summary>
        bool FindOrCreateStackDef(
            IActivityMonitor m,
            string stackName,
            string url,
            bool isPublic,
            string branchName)
        {
            var def = new StackDef(SecretKeyStore, stackName, new Uri(url), isPublic, branchName);
            int idx = _stacks.IndexOf(d => d.StackName.Equals(stackName, StringComparison.OrdinalIgnoreCase));

            if (idx >= 0)
            {
                if (_stacks[idx].ToString() == def.ToString())
                {
                    return(false);
                }
                m.Info($"Replaced existing Stack: '{_stacks[idx]}' with '{def}'.");
                _stacks[idx] = def;
            }
            else
            {
                m.Info($"Added Stack: '{def}'.");
                _stacks.Add(def);
            }
            return(true);
        }
        public void Run()
        {
            _monitor.Info().Send("ThreadContext{0}Begin", NumMonitor);
            foreach (var bc in _monitor.Output.Clients.OfType <BuggyClient>())
            {
                bc.RunThreadId = Thread.CurrentThread.ManagedThreadId;
            }
            for (int i = 0; i < OperationCount; ++i)
            {
                double op = Rand.NextDouble();
                if (op < 1.0 / 60)
                {
                    _monitor.MinimalFilter = _monitor.MinimalFilter == LogFilter.Debug ? LogFilter.Verbose : LogFilter.Debug;
                }

                if (op < 1.0 / 3)
                {
                    _monitor.Info().Send("OP-{0}-{1}", NumMonitor, i);
                }
                else if (op < 2.0 / 3)
                {
                    _monitor.OpenInfo().Send("G-OP-{0}-{1}", NumMonitor, i);
                }
                else
                {
                    _monitor.CloseGroup();
                }
            }
            _monitor.Info().Send("ThreadContext{0}End", NumMonitor);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Deletes a file or folder. It must be physically accessible
        /// (<see cref="IFileInfo.PhysicalPath"/> must not be null): if inside a <see cref="GitFolder"/>, it must
        /// be a in the current head (ie. corresponds to a file in the current working directory).
        /// </summary>
        /// <param name="m">The monitor.</param>
        /// <param name="subPath">The item path to delete.</param>
        /// <returns>True on success, false on error (error is logged into the monitor).</returns>
        public bool Delete(IActivityMonitor m, NormalizedPath subPath)
        {
            IFileInfo info = GetFileInfo(subPath);

            if (info.Exists)
            {
                if (info.PhysicalPath == null)
                {
                    m.Error($"'{subPath}' to delete is not physically available.");
                    return(false);
                }
                try
                {
                    if (info.IsDirectory)
                    {
                        m.Info($"Deleting folder '{subPath}'.");
                        FileHelper.RawDeleteLocalDirectory(m, info.PhysicalPath);
                    }
                    else
                    {
                        m.Info($"Deleting file '{subPath}'.");
                        File.Delete(info.PhysicalPath);
                    }
                }
                catch (Exception ex)
                {
                    m.Fatal(ex);
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 6
0
 public Task StartAsync(CancellationToken stoppingToken)
 {
     // This monitor is tied to this service. It is solicited from (and only from)
     // the OnTime method that prevents reentrancy: only one thread enters the monitor at a time.
     _monitor.Info("LoggerTestHostedService started.");
     _timer = new Timer(OnTime, null, TimeSpan.Zero, _options.CurrentValue.TimerDuration);
     return(Task.CompletedTask);
 }
        /// <summary>
        /// Low level helper that initializes a new <see cref="StObjEngineConfiguration"/> and computes the force setup flag
        /// that can be used by other helpers that need to run a setup.
        /// </summary>
        /// <param name="helper">The <see cref="IStObjSetupTestHelper"/> helper.</param>
        /// <returns>The configuration and the flag.</returns>
        static public (StObjEngineConfiguration Configuration, ForceSetupLevel ForceSetup) CreateDefaultConfiguration(IActivityMonitor monitor,
                                                                                                                      IStObjSetupTestHelper helper)
        {
            var stObjConf = new StObjEngineConfiguration
            {
                RevertOrderingNames         = helper.StObjRevertOrderingNames,
                TraceDependencySorterInput  = helper.StObjTraceGraphOrdering,
                TraceDependencySorterOutput = helper.StObjTraceGraphOrdering,
            };
            // BinPath by default is: the first "CKSetup/DefaultBinPaths" if it has been configured
            // otherwise it is the {ClosestSUTProjectFolder}/{PathToBin} (if no ClosestSUTProjectFolder
            // has been found, {ClosestSUTProjectFolder} is the {TestProjectFolder} so {ClosestSUTProjectFolder}/{PathToBin}
            // is... this {BinFolder})
            NormalizedPath binPath;

            if (helper.CKSetup.DefaultBinPaths.Count > 0)
            {
                binPath = helper.CKSetup.DefaultBinPaths[0];
                monitor.Info($"Using first configured 'CKSetup/DefaultBinPaths' = {binPath}");
            }
            else
            {
                binPath = helper.ClosestSUTProjectFolder.Combine(helper.PathToBin);
                monitor.Info($"No 'CKSetup/DefaultBinPaths' configuration. Using ClosestSUTProjectFolder/PathToBin: {binPath}.");
            }

            var b = new BinPathConfiguration
            {
                // The name of the BinPath to use is the current IStObjMapTestHelper.BinPathName.
                Name = helper.BinPathName,
                Path = binPath,
                // Then the OutputPath will copy the generated assembly to this bin folder.
                OutputPath    = helper.BinFolder,
                CompileOption = CompileOption.Compile,
                // ...and the G0.cs to the TestProjectFolder.
                GenerateSourceFiles = helper.StObjGenerateSourceFiles,
                ProjectPath         = helper.TestProjectFolder
            };

            stObjConf.BinPaths.Add(b);

            // Consider by default the CKSetup configuration that be not None,
            // but if it is None, set it to Engine: the engine must run even if
            // all the binaries are unchanged to check the G0.cs and assembly.

            var f = helper.CKSetup.ForceSetup;

            if (f == ForceSetupLevel.None)
            {
                monitor.Trace($"Setting CKSetup ForceSetupLevel to Engine so it can check the required artifacts.");
                f = ForceSetupLevel.Engine;
            }
            return(stObjConf, f);
        }
Exemplo n.º 8
0
 void StObjConstruct(IActivityMonitor m)
 {
     Assert.That(ConstructCount, Is.EqualTo(0), "First StObjConstruct.");
     SimpleObjectsTrace.LogMethod(GetType().GetMethod("StObjConstruct", BindingFlags.Instance | BindingFlags.NonPublic));
     ConstructCount = ConstructCount + 1;
     m.Info($"This is the setup logger.");
 }
Exemplo n.º 9
0
            public virtual string SaySomething(IActivityMonitor monitor, string messageFormat = "Hello {0}!")
            {
                var msg = string.Format(messageFormat, "World");

                monitor.Info(msg);
                return(msg);
            }
        /// <summary>
        /// Allows a direct login if and only if:
        ///     * Scheme is "Guest"
        ///     * The payload is valid
        ///     * The payload's token is neither null or whitespaces
        /// </summary>
        /// <param name="ctx">The current context.</param>
        /// <param name="monitor">The monitor to use.</param>
        /// <param name="scheme">The authentication scheme.</param>
        /// <param name="payload">The login payload.</param>
        /// <returns></returns>
        public Task <bool> AllowAsync(HttpContext ctx, IActivityMonitor monitor, string scheme, object payload)
        {
            using (monitor.OpenInfo($"{GetType()}.AllowAsync challenge"))
            {
                if (scheme != "Guest")
                {
                    monitor.Trace("Invalid scheme");
                    return(Task.FromResult(false));
                }
                monitor.Trace("Valid scheme");

                IGuestActorInfo info;
                try
                {
                    info = _infoFactory.ExtractPayload(payload);
                }
                catch (Exception exception)
                {
                    monitor.Error("Error while extracting payload.", exception);
                    return(Task.FromResult(false));
                }

                Debug.Assert(info != null);

                if (string.IsNullOrWhiteSpace(info.Token))
                {
                    monitor.Trace("Invalid payload");
                    return(Task.FromResult(false));
                }
                monitor.Trace("Valid payload");

                monitor.Info("DirectLogin allowed.");
                return(Task.FromResult(true));
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Reads the Stacks.xml file and instanciates the <see cref="StackRepo"/> objects and
 /// their <see cref="WorldInfo"/>: creating the StackRepo registers the required secrets
 /// in the key store.
 /// </summary>
 /// <param name="m">The monitor to use.</param>
 internal void ReadStacksFromLocalStacksFilePath(IActivityMonitor m)
 {
     if (!File.Exists(StacksFilePath))
     {
         m.Warn($"File '{StacksFilePath}' not found.");
     }
     else
     {
         using (m.OpenInfo($"Reading '{StacksFilePath}'."))
         {
             try
             {
                 _stackRepos.Clear();
                 _stackRepos.AddRange(XDocument.Load(StacksFilePath).Root.Elements().Select(e => StackRepo.Parse(this, e)));
             }
             catch (Exception ex)
             {
                 m.Error($"Unable to read '{StacksFilePath}' file.", ex);
             }
         }
     }
     if (_stackRepos.Count == 0)
     {
         using (m.OpenInfo("Since there is no Stack defined, we initialize CK and CK-Build mapped to '/Dev/CK' by default."))
         {
             m.Info($"Use 'run World/{nameof( SetWorldMapping )}' command to update the mapping.");
             _stackRepos.Add(new StackRepo(this, new Uri("https://github.com/signature-opensource/CK-Stack.git"), true));
             _stackRepos.Add(new StackRepo(this, new Uri("https://github.com/CK-Build/CK-Build-Stack.git"), true));
             WorldLocalMapping.SetMap(m, "CK-Build", "/Dev/CK");
             WorldLocalMapping.SetMap(m, "CK", "/Dev/CK");
             WriteStacksToLocalStacksFilePath(m);
         }
     }
 }
Exemplo n.º 12
0
        /// <summary>
        /// Registers a new <see cref="StackRepo"/> or updates its <see cref="GitRepositoryKey.IsPublic"/> configuration.
        /// This is exposed as a command by <see cref="UserHost.EnsureStackRepository"/> in order for Stack repository manipulations
        /// (that are NOT world: it's meta) to appear in "Home/" command namespace instead of "World/".
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="url">The repository url. Must not be numm or empty.</param>
        /// <param name="isPublic">Whether this repository contains public (Open Source) worlds.</param>
        public void EnsureStackRepository(IActivityMonitor m, string url, bool isPublic)
        {
            if (DisableRepositoryAndStacksCommands)
            {
                throw new InvalidOperationException(nameof(DisableRepositoryAndStacksCommands));
            }
            if (String.IsNullOrWhiteSpace(url) || !Uri.TryCreate(url, UriKind.Absolute, out var uri))
            {
                throw new ArgumentException("Must be a valid url.", nameof(url));
            }
            int idx = _stackRepos.IndexOf(r => r.OriginUrl.ToString().Equals(url, StringComparison.OrdinalIgnoreCase));

            if (idx < 0)
            {
                var r = new StackRepo(this, uri, isPublic);
                _stackRepos.Add(r);
                if (r.Refresh(m))
                {
                    WriteStacksToLocalStacksFilePath(m);
                }
            }
            else
            {
                var r = _stackRepos[idx];
                if (r.IsPublic != isPublic)
                {
                    r.IsPublic = isPublic;
                    m.Info($"Changing configuration for '{r.OriginUrl}' from {(isPublic ? "Private to Public" : "Public to Private")}.");
                    WriteStacksToLocalStacksFilePath(m);
                }
            }
        }
            void RegisterStartupServices(IActivityMonitor m, SimpleServiceContainer startupServices)
            {
                m.Info($"Registering the Super Startup service.");
                bool willFail = startupServices.GetRequiredService <TotallyExternalStartupServiceThatActAsAConfiguratorOfTheWholeSystem>().EmitErrorLogSoThatConfigureServicesFails;

                startupServices.Add(new SuperStartupService(willFail));
            }
Exemplo n.º 14
0
        /// <summary>
        /// Creates a ZeroBuilder.
        /// </summary>
        /// <param name="m">The monitor to use.</param>
        /// <param name="feeds">The local feeds.</param>
        /// <param name="depContext">The dependency context to consider.</param>
        /// <param name="driverFinder">The driver finder by solution name.</param>
        /// <param name="solutionReloader">Optional solutions reloader.</param>
        /// <returns>The ZeroBuilder on success, null on error.</returns>
        static ZeroBuilder Create(
            IActivityMonitor m,
            IEnvLocalFeedProvider feeds,
            IWorldSolutionContext context)
        {
            if (context.DependencyContext.BuildProjectsInfo.HasError)
            {
                using (m.OpenError("Build Projects dependencies failed to be computed."))
                {
                    context.DependencyContext.BuildProjectsInfo.RawBuildProjectsInfoSorterResult.LogError(m);
                }
                return(null);
            }
            var zeroProjects = context.DependencyContext.BuildProjectsInfo.ZeroBuildProjects;

            if (zeroProjects.Count == 0)
            {
                m.Error(context.DependencyContext.HasError ? "Invalid dependency analysis." : "No Build Project exist.");
                return(null);
            }
            var mustBuild = new HashSet <string>(zeroProjects.Select(p => p.Project.FullFolderPath.Path));
            var memPath   = feeds.ZeroBuild.PhysicalPath.AppendPart("CacheZeroVersion.txt");
            var sha1Cache = System.IO.File.Exists(memPath)
                            ? System.IO.File.ReadAllLines(memPath)
                            .Select(l => l.Split())
                            .Where(l => mustBuild.Contains(l[0]))
                            .ToDictionary(l => l[0], l => new HashSet <string>(l[1].Split('|')))
                            : new Dictionary <string, HashSet <string> >();

            m.Info($"File '{memPath}' contains {sha1Cache.Count} entries.");
            var currentShas = new string[zeroProjects.Count];

            return(new ZeroBuilder(feeds, memPath, sha1Cache, mustBuild, context));
        }
 CSCodeGenerationResult DoImplement(IActivityMonitor monitor, Type classType, ICSCodeGenerationContext c, ITypeScope scope, ISourceCodeHelper helper)
 {
     c.Should().NotBeNull();
     scope.Should().NotBeNull();
     monitor.Info($"AutoImpl2: {helper.IHelpTheCodeGeneration()}.");
     return(new CSCodeGenerationResult(nameof(FinalizeImpl)));
 }
Exemplo n.º 16
0
 internal static StObjMapInfo?Create(IActivityMonitor m, Assembly a, CustomAttributeData attr)
 {
     try
     {
         object?v = attr.AttributeType.GetField("V", BindingFlags.Public | BindingFlags.Static)?.GetValue(null);
         if (v == null)
         {
             m.Error($"Unable to retrieve the CK.StObj.Signature assembly attribute from '{a.FullName}'.");
         }
         else
         {
             (SHA1Value, IReadOnlyList <string>)s = ((SHA1Value, IReadOnlyList <string>))v;
             Type?t = a.GetType(StObjContextRoot.RootContextTypeFullName, false, false);
             if (t == null)
             {
                 m.Error($"Unable to retrieve the generated {StObjContextRoot.RootContextTypeFullName} type from '{a.FullName}'.");
             }
             else
             {
                 var r = new StObjMapInfo(s.Item1, s.Item2, t);
                 m.Info($"Found StObjMap: {r}.");
                 return(r);
             }
         }
     }
     catch (Exception ex)
     {
         m.Error("Unable to read StObjMap information.", ex);
     }
     return(null);
 }
Exemplo n.º 17
0
        /// <summary>
        /// Helper that copies a file with retries.
        /// </summary>
        /// <param name="monitor">The monitor to use.</param>
        /// <param name="source">The source file path.</param>
        /// <param name="target">The target file path.</param>
        /// <returns>True on success, false on error.</returns>
        public static bool SafeCopy(IActivityMonitor monitor, NormalizedPath source, NormalizedPath target)
        {
            int tryCount = 0;

retry:
            try
            {
                File.Copy(source, target, true);
            }
            catch (FileNotFoundException ex)
            {
                monitor.Error($"Unable to copy file: source '{source}' not found.", ex);
                return(false);
            }
            catch (Exception ex)
            {
                if (++tryCount > 5)
                {
                    monitor.Error($"Unable to copy file: '{source}' to '{target}' after 5 tries.", ex);
                    return(false);
                }
                monitor.Warn($"Unable to copy file: '{source}' to '{target}'. Retrying in {tryCount * 50} ms.", ex);
                System.Threading.Thread.Sleep(tryCount * 50);
                goto retry;
            }
            monitor.Info($"Copied file '{source}' to '{target}'.");
            return(true);
        }
Exemplo n.º 18
0
        static void GenerateNuGetCredentialsEnvironmentVariable(IActivityMonitor m)
        {
            // The VSS_NUGET_EXTERNAL_FEED_ENDPOINTS is used by Azure Credential Provider to handle authentication
            // for the feed.
            StringBuilder b       = new StringBuilder(@"{""endpointCredentials"":[");
            bool          already = false;

            foreach (var kv in _secretAzureKeys)
            {
                if (already)
                {
                    b.Append(',');
                }
                else
                {
                    already = true;
                }

                b.Append(@"{""endpoint"":""").AppendJSONEscaped(kv.Key).Append(@""",")
                .Append(@"""username"":""Unused"",""password"":""").AppendJSONEscaped(kv.Value).Append(@"""")
                .Append("}");
            }
            b.Append("]}");
            var json = b.ToString();

            m.Info($"Updated VSS_NUGET_EXTERNAL_FEED_ENDPOINTS with {_secretAzureKeys.Count} endpoints.");

            Debug.Assert(Newtonsoft.Json.Linq.JObject.Parse(json)["endpointCredentials"] != null);
            Environment.SetEnvironmentVariable("VSS_NUGET_EXTERNAL_FEED_ENDPOINTS", json);
        }
        static StObjMapInfo?LockedGetMapInfo(Assembly a, [AllowNull] ref IActivityMonitor monitor)
        {
            if (_alreadyHandled.TryGetValue(a, out var info))
            {
                return(info);
            }
            LockedEnsureMonitor(ref monitor);
            var attr = a.GetCustomAttributesData().FirstOrDefault(m => m.AttributeType.Name == "SignatureAttribute" && m.AttributeType.Namespace == "CK.StObj");

            if (attr != null)
            {
                using (monitor.OpenInfo($"Analyzing '{a.FullName}' assembly."))
                {
                    info = StObjMapInfo.Create(monitor, a, attr);
                    if (info != null)
                    {
                        var sha1S = info.GeneratedSignature.ToString();
                        if (_alreadyHandled.TryGetValue(sha1S, out var exists))
                        {
                            Debug.Assert(exists != null);
                            monitor.Info($"StObjMap found with the same signature as an already existing one. Keeping the previous one.");
                            info = exists;
                        }
                        else
                        {
                            _alreadyHandled.Add(sha1S, info);
                            _availableMaps.Add(info);
                        }
                    }
                }
                _alreadyHandled.Add(a, info);
            }
            return(info);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Run all apply settings in a random fashion.
        /// </summary>
        /// <param name="universe"></param>
        /// <param name="m"></param>
        /// <param name="worldName"></param>
        /// <param name="seed"></param>
        /// <returns></returns>
        public static TestUniverse ApplyRandomly(this TestUniverse universe, IActivityMonitor m, string worldName, int seed)
        {
            EnsureWorldOpened(universe, worldName);
            var commandRegister = universe.UserHost.CommandRegister;
            var commands        = commandRegister.GetCommands("*applysettings*");

            Action[] actions = commands.Select(s => new Action(() => { s.Execute(m, s.CreatePayload()); }))
                               .Append(() => { CommitAll(universe, m, "Applied some settings.", worldName); })
                               .Append(() => { universe = universe.RestartCKli(); }).ToArray();

            bool[] ranAction = new bool[actions.Length];
            m.Info($"Running random actions with seed '{seed}'");
            var rand = new Random(seed);

            for (int i = 0; i < actions.Length * 2; i++) //TODO: we can add better checks.
            {
                int choosed = rand.Next(0, actions.Length);
                ranAction[choosed] = true;
                actions[choosed]();
            }

            IOrderedEnumerable <Action> shuffled = actions.Where((p, i) => !ranAction[i]).OrderBy(k => rand.Next());

            foreach (var action in shuffled)
            {
                action();
            }
            return(universe);
        }
Exemplo n.º 21
0
 internal CKTypeInfo(IActivityMonitor monitor, CKTypeInfo?parent, Type t, IServiceProvider services, bool isExcluded, AutoServiceClassInfo?serviceClass)
 {
     Debug.Assert((serviceClass == null) == (this is RealObjectClassInfo));
     ServiceClass     = serviceClass;
     Generalization   = parent;
     Type             = t;
     _interfacesCache = System.Type.EmptyTypes;
     if ((parent?.IsExcluded ?? false))
     {
         monitor.Warn($"Type {t.FullName} is excluded since its parent is excluded.");
         IsExcluded = true;
     }
     else if (IsExcluded = isExcluded)
     {
         monitor.Info($"Type {t.FullName} is excluded.");
     }
     else
     {
         _attributes      = new TypeAttributesCache(monitor, t, services, parent == null);
         _interfacesCache = t.GetInterfaces();
         if (parent != null)
         {
             _nextSibling       = parent._firstChild;
             parent._firstChild = this;
             ++parent._specializationCount;
         }
     }
 }
Exemplo n.º 22
0
        public bool SetWorldMapping(IActivityMonitor m, string worldFullName, NormalizedPath mappedPath)
        {
            var worlds = ReadWorlds(m);

            if (worlds == null)
            {
                return(false);
            }
            var w = worlds.FirstOrDefault(x => x.FullName.Equals(worldFullName, StringComparison.OrdinalIgnoreCase));

            if (w == null)
            {
                m.Error($"World '{worldFullName}' not found.");
                return(false);
            }
            if (w.Root == mappedPath)
            {
                m.Trace($"World '{w.FullName}' is already mapped to '{w.Root}'.");
                return(true);
            }
            if (!mappedPath.IsRooted)
            {
                m.Error($"Invalid '{mappedPath}'. It must be rooted.");
                return(false);
            }
            if (!WorldLocalMapping.SetMap(m, w.FullName, mappedPath))
            {
                return(true);
            }
            m.Info($"World '{w.FullName}' is now mapped to '{mappedPath}'.");
            ReadWorlds(m, false);
            return(true);
        }
Exemplo n.º 23
0
 public bool FetchBranches(IActivityMonitor m, bool originOnly = true)
 {
     using (m.OpenInfo($"Fetching {(originOnly ? "origin" : "all remotes")} in repository '{SubPath}'."))
     {
         try
         {
             foreach (Remote remote in Git.Network.Remotes.Where(r => !originOnly || r.Name == "origin"))
             {
                 m.Info($"Fetching remote '{remote.Name}'.");
                 IEnumerable <string> refSpecs = remote.FetchRefSpecs.Select(x => x.Specification).ToArray();
                 Commands.Fetch(Git, remote.Name, refSpecs, new FetchOptions()
                 {
                     CredentialsProvider = (url, user, cred) => PATCredentialsHandler(m),
                     TagFetchMode        = TagFetchMode.All
                 }, $"Fetching remote '{remote.Name}'.");
             }
             return(true);
         }
         catch (Exception ex)
         {
             using (m.OpenFatal("This error need manual fix : "))
             {
                 m.Fatal(ex);
             }
             return(false);
         }
     }
 }
Exemplo n.º 24
0
        static Branch DoGetBranch(IActivityMonitor m, Repository r, string branchName, bool logErrorMissingLocalAndRemote, string repoDisplayName)
        {
            var b = r.Branches[branchName];

            if (b == null)
            {
                string remoteName = "origin/" + branchName;
                var    remote     = r.Branches[remoteName];
                if (remote == null)
                {
                    var msg = $"Repository '{repoDisplayName}': Both local '{branchName}' and remote '{remoteName}' not found.";
                    if (logErrorMissingLocalAndRemote)
                    {
                        m.Error(msg);
                    }
                    else
                    {
                        m.Warn(msg);
                    }
                    return(null);
                }
                m.Info($"Creating local branch on remote '{remoteName}' in repository '{repoDisplayName}'.");
                b = r.Branches.Add(branchName, remote.Tip);
                b = r.Branches.Update(b, u => u.TrackedBranch = remote.CanonicalName);
            }
            return(b);
        }
Exemplo n.º 25
0
 void DemoLogs( IActivityMonitor m, FileInfo f, Exception ex )
 {
     m.Trace().Send( "Data from '{0}' processed.", f.Name );
     m.Info().Send( ex, "An error occurred while processing '{0}'. Process will be retried later.", f.Name );
     m.Warn().Send( "File '{0}' is too big ({1} Kb). It must be less than 50Kb.", f.Name, f.Length / 1024 );
     m.Error().Send( ex, "File '{0}' can not be processed.", f.Name );
     m.Fatal().Send( ex, "This will cancel the whole operation." );
 }
 public void Talk(IActivityMonitor m)
 {
     m.Info("SuperStartupService is talking to you.");
     if (_mustFail)
     {
         m.Error("But SuperStartupService has been told to fail miserably.");
     }
 }
Exemplo n.º 27
0
 void DemoLogs(IActivityMonitor m, FileInfo f, Exception ex)
 {
     m.Trace().Send("Data from '{0}' processed.", f.Name);
     m.Info().Send(ex, "An error occurred while processing '{0}'. Process will be retried later.", f.Name);
     m.Warn().Send("File '{0}' is too big ({1} Kb). It must be less than 50Kb.", f.Name, f.Length / 1024);
     m.Error().Send(ex, "File '{0}' can not be processed.", f.Name);
     m.Fatal().Send(ex, "This will cancel the whole operation.");
 }
Exemplo n.º 28
0
 bool IStObjTypeFilter.TypeFilter(IActivityMonitor monitor, Type t)
 {
     // Type.FullName is null if the current instance represents a generic type parameter, an array
     // type, pointer type, or byref type based on a type parameter, or a generic type
     // that is not a generic type definition but contains unresolved type parameters.
     // This FullName is also null for (at least) classes nested into nested generic classes.
     // In all cases, we emit a warn and filters this beast out.
     if (t.FullName == null)
     {
         monitor.Warn($"Type has no FullName: '{t.Name}'. It is excluded.");
         return(false);
     }
     Debug.Assert(t.AssemblyQualifiedName != null, "Since FullName is defined.");
     if (_excludedTypes.Contains(t.Name))
     {
         monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type Name.");
         return(false);
     }
     if (_excludedTypes.Contains(t.FullName))
     {
         monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type FullName.");
         return(false);
     }
     if (_excludedTypes.Contains(t.AssemblyQualifiedName))
     {
         monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its Type AssemblyQualifiedName.");
         return(false);
     }
     if (SimpleTypeFinder.WeakenAssemblyQualifiedName(t.AssemblyQualifiedName, out var weaken) &&
         _excludedTypes.Contains(weaken))
     {
         monitor.Info($"Type {t.AssemblyQualifiedName} is filtered out by its weak type name ({weaken}).");
         return(false);
     }
     // We only care about IPoco and IRealObject. Nothing more.
     if (_isUnifiedPure)
     {
         if (!typeof(IPoco).IsAssignableFrom(t) &&
             !typeof(IRealObject).IsAssignableFrom(t))
         {
             return(false);
         }
     }
     return(_firstLayer?.TypeFilter(monitor, t) ?? true);
 }
Exemplo n.º 29
0
 public void Close(IActivityMonitor m)
 {
     if (!CanClose)
     {
         throw new InvalidOperationException();
     }
     m.Info($"Closing current world: {CurrentWorld.WorldName.FullName}.");
     Close();
 }
Exemplo n.º 30
0
            /// <summary>
            /// Ensures that the the Git Repository is opened and updates the <see cref="Worlds"/>.
            /// Returns true on success, false on error.
            /// </summary>
            /// <param name="m">The monitor to use.</param>
            /// <param name="force">True to refresh the <see cref="Worlds"/> even if <see cref="IsOpen"/> is already true.</param>
            /// <returns>Whether this repository has been successfully opened.</returns>
            internal bool Refresh(IActivityMonitor m, bool force = true)
            {
                bool isOpened = false;

                if (!IsOpen)
                {
                    _git = GitRepository.Create(m, this, Root, Root.LastPart, false, BranchName, checkOutBranchName: true);
                    if (_git == null)
                    {
                        return(false);
                    }
                    isOpened = true;
                }
                if (force || isOpened)
                {
                    if (_git.Pull(m, MergeFileFavor.Theirs).ReloadNeeded || isOpened)
                    {
                        var worldNames = Directory.GetFiles(Root, "*.World.xml")
                                         .Select(p => LocalWorldName.TryParse(p, _store.WorldLocalMapping))
                                         .Where(w => w != null)
                                         .ToDictionary(w => w.FullName);

                        var invalidParallels = worldNames.Values.Where(p => p.ParallelName != null && !worldNames.ContainsKey(p.Name)).ToList();
                        foreach (var orphan in invalidParallels)
                        {
                            m.Warn($"Invalid Parallel World '{orphan.FullName}': unable to find the default stack definition '{orphan.Name}' in the repository. It is ignored.");
                            worldNames.Remove(orphan.FullName);
                        }
                        foreach (var exists in _worlds)
                        {
                            if (!worldNames.Remove(exists.WorldName.FullName))
                            {
                                if (exists.WorldName.HasDefinitionFile)
                                {
                                    m.Warn($"Unable to find World definition file for '{exists.WorldName}'. File '{exists.WorldName.XmlDescriptionFilePath}' not found.");
                                    exists.WorldName.HasDefinitionFile = false;
                                }
                            }
                            else
                            {
                                if (!exists.WorldName.HasDefinitionFile)
                                {
                                    m.Trace($"Found World definition file for '{exists.WorldName}'.");
                                    exists.WorldName.HasDefinitionFile = true;
                                }
                            }
                        }
                        foreach (var newWorld in worldNames.Values)
                        {
                            m.Info($"Found a new World definition: creating '{newWorld.FullName}' entry.");
                            newWorld.HasDefinitionFile = true;
                            _worlds.Add(new WorldInfo(this, newWorld));
                        }
                    }
                }
                return(IsOpen);
            }
Exemplo n.º 31
0
 void DoSaveKeyVault(IActivityMonitor m)
 {
     foreach (var e in _store.OptimalAvailableInfos)
     {
         _vaultContent[e.Name] = e.Secret;
     }
     m?.Info($"Saved Key Vault with keys: {_vaultContent.Keys.Concatenate()}.");
     File.WriteAllText(KeyVaultPath, KeyVault.EncryptValuesToString(_vaultContent, _passPhrase));
 }
Exemplo n.º 32
0
        static void DumpMonitorOutput( IActivityMonitor monitor )
        {
            Exception exception1;
            Exception exception2;

            try
            {
                throw new InvalidOperationException( "Exception!" );
            }
            catch( Exception e )
            {
                exception1 = e;
            }

            try
            {
                throw new InvalidOperationException( "Inception!", exception1 );
            }
            catch( Exception e )
            {
                exception2 = e;
            }

            for( int i = 0; i < 5; i++ )
            {
                using( monitor.OpenTrace().Send( "Dump output loop {0}", i ) )
                {
                    for( int j = 0; j < 1000; j++ )
                    {
                        monitor.Trace().Send( "Trace log! {0}", j );
                        monitor.Info().Send( "Info log! {0}", j );
                        monitor.Warn().Send( "Warn log! {0}", j );
                        monitor.Error().Send( "Error log! {0}", j );
                        monitor.Error().Send( "Fatal log! {0}", j );

                        monitor.Error().Send( exception2, "Exception log! {0}", j );

                    }
                }
            }
        }
Exemplo n.º 33
0
 public static void ReplayLogs( DirectoryInfo directory, bool recurse, Func<MultiLogReader.Monitor, ActivityMonitor> monitorProvider, IActivityMonitor m = null )
 {
     var reader = new MultiLogReader();
     using( m != null ? m.OpenTrace().Send( "Reading files from '{0}' {1}.", directory.FullName, recurse ? "(recursive)" : null ) : null )
     {
         var files = reader.Add( directory.EnumerateFiles( "*.ckmon", recurse ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly ).Select( f => f.FullName ) );
         if( files.Count == 0 )
         {
             if( m != null ) m.Warn().Send( "No *.ckmon files found!" );
         }
         else
         {
             var monitors = reader.GetActivityMap().Monitors;
             if( m != null )
             {
                 m.Trace().Send( String.Join( Environment.NewLine, files ) );
                 m.CloseGroup( String.Format( "Found {0} file(s) containing {1} monitor(s).", files.Count, monitors.Count ) );
                 m.OpenTrace().Send( "Extracting entries." );
             }
             foreach( var mon in monitors )
             {
                 var replay = monitorProvider( mon );
                 if( replay == null )
                 {
                     if( m != null ) m.Info().Send( "Skipping activity from '{0}'.", mon.MonitorId );
                 }
                 else
                 {
                     mon.Replay( replay, m );
                 }
             }
         }
     }
 }