Skip to content

Commit

Permalink
code tidy services.
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinJump committed Apr 10, 2024
1 parent 2213a4b commit e59dcb6
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 55 deletions.
3 changes: 2 additions & 1 deletion uSync.BackOffice/Services/SyncActionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ private string MakeValidImportFolder(string folder)
var fullPath = _syncFileService.GetAbsPath(folder);
var fullRoot = _syncFileService.GetAbsPath(_uSyncConfig.GetRootFolder());

var rootParent = Path.GetDirectoryName(fullRoot.TrimEnd(new char[] { '/', '\\' }));
var rootParent = Path.GetDirectoryName(fullRoot.TrimEnd(['/', '\\']));

_logger.LogDebug("Import Folder: {fullPath} {rootPath} {fullRoot}", fullPath, rootParent, fullRoot);

if (rootParent is not null && fullPath.StartsWith(rootParent))
Expand Down
59 changes: 26 additions & 33 deletions uSync.BackOffice/Services/SyncFileService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ namespace uSync.BackOffice.Services;
/// </summary>
public class SyncFileService
{
private readonly ILogger<SyncFileService> logger;
private readonly ILogger<SyncFileService> _logger;
private readonly IHostEnvironment _hostEnvironment;

private static char[] _trimChars = [' ', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar];
private static readonly char[] _trimChars = [' ', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar];

/// <summary>
/// Constructor for File service (via DI)
Expand All @@ -35,7 +35,7 @@ public class SyncFileService
public SyncFileService(ILogger<SyncFileService> logger,
IHostEnvironment hostEnvironment)
{
this.logger = logger;
_logger = logger;
_hostEnvironment = hostEnvironment;
}

Expand Down Expand Up @@ -64,7 +64,7 @@ public string GetSiteRelativePath(string path)
/// <summary>
/// clean up the local path, and full expand any short file names
/// </summary>
private string CleanLocalPath(string path)
private static string CleanLocalPath(string path)
=> Path.GetFullPath(path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));

/// <summary>
Expand Down Expand Up @@ -190,8 +190,8 @@ public void CreateFoldersForFile(string filePath)
public void CreateFolder(string folder)
{
var absPath = GetAbsPath(folder);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
if (!Directory.Exists(absPath))
Directory.CreateDirectory(absPath);
}

