Exemplo n.º 1
0
        public static AssetMoveResult OnWillMoveAsset(string sourcePath, string destinationPath)
        {
            var assetMoveResult = AssetMoveResult.DidNotMove;

            try
            {
                if (!_currentlyMovingAssets.Contains(sourcePath))
                {
                    if (!SmartNSSettings.SettingsFileExists())
                    {
                        SmartNSSettings.GetOrCreateSettings();
                    }

                    var smartNSSettings = SmartNSSettings.GetSerializedSettings();
                    var updateNamespacesWhenMovingScripts = smartNSSettings.FindProperty("m_UpdateNamespacesWhenMovingScripts").boolValue;
                    var enableDebugLogging = smartNSSettings.FindProperty("m_EnableDebugLogging").boolValue;
                    _shouldWriteDebugLogInfo = enableDebugLogging;

                    if (updateNamespacesWhenMovingScripts)
                    {
                        // We only intercept C# scripts.
                        if (sourcePath.EndsWith(".cs"))
                        {
                            WriteDebug("Moving asset. Source path: " + sourcePath + ". Destination path: " + destinationPath + ".");

                            // Perform operations on the asset and set the value of 'assetMoveResult' accordingly.

                            var validationMessage = AssetDatabase.ValidateMoveAsset(sourcePath, destinationPath);

                            if (string.IsNullOrWhiteSpace(validationMessage))
                            {
                                // Keep track of the fact that we're moving this asset, because OnWillMoveAsset will be called again
                                // when we call MoveAsset below. We keep track of it to avoid recursing into this code again.
                                _currentlyMovingAssets.Add(sourcePath);

                                // We can move this. So go ahead.
                                AssetDatabase.MoveAsset(sourcePath, destinationPath);


                                // Now post-process the moved script to clean up its namespace.
                                ProcessNamespaceForScriptAtPath(destinationPath);

                                assetMoveResult = AssetMoveResult.DidMove;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.LogError(string.Format("Something went really wrong trying to execute SmartNS: {0}", ex.Message));
                Debug.LogError(string.Format("SmartNS Failure Stack Trace: {0}", ex.StackTrace));
            }
            finally
            {
                _currentlyMovingAssets.Remove(sourcePath);
            }

            return(assetMoveResult);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Intercepts the creation of assets, looking for new .cs scripts, and inserts a namespace.
        /// </summary>
        /// <param name="path"></param>
        public static void OnWillCreateAsset(string path)
        {
            try
            {
                // We only intercept C# scripts.
                if (!path.EndsWith(".cs.meta"))
                {
                    return;
                }


                path = path.Replace(".meta", "");
                path = path.Trim();
                int index = path.LastIndexOf(".");
                if (index < 0)
                {
                    return;
                }

                var smartNSSettings    = SmartNSSettings.GetSerializedSettings();
                var enableDebugLogging = smartNSSettings.FindProperty("m_EnableDebugLogging").boolValue;
                _shouldWriteDebugLogInfo = enableDebugLogging;

                ProcessNamespaceForScriptAtPath(path);
            }
            catch (Exception ex)
            {
                Debug.LogError(string.Format("Something went really wrong trying to execute SmartNS: {0}", ex.Message));
                Debug.LogError(string.Format("SmartNS Failure Stack Trace: {0}", ex.StackTrace));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the list of directories that should be ignored.
        /// </summary>
        /// <returns></returns>
        public static HashSet <string> GetIgnoredDirectories()
        {
            var retval          = new HashSet <string>();
            var smartNSSettings = SmartNSSettings.GetSerializedSettings();
            var directoryDenyListSettingsValue = smartNSSettings.FindProperty("m_DirectoryIgnoreList").stringValue;

            foreach (var directoryPathPart in directoryDenyListSettingsValue.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
            {
                var dpp = directoryPathPart.Trim();
                if (dpp.StartsWith("/"))
                {
                    dpp = dpp.Remove(0, 1);
                }
                if (!dpp.StartsWith("Assets"))
                {
                    dpp = "Assets/" + dpp;
                }

                var fullDenyDirectoryPath = Application.dataPath.Substring(0, Application.dataPath.LastIndexOf("Assets")) + dpp;
                var di = new DirectoryInfo(fullDenyDirectoryPath);
                if (di.Exists)
                {
                    retval.Add(di.FullName);
                    foreach (var subDir in di.GetDirectories("*.*", SearchOption.AllDirectories))
                    {
                        retval.Add(subDir.FullName);
                    }
                }
                else
                {
                    Debug.LogWarning(string.Format("Directory {0} in SmartNS Project Setting's Directory Ignore List was not a valid directory.", dpp));
                }
            }

            return(retval);
        }
Exemplo n.º 4
0
        void OnGUI()
        {
            if (string.IsNullOrWhiteSpace(_baseDirectory))
            {
                _baseDirectory = GetClickedDirFullPath();
            }

            if (string.IsNullOrWhiteSpace(_baseDirectory))
            {
                _baseDirectory = "Assets";
            }

            GUILayout.Label("SmartNS Bulk Namespace Conversion", EditorStyles.boldLabel);


            int yPos = 20;

            GUI.Box(new Rect(0, yPos, position.width, 220), @"This tool will automatically add or correct the namespaces on any C# scripts in your project, making them consistent with your SmartNS settings.

BE CAREFUL!

This is a potentially destrucive tool. It will modify the actual file contents on your script, possibly incorrectly. There is no 'Undo'. Don't use this tool unless you have an easy way to revert the changes it makes, such as version control.

See the Documentation.txt file for more information on this. But in general, you probably shouldn't run this on 3rd-party code you got from the asset store.");

            yPos += 220;


            GUI.Box(new Rect(0, yPos, position.width, 100), @"Instructions:
 - Click the 'Base Directory' button to choose the base directory. Only scripts in, or under, that directory will be processed.
 - The click 'Begin Namespace Conversion'
 - Look in the Unity Console log for errors and other information on the progress.");

            yPos += 100;

            var baseDirectoryLabel = new GUIContent(string.Format("Base Directory: {0}", _baseDirectory), "SmartNS will search all scripts in, or below, this directory. Use this to limit the search to a subdirectory.");

            if (GUI.Button(new Rect(3, yPos, position.width - 6, 20), baseDirectoryLabel))
            {
                var fullPath = EditorUtility.OpenFolderPanel("Choose root folder", _baseDirectory, "");
                _baseDirectory = fullPath.Replace(Application.dataPath, "Assets").Trim();
                if (string.IsNullOrWhiteSpace(_baseDirectory))
                {
                    _baseDirectory = "Assets";
                }
            }


            yPos += 30;



            if (!_isProcessing)
            {
                var submitButtonContent = new GUIContent("Begin Namespace Conversion", "Begin processing scripts");
                var submitButtonStyle   = new GUIStyle(GUI.skin.button);
                submitButtonStyle.normal.textColor = new Color(0, .5f, 0);
                if (GUI.Button(new Rect(position.width / 2 - 350 / 2, yPos, 350, 30), submitButtonContent, submitButtonStyle))
                {
                    string assetBasePath = (string.IsNullOrWhiteSpace(_baseDirectory) ? "Assets" : _baseDirectory).Trim();
                    if (!assetBasePath.EndsWith("/"))
                    {
                        assetBasePath += "/";
                    }


                    _assetsToProcess = GetAssetsToProcess(assetBasePath);

                    if (EditorUtility.DisplayDialog("Are you sure?",
                                                    string.Format("This will process a total of {0} scripts found in or under the '{1}' directory, updating their namespaces based on your current SmartNS settings. You should back up your project before doing this, in case something goes wrong. Are you sure you want to do this?", _assetsToProcess.Count, assetBasePath),
                                                    string.Format("I'm sure. Process {0} scripts", _assetsToProcess.Count),
                                                    "Cancel"))
                    {
                        var smartNSSettings = SmartNSSettings.GetSerializedSettings();
                        _scriptRootSettingsValue         = smartNSSettings.FindProperty("m_ScriptRoot").stringValue;
                        _prefixSettingsValue             = smartNSSettings.FindProperty("m_NamespacePrefix").stringValue;
                        _universalNamespaceSettingsValue = smartNSSettings.FindProperty("m_UniversalNamespace").stringValue;
                        _useSpacesSettingsValue          = smartNSSettings.FindProperty("m_IndentUsingSpaces").boolValue;
                        _numberOfSpacesSettingsValue     = smartNSSettings.FindProperty("m_NumberOfSpaces").intValue;
                        _directoryDenyListSettingsValue  = smartNSSettings.FindProperty("m_DirectoryIgnoreList").stringValue;
                        _enableDebugLogging = smartNSSettings.FindProperty("m_EnableDebugLogging").boolValue;

                        // Cache this once now, for performance reasons.
                        _ignoredDirectories = SmartNS.GetIgnoredDirectories();



                        _progressCount = 0;
                        _isProcessing  = true;
                    }
                }
            }


            if (_isProcessing)
            {
                var cancelButtonContent = new GUIContent("Cancel", "Cancel script conversion");
                var cancelButtonStyle   = new GUIStyle(GUI.skin.button);
                cancelButtonStyle.normal.textColor = new Color(.5f, 0, 0);
                if (GUI.Button(new Rect(position.width / 2 - 50 / 2, yPos, 50, 30), cancelButtonContent, cancelButtonStyle))
                {
                    _isProcessing  = false;
                    _progressCount = 0;
                    AssetDatabase.Refresh();
                    Log("Cancelled");
                }

                yPos += 40;

                if (_progressCount < _assetsToProcess.Count)
                {
                    EditorGUI.ProgressBar(new Rect(3, yPos, position.width - 6, 20), (float)_progressCount / (float)_assetsToProcess.Count, string.Format("Processing {0} ({1}/{2})", _assetsToProcess[_progressCount], _progressCount, _assetsToProcess.Count));
                    Log("Processing " + _assetsToProcess[_progressCount]);

                    SmartNS.UpdateAssetNamespace(_assetsToProcess[_progressCount],
                                                 _scriptRootSettingsValue,
                                                 _prefixSettingsValue,
                                                 _universalNamespaceSettingsValue,
                                                 _useSpacesSettingsValue,
                                                 _numberOfSpacesSettingsValue,
                                                 _directoryDenyListSettingsValue,
                                                 _enableDebugLogging,
                                                 directoryIgnoreList: _ignoredDirectories);

                    _progressCount++;
                }
                else
                {
                    // We done.
                    _isProcessing       = false;
                    _ignoredDirectories = null;
                    _progressCount      = 0;
                    AssetDatabase.Refresh();
                    Debug.Log("Bulk Namespace Conversion complete.");
                }
            }
        }
Exemplo n.º 5
0
 public override void OnActivate(string searchContext, VisualElement rootElement)
 {
     // This function is called when the user clicks on the SmartNSSettings element in the Settings window.
     m_SmartNSSettings = SmartNSSettings.GetSerializedSettings();
 }
Exemplo n.º 6
0
        private static void ProcessNamespaceForScriptAtPath(string path, HashSet <string> directoryIgnoreList = null)
        {
            // We depend on a properly created Project Settings file. Create it now, if it doesn't exist.
            if (!SmartNSSettings.SettingsFileExists())
            {
                SmartNSSettings.GetOrCreateSettings();
            }

            var smartNSSettings                 = SmartNSSettings.GetSerializedSettings();
            var scriptRootSettingsValue         = smartNSSettings.FindProperty("m_ScriptRoot").stringValue;
            var prefixSettingsValue             = smartNSSettings.FindProperty("m_NamespacePrefix").stringValue;
            var universalNamespaceSettingsValue = smartNSSettings.FindProperty("m_UniversalNamespace").stringValue;
            var useSpacesSettingsValue          = smartNSSettings.FindProperty("m_IndentUsingSpaces").boolValue;
            var numberOfSpacesSettingsValue     = smartNSSettings.FindProperty("m_NumberOfSpaces").intValue;
            //var defaultScriptCreationDirectorySettingsValue = smartNSSettings.FindProperty("m_DefaultScriptCreationDirectory").stringValue;
            var directoryDenyListSettingsValue = smartNSSettings.FindProperty("m_DirectoryIgnoreList").stringValue;
            var enableDebugLogging             = smartNSSettings.FindProperty("m_EnableDebugLogging").boolValue;



            /*
             * This has been commented out. It was causing errors when moving files. I'm not sure why yet, but
             * moving a file in this was would always produce a "File couldn't be read!" error.
             *
             * // If this script was created directly under the Assets folder, and the settings tell us a default script location
             * // (other than "Assets") move it there.
             * if (!string.IsNullOrWhiteSpace(defaultScriptCreationDirectorySettingsValue))
             * {
             *  var trimmedDefaultDir = defaultScriptCreationDirectorySettingsValue.Trim();
             *
             *  if (path.Split('/').Length == 2)
             *  {
             *      var destinationDirectory = trimmedDefaultDir;
             *      if (!destinationDirectory.StartsWith("Assets"))
             *      {
             *          destinationDirectory = string.Join(PathSeparator, "Assets", destinationDirectory);
             *      }
             *      // Replace anu double-slashes.
             *      destinationDirectory = Regex.Replace(destinationDirectory, "//", "/");
             *
             *      // Make sure the directory exists
             *      if (AssetDatabase.IsValidFolder(destinationDirectory))
             *      {
             *          var preferredPath = path.Replace("Assets", destinationDirectory);
             *
             *          var moveAssetTestResult = AssetDatabase.ValidateMoveAsset(path, preferredPath);
             *          if (string.IsNullOrWhiteSpace(moveAssetTestResult))
             *          {
             *              WriteDebug(string.Format("Moving file from {0} to Default Script Creation Directory: {1}", path, preferredPath));
             *              AssetDatabase.MoveAsset(path, preferredPath);
             *
             *              AssetDatabase.Refresh();
             *
             *              return;
             *          }
             *          else
             *          {
             *              Debug.LogError(string.Format("SmartNS unable to move script to default script creation directory, '{0}': {1}", destinationDirectory, moveAssetTestResult));
             *          }
             *      }
             *      else
             *      {
             *          Debug.LogError(string.Format("SmartNS unable to move script to default script creation directory, '{0}', because the folder does not exist. Make sure the 'Default Script Creation Directory' specified in the Project Settings is valid.", destinationDirectory));
             *      }
             *  }
             * }
             */


            UpdateAssetNamespace(path,
                                 scriptRootSettingsValue,
                                 prefixSettingsValue,
                                 universalNamespaceSettingsValue,
                                 useSpacesSettingsValue,
                                 numberOfSpacesSettingsValue,
                                 directoryDenyListSettingsValue,
                                 enableDebugLogging,
                                 directoryIgnoreList);


            // Without this, the file won't update in Unity, and won't look right.
            AssetDatabase.ImportAsset(path);
        }