using DTT.Utils.Exceptions;
using DTT.Utils.Extensions;
using System;
using System.IO;
using UnityEngine;
namespace DTT.Utils.Workflow
{
///
/// Provides path related utility methods.
///
public static class PathUtility
{
///
/// Returns the element of the path depending on the given
/// index when split using the directory separation character.
///
/// The path of which to get the element.
/// The index of the split elements.
/// The name of the directory.
public static string GetPathElementAt(this string path, int index)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
string[] names = path.Split(Path.AltDirectorySeparatorChar);
if (names.HasIndex(index))
return names[index];
else
return string.Empty;
}
///
/// Returns whether the given directory name is part of the given path.
///
/// The path to check.
/// The directory name to look for.
/// Whether the given directory name is part of the given path.
public static bool ContainsDirectory(string path, string directoryName)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (directoryName == null)
throw new ArgumentNullException(nameof(directoryName));
string[] directoriesInPath = path.Split(Path.AltDirectorySeparatorChar);
for (int i = 0; i < directoriesInPath.Length; i++)
{
if (directoriesInPath[i] == directoryName)
return true;
}
return false;
}
///
/// Ensures the directory at given directory path exists by creating
/// it if it isn't there yet.
///
/// The directory path.
public static void EnsureDirectoryExistence(string directoryPath)
{
if (string.IsNullOrEmpty(directoryPath))
throw new NullOrEmptyException(nameof(directoryPath));
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
}
///
/// Returns the asset path for a given full path of the asset.
///
/// The full path of the asset.
/// The asset path.
public static string ToAssetPath(this string fullPathOfAsset)
{
if (string.IsNullOrEmpty(fullPathOfAsset))
throw new NullOrEmptyException(nameof(fullPathOfAsset));
if (fullPathOfAsset.Contains("\\"))
fullPathOfAsset = fullPathOfAsset.Replace("\\", "/");
string path;
if (fullPathOfAsset.StartsWith(Application.dataPath))
path = "Assets" + fullPathOfAsset.Substring(Application.dataPath.Length);
else
path = fullPathOfAsset;
// Make sure the path is compatible with an asset path structure, otherwise Unity won't find it.
return path.Replace("\\", "/");
}
///
/// Returns whether a path corresponds with an asset inside the packages folder.
///
/// The asset path to check.
/// Whether the path corresponds with an asset inside the packages folder.
public static bool IsPackagePath(this string assetPath)
{
if (string.IsNullOrEmpty(assetPath))
throw new NullOrEmptyException(nameof(assetPath));
return assetPath.StartsWith("Packages/");
}
}
}