/// <summary>
Expand All @@ -216,18 +216,15 @@ public IEnumerable<string> GetFiles(string folder, string extensions)
/// </summary>
/// <param name="folder">path to the folder</param>
/// <param name="extensions">list of extensions (filter)</param>
/// <param name="allFolders">get all files in all decentant folders</param>
/// <param name="allFolders">get all files in all descendant folders</param>
/// <returns></returns>
public IEnumerable<string> GetFiles(string folder, string extensions, bool allFolders)
{
var localPath = GetAbsPath(folder);
if (DirectoryExists(localPath))
{
return Directory.GetFiles(localPath, extensions, allFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
}

return Enumerable.Empty<string>();
if (!DirectoryExists(localPath)) return [];

return Directory.GetFiles(localPath, extensions, allFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
}

/// <summary>
Expand All @@ -236,12 +233,10 @@ public IEnumerable<string> GetFiles(string folder, string extensions, bool allFo
public IEnumerable<string> GetDirectories(string folder)
{
var localPath = GetAbsPath(folder);
if (DirectoryExists(localPath))
{
return Directory.GetDirectories(localPath);
}

return Enumerable.Empty<string>();
if (!DirectoryExists(localPath)) return [];

return Directory.GetDirectories(localPath);

}

/// <summary>
Expand All @@ -263,7 +258,7 @@ public XElement LoadXElement(string file)
}
catch (Exception ex)
{
logger.LogWarning("Error while reading in {file} {message}", file, ex.Message);
_logger.LogWarning("Error while reading in {file} {message}", file, ex.Message);
throw new Exception($"Error while reading in {file}", ex);
}
}
Expand All @@ -273,7 +268,7 @@ public XElement LoadXElement(string file)
/// </summary>
public void SaveFile(string filename, Stream stream)
{
logger.LogDebug("Saving File: {file}", filename);
_logger.LogDebug("Saving File: {file}", filename);

using (Stream fileStream = OpenWrite(filename))
{
Expand All @@ -289,7 +284,7 @@ public void SaveFile(string filename, Stream stream)
public void SaveFile(string filename, string content)
{
var localFile = GetAbsPath(filename);
logger.LogDebug("Saving File: {local} [{length}]", localFile, content.Length);
_logger.LogDebug("Saving File: {local} [{length}]", localFile, content.Length);

using (Stream stream = OpenWrite(localFile))
{
Expand Down Expand Up @@ -361,7 +356,7 @@ public void DeleteFolder(string folder, bool safe = false)
catch (Exception ex)
{
// can happen when its locked, question is - do you care?
logger.LogWarning(ex, "Failed to remove directory {folder}", folder);
_logger.LogWarning(ex, "Failed to remove directory {folder}", folder);
if (!safe) throw;
}
}
Expand Down Expand Up @@ -396,12 +391,10 @@ public void CopyFolder(string source, string target)
}


// TODO: this doesn't need to be public?

/// <summary>
/// Locking item for saves.
/// </summary>
public static object _saveLock = new object();
private static object _saveLock = new();

/// <summary>
/// save an object to an XML file representing it.
Expand Down Expand Up @@ -460,13 +453,13 @@ public List<string> VerifyFolder(string folder, string extension)
var filename = Path.GetFileName(file);
var filePath = GetShortFileName(file);

if (!keys.ContainsKey(key))
if (keys.TryGetValue(key, out string? value))
{
keys[key] = filePath;
}
errors.Add($"Clash {filePath} shares an id with {value}");
}
else
{
errors.Add($"Clash {filePath} shares an id with {keys[key]}");
keys[key] = filePath;
}
}
}
Expand All @@ -479,7 +472,7 @@ public List<string> VerifyFolder(string folder, string extension)
return errors;
}

string GetShortFileName(string file)
static string GetShortFileName(string file)
=> $"{Path.DirectorySeparatorChar}{Path.GetFileName(Path.GetDirectoryName(file))}" +
$"{Path.DirectorySeparatorChar}{Path.GetFileName(file)}";

