Skip to content

Commit

Permalink
feat: 🧑‍💻 create TransformedQuery extension class (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNZL committed Jul 2, 2023
1 parent 7568f2a commit 0cab081
Show file tree
Hide file tree
Showing 4 changed files with 177 additions and 76 deletions.
30 changes: 0 additions & 30 deletions src/Main.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Windows.Controls;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
Expand Down Expand Up @@ -29,35 +28,6 @@ public class Main : IAsyncPlugin, ISettingProvider
null
);

public static string ExtractQueryTo(Query query, int index)
{
return string.Join(" ", query.SearchTerms.Take(index));
}

public static string ExtractQueryAfter(Query query, int index)
{
return (index == 1)
// Expect slight performance improvement by using query.SecondToEndSearch directly
? query.SecondToEndSearch
: string.Join(" ", query.SearchTerms.Skip(index));
}

public static string ExtractQueryBetween(Query query, int after, int to)
{
return string.Join(" ", query.SearchTerms.Take(to).Skip(after));
}

public static string UnescapeSearch(string search)
{
return Regex.Replace(search, @"(\\(?!\\))", string.Empty);
}

public static string EscapeDescription(string description)
{
string escaped = Regex.Replace(description, @"(\\(?!\\))", @"\\");
return Regex.Replace(escaped, @" -", @" \-");
}

/// <summary>
/// Runs on plugin initialisation.
/// Expensive operations should be performed here.
Expand Down
18 changes: 9 additions & 9 deletions src/Structures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ public int GetScoreByDuration(TimeEntry? longest)
}

string rawDescription = (escapePotentialFlags)
? Main.EscapeDescription(this._rawDescription)
? TransformedQuery.EscapeDescription(this._rawDescription)
: this._rawDescription;

if (!withTrailingSpace)
Expand All @@ -228,7 +228,7 @@ public string GetDescription(bool escapePotentialFlags = false)
}

return (escapePotentialFlags)
? Main.EscapeDescription(this._rawDescription)
? TransformedQuery.EscapeDescription(this._rawDescription)
: this._rawDescription;
}

Expand Down Expand Up @@ -286,6 +286,11 @@ public class SummaryReport : ICloneable
// Key as -1 for 'No Project' or 'No Client' cases
public Dictionary<long, SummaryReportGroup> Groups;

internal static long GetGroupKey(long? id)
{
return id ?? -1;
}

public SummaryReport(SummaryReportResponse response, Me me)
{
this._me = me;
Expand All @@ -299,11 +304,6 @@ public SummaryReport(SummaryReport summary)
this.Groups = summary.Groups.ToDictionary(keySelector: pair => pair.Key, elementSelector: pair => pair.Value.Clone());
}

internal static long GetGroupKey(long? id)
{
return id ?? -1;
}

public SummaryReport Clone()
{
return new SummaryReport(this);
Expand Down Expand Up @@ -575,7 +575,7 @@ public int GetScoreByDuration()
}

string rawTitle = (escapePotentialFlags)
? Main.EscapeDescription(this._rawTitle)
? TransformedQuery.EscapeDescription(this._rawTitle)
: this._rawTitle;

if (!withTrailingSpace)
Expand All @@ -594,7 +594,7 @@ public string GetTitle(bool escapePotentialFlags = false)
}

return (escapePotentialFlags)
? Main.EscapeDescription(this._rawTitle)
? TransformedQuery.EscapeDescription(this._rawTitle)
: this._rawTitle;
}

