using System.IO;
using Titano.Core.Packaging;
namespace Titano.Setup.Engine;
///
/// The program a command line registered with Windows starts (a service's image path, a Run value), and whether it is
/// one setup installed: setup changes only what starts a program its log or payload lists, never another program
/// that happens to live in the same folder.
///
internal static class CommandProgram
{
///
/// The first token, quoted or up to .exe, with environment variables expanded; for the dotnet host,
/// the assembly it runs. Null when the line names no full path.
///
public static string? Of(string commandLine)
{
var line = Environment.ExpandEnvironmentVariables(commandLine).Trim();
var first = NextToken(ref line);
if (first is null) return null;
if (Path.GetFileNameWithoutExtension(first).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) first = NextToken(ref line);
return first is not null && Path.IsPathFullyQualified(first) ? first : null;
}
///
/// Full paths of (an install log's or a manifest's files) under
/// , compared ignoring case: the programs setup installs or installed there.
///
public static IReadOnlySet FullPaths(string directory, IEnumerable payloadPaths)
{
var paths = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var path in payloadPaths.Where(PayloadPath.IsValid)) paths.Add(PayloadPath.Resolve(directory, path));
return paths;
}
/// True when (a full path, in any form Windows accepts) is one of .
public static bool IsAmong(string? program, IReadOnlySet programs)
{
if (string.IsNullOrEmpty(program) || !Path.IsPathFullyQualified(program)) return false;
try
{
return programs.Contains(Path.GetFullPath(program));
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// that answers false for a path Windows cannot normalise.
public static bool IsPathInside(string path, string directory)
{
try
{
return SetupPaths.IsSameOrInside(path, directory);
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return false;
}
}
/// Takes the next token of a command line: quoted, or up to .exe followed by a space, or up to the next space.
private static string? NextToken(ref string line)
{
line = line.TrimStart();
if (line.Length == 0) return null;
string token;
if (line[0] == '"')
{
var close = line.IndexOf('"', 1);
token = close < 0 ? line[1..] : line[1..close];
line = close < 0 ? string.Empty : line[(close + 1)..];
}
else
{
// An unquoted path with spaces ("C:\Program Files\Titano\Titano.Server.exe --service") ends at its extension.
var exe = line.IndexOf(".exe", StringComparison.OrdinalIgnoreCase);
var space = line.IndexOf(' ');
var end = exe >= 0 && (exe + 4 == line.Length || line[exe + 4] == ' ') ? exe + 4 : space >= 0 ? space : line.Length;
token = line[..end];
line = line[end..];
}
return token.Length == 0 ? null : token;
}
}