Expand Down Expand Up @@ -513,10 +506,10 @@ public IEnumerable<OrderedNodeInfo> MergeFolders(string[] folders, string extens

foreach (var item in items)
{
if (trackerBase is not null && elements.ContainsKey(item.Key))
if (trackerBase is not null && elements.TryGetValue(item.Key, out var value))
{
// merge these files.
item.Value.SetNode(trackerBase.MergeFiles(elements[item.Key].Node, item.Value.Node));
item.Value.SetNode(trackerBase.MergeFiles(value.Node, item.Value.Node));
}

elements[item.Key] = item.Value;
Expand Down Expand Up @@ -602,7 +595,7 @@ public List<XElement> GetAllNodes(string[] filePaths)
public bool AnyFolderExists(string[] folders)
=> folders.Any(DirectoryExists);

private string[] GetFilePaths(string folder, string extension)
private static string[] GetFilePaths(string folder, string extension)
=> Directory.GetFiles(folder, $"*.{extension}", SearchOption.AllDirectories);

private XElement? LoadXElementSafe(string file)
Expand Down
8 changes: 4 additions & 4 deletions uSync.BackOffice/Services/uSyncService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ public IEnumerable<uSyncAction> Report(string folder, IEnumerable<HandlerConfigP
#endregion

#region Importing
private static object _importLock = new object();
private static object _importLock = new();

/// <summary>
/// Import items into Umbraco from a given folder
Expand Down Expand Up @@ -277,7 +277,7 @@ public IEnumerable<uSyncAction> Import(string folder, bool force, IEnumerable<Ha
public IEnumerable<uSyncAction> Import(string[] folders, bool force, IEnumerable<HandlerConfigPair> handlers, uSyncCallbacks? callbacks)
{
// if its blank, we just throw it back empty.
if (handlers == null || !handlers.Any()) return Enumerable.Empty<uSyncAction>();
if (handlers == null || !handlers.Any()) return[];

lock (_importLock)
{
Expand Down Expand Up @@ -358,10 +358,10 @@ public IEnumerable<uSyncAction> Import(string[] folders, bool force, IEnumerable
}
}

private static IEnumerable<uSyncAction> PerformPostImport(IEnumerable<HandlerConfigPair> handlers, IEnumerable<uSyncAction> actions)
private static List<uSyncAction> PerformPostImport(IEnumerable<HandlerConfigPair> handlers, IEnumerable<uSyncAction> actions)
{
var postImportActions = actions.Where(x => x.Success && x.Change > Core.ChangeType.NoChange && x.RequiresPostProcessing).ToList();
if (postImportActions.Count == 0) return Enumerable.Empty<uSyncAction>();
if (postImportActions.Count == 0) return [];

var results = new List<uSyncAction>();

Expand Down
7 changes: 3 additions & 4 deletions uSync.BackOffice/Services/uSyncService_Files.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,8 @@ public void ReplaceFiles(string source, string target, bool clean)
}


private string GetRelativePath(string root, string file)
private static string GetRelativePath(string root, string file)
{

var cleanRoot = CleanPathForZip(root);
var cleanFile = CleanPathForZip(file);

Expand All @@ -97,11 +96,11 @@ private string GetRelativePath(string root, string file)
return cleanFile.Substring(cleanRoot.Length).TrimStart(Path.DirectorySeparatorChar);
}

private string GetOSDependentPath(string file)
private static string GetOSDependentPath(string file)
=> file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar)
.Trim(Path.DirectorySeparatorChar);

private string CleanPathForZip(string path)
private static string CleanPathForZip(string path)
=> Path.GetFullPath(
path.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar))
.TrimEnd(Path.DirectorySeparatorChar);
Expand Down
6 changes: 3 additions & 3 deletions uSync.BackOffice/Services/uSyncService_Handlers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public IEnumerable<uSyncAction> ReportHandler(string handler, uSyncImportOptions
Action = HandlerActions.Report
});

if (handlerPair == null) return Enumerable.Empty<uSyncAction>();
if (handlerPair == null) return [];
var folders = GetHandlerFolders(options.Folders, handlerPair.Handler);

return handlerPair.Handler.Report(folders, handlerPair.Settings, options.Callbacks?.Update);
Expand All @@ -50,7 +50,7 @@ public IEnumerable<uSyncAction> ImportHandler(string handlerAlias, uSyncImportOp
Action = HandlerActions.Import
});

if (handlerPair == null) return Enumerable.Empty<uSyncAction>();
if (handlerPair == null) return [];
var folders = GetHandlerFolders(options.Folders, handlerPair.Handler);

_logger.LogDebug("> Import Handler {handler}", handlerAlias);
Expand Down Expand Up @@ -107,7 +107,7 @@ public IEnumerable<uSyncAction> ExportHandler(string handler, uSyncImportOptions
Action = HandlerActions.Export
});

if (handlerPair == null) return Enumerable.Empty<uSyncAction>();
if (handlerPair == null) return [];
var folders = GetHandlerFolders(options.Folders, handlerPair.Handler);
return handlerPair.Handler.ExportAll(folders, handlerPair.Settings, options.Callbacks?.Update);
}
Expand Down
20 changes: 10 additions & 10 deletions uSync.BackOffice/Services/uSyncService_Single.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public IEnumerable<uSyncAction> ReportPartial(IList<OrderedNodeInfo> orderedNode
}

options.Callbacks?.Update?.Invoke(item.Node.GetAlias(),
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);