Expand Down
115 changes: 78 additions & 37 deletions src/TogglTrack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -639,7 +639,9 @@ internal async ValueTask<List<Result>> RequestStartEntry(CancellationToken token
{
var projects = new List<Result>();

string projectQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Project);
string projectQuery = new TransformedQuery(query)
.After(ArgumentIndices.Project)
.ToString();

if (string.IsNullOrEmpty(projectQuery) || this._context.API.FuzzySearch(projectQuery, "No Project").Score > 0)
{
Expand Down Expand Up @@ -690,7 +692,9 @@ internal async ValueTask<List<Result>> RequestStartEntry(CancellationToken token
long workspaceId = project?.WorkspaceId ?? me.DefaultWorkspaceId;

string projectName = project?.WithClientName ?? Settings.NoProjectName;
string description = Main.UnescapeSearch(Main.ExtractQueryAfter(query, ArgumentIndices.Description));
string description = new TransformedQuery(query)
.After(ArgumentIndices.Description)
.ToString(TransformedQuery.Escaping.Unescaped);

var results = new List<Result>();

Expand Down Expand Up @@ -796,7 +800,9 @@ internal async ValueTask<List<Result>> RequestStartEntry(CancellationToken token
try
{
var startTimeSpan = TimeSpanParser.Parse(
Main.ExtractQueryAfter(query, Array.IndexOf(query.SearchTerms, Settings.TimeSpanFlag) + 1),
new TransformedQuery(query)
.After(Settings.TimeSpanFlag)
.ToString(),
new TimeSpanParserOptions
{
UncolonedDefault = Units.Minutes,
Expand All @@ -808,9 +814,9 @@ internal async ValueTask<List<Result>> RequestStartEntry(CancellationToken token
var startTime = DateTimeOffset.UtcNow + startTimeSpan;

// Remove -t flag from description
string sanitisedDescription = Main.UnescapeSearch(
Main.ExtractQueryBetween(query, ArgumentIndices.Description, Array.IndexOf(query.SearchTerms, Settings.TimeSpanFlag))
);
string sanitisedDescription = new TransformedQuery(query)
.Between(ArgumentIndices.Description, Settings.TimeSpanFlag)
.ToString(TransformedQuery.Escaping.Unescaped);

results.Add(new Result
{
Expand Down Expand Up @@ -884,7 +890,8 @@ internal async ValueTask<List<Result>> RequestStartEntry(CancellationToken token
{
if (this._settings.ShowUsageExamples)
{
var queryToFlag = Main.ExtractQueryTo(query, Array.IndexOf(query.SearchTerms, Settings.TimeSpanFlag));
var queryToFlag = new TransformedQuery(query)
.To(Settings.TimeSpanFlag);

results.Add(new Result
{
Expand Down Expand Up @@ -1077,7 +1084,9 @@ internal async ValueTask<List<Result>> RequestStopEntry(CancellationToken token,
try
{
var stopTimeSpan = TimeSpanParser.Parse(
Main.ExtractQueryAfter(query, Array.IndexOf(query.SearchTerms, Settings.TimeSpanEndFlag) + 1),
new TransformedQuery(query)
.After(Settings.TimeSpanEndFlag)
.ToString(),
new TimeSpanParserOptions
{
UncolonedDefault = Units.Minutes,
Expand Down Expand Up @@ -1211,7 +1220,9 @@ internal async ValueTask<List<Result>> RequestContinueEntry(CancellationToken to
});
}

string entriesQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Description);
string entriesQuery = new TransformedQuery(query)
.After(ArgumentIndices.Description)
.ToString();

return timeEntries.Groups.Values.SelectMany(project =>
{
Expand Down Expand Up @@ -1287,7 +1298,9 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,

if (this._state.SelectedIds.TimeEntry == -1)
{
string entriesQuery = Main.ExtractQueryAfter(query, ArgumentIndices.DescriptionWithoutProject);
string entriesQuery = new TransformedQuery(query)
.After(ArgumentIndices.DescriptionWithoutProject)
.ToString();
var filteredTimeEntries = (string.IsNullOrEmpty(entriesQuery))
? timeEntries
: timeEntries.FindAll(timeEntry => this._context.API.FuzzySearch(entriesQuery, timeEntry.GetDescription()).Score > 0);
Expand Down Expand Up @@ -1339,7 +1352,9 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
{
var projects = new List<Result>();

string projectQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Project);
string projectQuery = new TransformedQuery(query)
.After(ArgumentIndices.Project)
.ToString();

if (string.IsNullOrEmpty(projectQuery) || this._context.API.FuzzySearch(projectQuery, "No Project").Score > 0)
{
Expand Down Expand Up @@ -1392,12 +1407,12 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,

if (query.SearchTerms.Contains(Settings.ClearDescriptionFlag))
{
string queryToDescription = Main.ExtractQueryTo(
query,
(this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
string queryToDescription = new TransformedQuery(query)
.To((this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
? ArgumentIndices.DescriptionWithProject
: ArgumentIndices.DescriptionWithoutProject
);
)
.ToString();

this._context.API.ChangeQuery($"{query.ActionKeyword} {queryToDescription} ");
}
Expand All @@ -1421,12 +1436,12 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
var project = me.GetProject(this._state.SelectedIds.Project);

string projectName = project?.WithClientName ?? Settings.NoProjectName;
string description = Main.UnescapeSearch(Main.ExtractQueryAfter(
query,
(this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
string description = new TransformedQuery(query)
.After((this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
? ArgumentIndices.DescriptionWithProject
: ArgumentIndices.DescriptionWithoutProject
));
)
.ToString(TransformedQuery.Escaping.Unescaped);

if (this._settings.ShowUsageWarnings && string.IsNullOrEmpty(description) && !string.IsNullOrEmpty(timeEntry.GetRawDescription()))
{
Expand Down Expand Up @@ -1642,7 +1657,9 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
try
{
startTimeSpan = TimeSpanParser.Parse(
Main.ExtractQueryAfter(query, Array.IndexOf(query.SearchTerms, Settings.TimeSpanFlag) + 1),
new TransformedQuery(query)
.After(Settings.TimeSpanFlag)
.ToString(),
new TimeSpanParserOptions
{
UncolonedDefault = Units.Minutes,
Expand All @@ -1663,7 +1680,9 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
try
{
endTimeSpan = TimeSpanParser.Parse(
Main.ExtractQueryAfter(query, Array.IndexOf(query.SearchTerms, Settings.TimeSpanEndFlag) + 1),
new TransformedQuery(query)
.After(Settings.TimeSpanEndFlag)
.ToString(),
new TimeSpanParserOptions
{
UncolonedDefault = Units.Minutes,
Expand All @@ -1681,13 +1700,14 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
}

// Remove flags from description
string sanitisedDescription = Main.UnescapeSearch(Main.ExtractQueryBetween(
query,
(this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
? ArgumentIndices.DescriptionWithProject
: ArgumentIndices.DescriptionWithoutProject,
firstFlag
));
string sanitisedDescription = new TransformedQuery(query)
.Between(
(this._state.EditProject == TogglTrack.EditProjectState.ProjectSelected)
? ArgumentIndices.DescriptionWithProject
: ArgumentIndices.DescriptionWithoutProject,
firstFlag
)
.ToString(TransformedQuery.Escaping.Unescaped);

if (this._settings.ShowUsageWarnings && string.IsNullOrEmpty(sanitisedDescription) && !string.IsNullOrEmpty(timeEntry.GetRawDescription()))
{
Expand Down Expand Up @@ -1847,7 +1867,9 @@ internal async ValueTask<List<Result>> RequestEditEntry(CancellationToken token,
{
string flag = exception.Message;

var queryToFlag = Main.ExtractQueryTo(query, Array.IndexOf(query.SearchTerms, flag));
var queryToFlag = new TransformedQuery(query)
.To(flag)
.ToString();

results.Add(new Result
{
Expand Down Expand Up @@ -1933,7 +1955,9 @@ internal async ValueTask<List<Result>> RequestDeleteEntry(CancellationToken toke

if (this._state.SelectedIds.TimeEntry == -1)
{
string entriesQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Description);
string entriesQuery = new TransformedQuery(query)
.After(ArgumentIndices.Description)
.ToString();
var filteredTimeEntries = (string.IsNullOrEmpty(entriesQuery))
? timeEntries
: timeEntries.FindAll(timeEntry => this._context.API.FuzzySearch(entriesQuery, timeEntry.GetDescription()).Score > 0);
Expand Down Expand Up @@ -2053,9 +2077,14 @@ internal async ValueTask<List<Result>> RequestViewReports(CancellationToken toke

if ((query.SearchTerms.Length == ArgumentIndices.Span) || !Settings.ReportsSpanArguments.Exists(span => Regex.IsMatch(query.SearchTerms[ArgumentIndices.Span], $"{span.Argument}({Settings.ReportsSpanOffsetRegex})?")))
{
string queryToSpan = Main.ExtractQueryTo(query, ArgumentIndices.Span);
string queryToSpan = new TransformedQuery(query)
.To(ArgumentIndices.Span)
.ToString();

string spanQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Span);
// TODO: #84
string spanQuery = new TransformedQuery(query)
.After(ArgumentIndices.Span)
.ToString();

// Implementation of eg '-5' to set span to be 5 [days | weeks | months | years] ago
Match spanOffsetMatch = Settings.ReportsSpanOffsetRegex.Match(spanQuery);
Expand Down Expand Up @@ -2141,9 +2170,14 @@ internal async ValueTask<List<Result>> RequestViewReports(CancellationToken toke
*/
if ((query.SearchTerms.Length == ArgumentIndices.Grouping) || !Settings.ReportsGroupingArguments.Exists(grouping => grouping.Argument == query.SearchTerms[ArgumentIndices.Grouping]))
{
string queryToGrouping = Main.ExtractQueryTo(query, ArgumentIndices.Grouping);
string queryToGrouping = new TransformedQuery(query)
.To(ArgumentIndices.Grouping)
.ToString();

string groupingsQuery = new TransformedQuery(query)
.After(ArgumentIndices.Grouping)
.ToString();

string groupingsQuery = Main.ExtractQueryAfter(query, ArgumentIndices.Grouping);
var filteredGroupings = (string.IsNullOrEmpty(groupingsQuery))
? Settings.ReportsGroupingArguments
: Settings.ReportsGroupingArguments.FindAll(grouping => this._context.API.FuzzySearch(groupingsQuery, grouping.Argument).Score > 0);
Expand Down Expand Up @@ -2231,7 +2265,9 @@ internal async ValueTask<List<Result>> RequestViewReports(CancellationToken toke

var results = new List<Result>();

string groupQuery = Main.ExtractQueryAfter(query, ArgumentIndices.GroupingName);
string groupQuery = new TransformedQuery(query)
.After(ArgumentIndices.GroupingName)
.ToString();

if (string.IsNullOrEmpty(groupQuery))
{
Expand Down Expand Up @@ -2293,7 +2329,9 @@ internal async ValueTask<List<Result>> RequestViewReports(CancellationToken toke
IEnumerable<Result> subResults = Enumerable.Empty<Result>();
var total = TimeSpan.Zero;

string subGroupQuery = Main.ExtractQueryAfter(query, ArgumentIndices.SubGroupingName);
string subGroupQuery = new TransformedQuery(query)
.After(ArgumentIndices.SubGroupingName)
.ToString();

if (this._state.ReportsShowDetailed)
{
Expand Down Expand Up @@ -2455,7 +2493,10 @@ internal async ValueTask<List<Result>> RequestViewReports(CancellationToken toke

var client = me.GetClient(selectedClientGroup.Id);

string subGroupQuery = Main.ExtractQueryAfter(query, ArgumentIndices.SubGroupingName);
string subGroupQuery = new TransformedQuery(query)
.After(ArgumentIndices.SubGroupingName)
.ToString();

var filteredSubGroups = (string.IsNullOrEmpty(subGroupQuery))
? selectedClientGroup.SubGroups.Values
: selectedClientGroup.SubGroups.Values.Where(subGroup =>
Expand Down
Loading

0 comments on commit 0cab081

Please sign in to comment.