if (handlerPair != null)
{
Expand Down Expand Up @@ -159,7 +159,7 @@ public IEnumerable<uSyncAction> ImportPartial(IList<OrderedNodeInfo> orderedNode
}

options.Callbacks?.Update?.Invoke(node.GetAlias(),
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);

if (handlerPair != null)
{
Expand Down Expand Up @@ -228,7 +228,7 @@ public IEnumerable<uSyncAction> ImportPartialSecondPass(IEnumerable<uSyncAction>
}

options.Callbacks?.Update?.Invoke($"Second Pass: {action.Name}",
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);
CalculateProgress(index, total, options.ProgressMin, options.ProgressMax), 100);

secondPassActions.AddRange(handlerPair.Handler.ImportSecondPass(action, handlerPair.Settings, options));

Expand All @@ -251,7 +251,7 @@ public IEnumerable<uSyncAction> ImportPartialSecondPass(IEnumerable<uSyncAction>
/// </summary>
public IEnumerable<uSyncAction> ImportPartialPostImport(IEnumerable<uSyncAction> actions, uSyncPagedImportOptions options)
{
if (actions == null || !actions.Any()) return Enumerable.Empty<uSyncAction>();
if (actions == null || !actions.Any()) return [];

lock (_importLock)
{
Expand Down Expand Up @@ -307,7 +307,7 @@ public IEnumerable<uSyncAction> ImportPartialPostImport(IEnumerable<uSyncAction>
/// </summary>
public IEnumerable<uSyncAction> ImportPostCleanFiles(IEnumerable<uSyncAction> actions, uSyncPagedImportOptions options)
{
if (actions == null) return Enumerable.Empty<uSyncAction>();
if (actions == null) return [];

lock (_importLock)
{
Expand Down Expand Up @@ -349,8 +349,8 @@ public IEnumerable<uSyncAction> ImportPostCleanFiles(IEnumerable<uSyncAction> ac
}
}

private SyncHandlerOptions HandlerOptionsFromPaged(uSyncPagedImportOptions options)
=> new SyncHandlerOptions(options.HandlerSet, options.UserId)
private static SyncHandlerOptions HandlerOptionsFromPaged(uSyncPagedImportOptions options)
=> new(options.HandlerSet, options.UserId)
{
IncludeDisabled = options.IncludeDisabledHandlers
};
Expand All @@ -360,7 +360,7 @@ private SyncHandlerOptions HandlerOptionsFromPaged(uSyncPagedImportOptions optio
/// </summary>
[Obsolete("use handler and multiple folder method will be removed in v15")]
public IList<OrderedNodeInfo> LoadOrderedNodes(string folder)
=> LoadOrderedNodes([folder]).ToList();
=> LoadOrderedNodes([folder]);

/// <summary>
/// Load the xml in a folder in level order so we process the higher level items first.
Expand Down Expand Up @@ -399,7 +399,7 @@ public IList<OrderedNodeInfo> LoadOrderedNodes(string[] folders)
/// </remarks>
[Obsolete("use handler and multiple folder method will be removed in v15")]
public IList<OrderedNodeInfo> LoadOrderedNodes(ISyncHandler handler, string handlerFolder)
=> LoadOrderedNodes(handler, [handlerFolder]).ToList();
=> LoadOrderedNodes(handler, [handlerFolder]);

/// <summary>
/// load up ordered nodes from a handler folder,
Expand All @@ -416,6 +416,6 @@ public IList<OrderedNodeInfo> LoadOrderedNodes(ISyncHandler handler, string[] ha
/// <remarks>
/// for partial imports this allows the calling progress to smooth out the progress bar.
/// </remarks>
private int CalculateProgress(int value, int total, int min, int max)
private static int CalculateProgress(int value, int total, int min, int max)
=> (int)(min + (((float)value / total) * (max - min)));
}

0 comments on commit e59dcb6

Please sign in to comment.