Exemplo n.º 1
1
        public bool PushDir(DirectoryInfo localDir, List <FileInfoWithPatchOptions> patchFiles, string remotePath, string linkPath, bool isDMFR)
        {
            VSSItem remoteDir   = VSSDB.get_VSSItem(remotePath);
            VSSItem linkRootDir = VSSDB.get_VSSItem(linkPath);

            foreach (VSSItem item in linkRootDir.Items)
            {
                if (item.Type == 0 && item.Name.Equals(localDir.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    item.Destroy();
                    sender($"{item.Spec} найдена в {linkRootDir.Spec} и удалена!");
                    break;
                }
            }
            VSSItem linkDir = linkRootDir.NewSubproject(localDir.Name);

            sender($"{linkDir.Spec} создана в {linkRootDir.Spec}");

            string dbScriptsRep = Properties.Settings.Default.ScriptsSubdir;
            string infaRep      = Properties.Settings.Default.InfaSubdir;
            string repDir       = Properties.Settings.Default.RemoteRoot;


            string mask;

            string[]      patchRootDirs;
            List <string> patchesToFindObject = new List <string>();

            bool patchSearchCompleted = false;

            foreach (FileInfoWithPatchOptions fi in patchFiles)
            {
                string   fromPatchPath = fi.FileInfo.Directory.FullName.Substring(localDir.FullName.Length);
                string[] dirs          = fromPatchPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

                sender($"Создаем папки, если их нет: { string.Join(",", dirs) }");

                bool     found;
                IVSSItem currDir = linkDir;

                if (fi.AddToPatch)
                {
                    foreach (string dir in dirs)
                    {
                        found = false;
                        foreach (VSSItem currSubDir in currDir.Items)
                        {
                            if (currSubDir.Type == 0 && currSubDir.Name.Equals(dir, StringComparison.InvariantCultureIgnoreCase))
                            {
                                found = true;
                                sender($"{currSubDir.Spec} найдена в {currDir.Spec}");
                                break;
                            }
                        }

                        if (!found)
                        {
                            string prevDir = currDir.Spec;
                            currDir = currDir.NewSubproject(dir);
                            sender($"{currDir.Spec} создана в {prevDir}");
                        }
                    }
                }

                if (fi.AddInRepDir)
                {
                    string sourceFolder;
                    string repsubdir;
                    //если это скрипт
                    if (fi.FileInfo.Extension.Equals(".sql", StringComparison.InvariantCultureIgnoreCase))
                    {
                        sender($"Ищем в {fi.FileInfo.FullName} по шаблону {dbScriptsRep}\\\\([^\\\\]+)");
                        sourceFolder = Regex.Match(fi.FileInfo.FullName, $"{dbScriptsRep}\\\\([^\\\\]+)").Groups[1].Value;
                        repsubdir    = dbScriptsRep;
                    }
                    else
                    {
                        sender($"Ищем в {fi.FileInfo.FullName} по шаблону {infaRep}\\\\([^\\\\]+)");
                        sourceFolder = Regex.Match(fi.FileInfo.FullName, $"{infaRep}\\\\([^\\\\]+)").Groups[1].Value;
                        repsubdir    = infaRep;
                    }
                    sender($"Ищем в папке {sourceFolder}");

                    if (FirstInEntireBase($"{repDir}/{repsubdir}/{sourceFolder}", fi.FileInfo.Name, -1, false, out string match))
                    {
                        IVSSItem repItem = VSSDB.get_VSSItem(match);
                        CreateLink(repItem, currDir);
                    }
                    else
                    {
                        if (!patchSearchCompleted)
                        {
                            if (isDMFR)
                            {
                                mask          = Properties.Settings.Default.DMFRSubstring;
                                patchRootDirs = Properties.Settings.Default.PatchesRootDirDMFR.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                            }
                            else
                            {
                                mask          = Properties.Settings.Default.DWH4DMSubstring;
                                patchRootDirs = Properties.Settings.Default.PatchesRootDirDWH4DM.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                            }

                            sender($"Ищем {mask} в { string.Join(",", patchRootDirs) }");

                            foreach (string root in patchRootDirs)
                            {
                                try
                                {
                                    foreach (string patch in AllInEntireBase(root, mask, true, -1))
                                    {
                                        patchesToFindObject.Add(patch);
                                    }
                                }
                                catch { }
                            }

                            patchSearchCompleted = true;
                        }

                        sender($"Ищем {fi.FileInfo.Name} в патчах");
                        foreach (string root in patchesToFindObject)
                        {
                            if (FirstInEntireBase(root, fi.FileInfo.Name, -1, false, out string prevVersion))
                            {
                                IVSSItem prevItem = VSSDB.get_VSSItem(prevVersion);
                                CreateLink(prevItem, currDir);
                                break;
                            }
                        }
                    }
                }

                PushFile(currDir.Spec, fi.FileInfo.Directory.FullName, fi.FileInfo.Name, localDir.Name, out VSSItem item);
            }

            return(true);
        }
Exemplo n.º 2
0
 public static int GetItems(IVSSItem originalItem)
 {
     int total = 0;
     foreach (IVSSItem subItem in originalItem.get_Items(false))
     {
         if (subItem.Type == VSSITEM_FILE && subItem.IsCheckedOut == VSSFILE_CHECKEDOUT_ME)
         {
             Console.WriteLine(subItem.Spec);
             total++;
         }
         else if (subItem.Type == VSSITEM_PROJECT)
         {
             total += GetItems(subItem);
         }
     }
     return total;
 }
Exemplo n.º 3
0
        private void ItemDiff(IVSSItem ssItem)
        {
            Log(Level.Verbose, "History of \"{0}\"...", ssItem.Name);

            if (FromLabel != null || ToLabel != null) {
                DiffByLabel(ssItem);
            } else {
                DiffByDate(ssItem);
            }
        }
Exemplo n.º 4
0
 public void Add(IVSSItem i) {
     BaseAdd(i.Name, i);
 }
Exemplo n.º 5
0
 private void CreateLink(IVSSItem sourceItem, IVSSItem destDir)
 {
     destDir.Share((VSSItem)sourceItem, destDir.Name, (int)VSSFlags.VSSFLAG_GETNO);
     sender($"Создана ссылка для файла {sourceItem.Spec} в {destDir.Spec}");
 }
Exemplo n.º 6
0
        private void TestPatchDirRec(IVSSItem patchCurrDir, string localPath, IVSSItem repCurrDir, ref bool res, ref string errDesc)
        {
            foreach (IVSSItem linkItem in patchCurrDir.Items)
            {
                if ((VSSItemType)linkItem.Type == VSSItemType.VSSITEM_PROJECT)
                {
                    try
                    {
                        sender($"Проверка папки {linkItem.Spec}");
                        IVSSItem repNextDir   = VSSDB.get_VSSItem($"{repCurrDir.Spec}/{linkItem.Name}");
                        string   localNextDir = Path.Combine(localPath, linkItem.Name);
                        sender($"Папка {repNextDir.Spec} найдена");
                        TestPatchDirRec(linkItem, localNextDir, repNextDir, ref res, ref errDesc);
                    }
                    catch (System.Runtime.InteropServices.COMException exc)
                    {
                        if (!IsFileNotFoundError(exc))
                        {
                            throw exc;
                        }
                        else
                        {
                            sender($"Папка {repCurrDir.Spec}/{linkItem.Name} не найдена");
                        }
                    }
                }
                else
                {
                    if (linkItem.Name.StartsWith("SCRIPT_", StringComparison.InvariantCultureIgnoreCase) ||
                        Regex.IsMatch(linkItem.Name, "WF_.*_FIX.xml", RegexOptions.IgnoreCase))
                    {
                        sender($"Файл {linkItem.Spec} пропущен");
                    }
                    else
                    {
                        try
                        {
                            IVSSItem repItem = VSSDB.get_VSSItem($"{repCurrDir.Spec}/{linkItem.Name}");
                            sender($"Файл {repItem.Spec} найден");

                            string localItem = Path.Combine(localPath, linkItem.Name);
                            sender($"Сравнение версий. Локальный файл {localItem}");

                            if (!CompareItems(repItem, linkItem, localItem, out IVSSItem lastItem))
                            {
                                res = false;
                                sender($"Разные версии у файлов {linkItem.Spec} и {repItem.Spec}. Последняя версия: {lastItem.Spec}");
                                errDesc += $"Несоответствие версии для файла {linkItem.Spec};{linkItem.VersionNumber}. Последняя версия: {lastItem.Spec};{lastItem.VersionNumber}" + Environment.NewLine;
                            }
                            else
                            {
                                sender($"Одинаковые версии у файлов {linkItem.Spec} и {repItem.Spec}");
                            }
                        }
                        catch (System.Runtime.InteropServices.COMException exc)
                        {
                            if (!IsFileNotFoundError(exc))
                            {
                                throw exc;
                            }
                            else
                            {
                                errDesc += $"Файл {linkItem.Spec} не найден в репозитории" + Environment.NewLine;
                                sender($"Файл {repCurrDir.Spec}/{linkItem.Name} не найден в репозитории");
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        private void ItemDiff(IVSSItem ssItem)
        {
            Log.LogMessage(MessageImportance.Normal, "History of {0}...", ssItem.Name);

            if (FromLabel != null || ToLabel != null)
            {
                DiffByLabel(ssItem);
            }
            else
            {
                DiffByDate(ssItem);
            }
        }
Exemplo n.º 8
0
        private void DiffByLabel(IVSSItem ssItem)
        {
            bool startLogging = false;
            bool stopLogging = false;

            string user = User != null ? User.ToLower(CultureInfo.InvariantCulture) : null;

            foreach (IVSSVersion version in ssItem.get_Versions(VersionFlags))
            {
                // VSS returns the versions in descending order, meaning the
                // most recent versions appear first.
                if (ToLabel == null || version.Action.StartsWith(string.Format("Labeled '{0}'", ToLabel)))
                {
                    startLogging = true;
                }
                if (FromLabel != null && version.Action.StartsWith(string.Format("Labeled '{0}'", FromLabel)))
                {
                    stopLogging = true;
                }
                if (startLogging && !stopLogging)
                {
                    // if user was specified, then skip changes that were not 
                    // performed by that user
                    if (user != null && version.Username.ToLower(CultureInfo.InvariantCulture) != user)
                    {
                        continue;
                    }

                    LogChange(version);
                }
            }
        }
Exemplo n.º 9
0
 private bool IsProject(IVSSItem item) {
     return item.Type == (int) VSSItemType.VSSITEM_PROJECT;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Attempts to connect to the SourceSafe Database and
        /// load the specified item, or version of the item, if specified.
        /// </summary>
        protected void ConnectToDatabase()
        {
            _database = new VSSDatabase();
            _database.Open(new FileInfo(DatabasePath).FullName, UserName, Password);

            _item = _database.get_VSSItem(Path, false);
            if (Version != null)
            {
                _item = _item.get_Version(Version);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Scans the Project Item for deleted files and removes their local
        /// copies from the local image of the project. Obeys the recursive setting
        /// (and thus optionally calls itself recursively).
        /// </summary>
        /// <param name="item">The VSS Item (project) to check for deletions</param>
        /// <param name="localPathPrefix">The path to the folder of the item being processed</param>
        public void RemoveDeletedFromLocalImage(IVSSItem item, string localPathPrefix) {
            IVSSItems items = item.get_Items(true);

            Hashtable deletedTable = BuildDeletedTable(items);
        
            IEnumerator ie = items.GetEnumerator();
            while (ie.MoveNext()) {
                IVSSItem i = (IVSSItem) ie.Current;
                string localPath = System.IO.Path.Combine(localPathPrefix, i.Name);

                if (IsTrulyDeleted(deletedTable, i) && Exists(localPath)) {
                    SetToWriteable(localPath);
                    Delete(localPath);
                } else {
                    if (IsProject(i) && Recursive) {
                        RemoveDeletedFromLocalImage(i, System.IO.Path.Combine(localPathPrefix, i.Name));
                    }
                }
            }
        }
Exemplo n.º 12
0
 private bool IsTrulyDeleted(Hashtable deletedTable, IVSSItem item) {
     return (bool) deletedTable[item.Name];
 }
Exemplo n.º 13
0
        /// <summary>
        /// Opens the Source Safe database and sets the reference to the specified
        /// item and version.
        /// </summary>
        protected void Open()
        {
            try {
                _database = new VSSDatabase();
                _database.Open(DBPath.FullName, UserName, Password);
            } catch (Exception ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                    "Failed to open database \"{0}\".", DBPath.FullName),
                    Location, ex);
            }

            try {
                // get the reference to the specified project item
                // and version
                _item = _database.get_VSSItem(Path, false);
                if (Version != null) {
                    _item = _item.get_Version(Version);
                }
            } catch (Exception ex) {
                throw new BuildException("The \"path\" and/or \"version\" is not valid.",
                    Location, ex);
            }
        }
Exemplo n.º 14
0
        public bool TestPatchDir(string remotePath, out string errDesc, DirectoryInfo localDir)
        {
            sender($"Проверка патча {remotePath}");
            IVSSItem patchStartDir = VSSDB.get_VSSItem(remotePath);

            sender($"Патч {remotePath} найден");

            string startRepPath = Properties.Settings.Default.RemoteRoot;

            sender($"Папка {Properties.Settings.Default.RemoteRoot} найдена");
            List <string> versionMismatches = new List <string>();

            bool res = true;

            errDesc = "";

            string scriptsSubdir = Properties.Settings.Default.ScriptsSubdir;
            string infaSubdir    = Properties.Settings.Default.InfaSubdir;

            List <IVSSItem> startItemsScripts = new List <IVSSItem>();
            List <IVSSItem> startItemsInfa    = new List <IVSSItem>();

            sender($"Находим папку {startRepPath}/{scriptsSubdir}");
            IVSSItem scriptsRepDir = VSSDB.get_VSSItem($"{startRepPath}/{scriptsSubdir}");

            sender($"Находим папку {startRepPath}/{infaSubdir}");
            IVSSItem infaRepDir = VSSDB.get_VSSItem($"{startRepPath}/{infaSubdir}");

            try
            {
                foreach (string itemSpec in AllInEntireBase(patchStartDir.Spec, scriptsSubdir, false, -1))
                {
                    sender($"Нашли папку со скриптами в патче {itemSpec}");
                    startItemsScripts.Add(VSSDB.get_VSSItem(itemSpec));
                }
            }
            catch (FileNotFoundException)
            { }

            try
            {
                foreach (string itemSpec in AllInEntireBase(patchStartDir.Spec, infaSubdir, false, -1))
                {
                    sender($"Нашли папку информатики в патче {itemSpec}");
                    startItemsInfa.Add(VSSDB.get_VSSItem(itemSpec));
                }
            }
            catch (FileNotFoundException)
            { }

            foreach (IVSSItem subpatchItem in startItemsScripts)
            {
                int    patchIndex = subpatchItem.Spec.IndexOf(localDir.Name, StringComparison.InvariantCultureIgnoreCase) + localDir.Name.Length;
                string subPath    = subpatchItem.Spec.Substring(patchIndex).Replace('/', '\\');

                string currLocalDir = localDir.FullName + subPath;

                sender($"Локальная папка {currLocalDir} (Путь: {localDir.FullName}, подпуть: {subPath})");

                if ((VSSItemType)subpatchItem.Type == VSSItemType.VSSITEM_PROJECT)
                {
                    TestPatchDirRec(subpatchItem, currLocalDir, scriptsRepDir, ref res, ref errDesc);
                }
            }

            foreach (IVSSItem subpatchItem in startItemsInfa)
            {
                int    patchIndex = subpatchItem.Spec.IndexOf(localDir.Name, StringComparison.InvariantCultureIgnoreCase) + localDir.Name.Length;
                string subPath    = subpatchItem.Spec.Substring(patchIndex).Replace('/', '\\');

                string currLocalDir = localDir.FullName + subPath;

                sender($"Локальная папка {currLocalDir} (Путь: {localDir.FullName}, подпуть: {subPath})");

                if ((VSSItemType)subpatchItem.Type == VSSItemType.VSSITEM_PROJECT)
                {
                    TestPatchDirRec(subpatchItem, currLocalDir, infaRepDir, ref res, ref errDesc);
                }
            }

            foreach (string file in versionMismatches)
            {
                errDesc += "Несоответствие версий в файле " + file + Environment.NewLine;
            }

            res &= CheckPatchErrors(localDir, ref errDesc);

            return(res);
        }
Exemplo n.º 15
0
        private bool CompareItems(IVSSItem repItem, IVSSItem linkItem, string linkItemLocal, out IVSSItem lastItem)
        {
            int maxVersion      = -1;
            int linkItemVersion = -1;

            lastItem = null;

            foreach (IVSSItem item in repItem.Links)
            {
                if (item.VersionNumber > maxVersion)
                {
                    maxVersion = item.VersionNumber;
                    lastItem   = item;
                }

                if (item.Spec.Equals(linkItem.Spec, StringComparison.InvariantCultureIgnoreCase))
                {
                    linkItemVersion = item.VersionNumber;
                }
            }

            if (linkItemVersion == maxVersion)
            {
                return(true);
            }

            if (!repItem.IsDifferent[linkItemLocal])
            {
                sender($"Файлы {repItem.Spec} и {linkItem.Spec} идентичны");
                return(true);
            }

            return(false);
        }
Exemplo n.º 16
0
 private bool IsTrulyDeleted(Hashtable deletedTable, IVSSItem item)
 {
     return((bool)deletedTable[item.Name]);
 }
Exemplo n.º 17
0
        private static void ApplyTag(IVSSItem vssFile, SvnClient svnClient, IVSSVersion vssVersion, Tag tag)
        {
            var copyArgs = new SvnCopyArgs
            {
                LogMessage =
                    string.Format("Released {0}\n{1}", vssVersion.Label, vssVersion.LabelComment)
            };

            migrateLog.DebugFormat("------------------------------------");
            migrateLog.DebugFormat(string.Format("Setting Tag:"));
            migrateLog.DebugFormat(string.Format("Label: {0}", vssVersion.Label));
            migrateLog.DebugFormat(string.Format("Comment: {0}", vssVersion.LabelComment));
            migrateLog.DebugFormat(string.Format("from Url: {0}", tag.fromUrlString));
            migrateLog.DebugFormat(string.Format("to Url: {0}", tag.tagString));


            try
            {
                svnClient.RemoteCopy(SvnTarget.FromString(tag.fromUrlString),
                                     new Uri(tag.tagString),
                                     copyArgs);

                CounterfeitRevProps(svnClient, SvnTarget.FromUri(new Uri(tag.tagString)), vssVersion);
            }


            catch (SvnFileSystemException e)
            {
                //tags with same names get handled here

                if (e.ToString().Contains("already exists"))
                {
                    int index = tag.tagString.IndexOf(svnTAG) + svnTAG.Length + 1;
                    //FIXME: correct calculation of // and /
                    string newstring = tag.tagString.Insert(index, vssFile.Parent.Name + "_");
                    tag.tagString = newstring;
                    migrateLog.DebugFormat("Tag already existing, adding parent name ...");

                    ApplyTag(vssFile, svnClient, vssVersion, tag);

                    return;
                }

                migrateLog.ErrorFormat("Error: Line was: " + tag.fromUrlString);
                migrateLog.ErrorFormat(e.ToString());
                migrateLog.InfoFormat(String.Format("Fallback, tagging repository successful: "
                                                    + (svnClient.RemoteCopy(
                                                           SvnTarget.FromString(String.Format("{0}/{1}", svnURL,
                                                                                              svnPROJ)),
                                                           new Uri(tag.tagString)
                                                           , copyArgs))));


                CounterfeitRevProps(svnClient, SvnTarget.FromUri(new Uri(tag.tagString)), vssVersion);
            }

            catch (Exception e)
            {
                migrateLog.ErrorFormat(e.ToString());
                //Console.Out.WriteLine("Press a key to continue");
                //Console.ReadKey();
            }

            migrateLog.DebugFormat("------------------------------------");
        }
Exemplo n.º 18
0
 private bool IsProject(IVSSItem item)
 {
     return(item.Type == (int)VSSItemType.VSSITEM_PROJECT);
 }
Exemplo n.º 19
0
        private static void GetFileVersion(IVSSItem vssFile, IVSSVersion vssVersion, SvnClient svnClient)
        {
            numFilesHandled++;
            string dir = string.Format("{0}{1}", repoDIR, vssFile.Spec.Substring(1)).Replace("/", "\\");

            dir = Path.GetDirectoryName(dir);
            string  filePath    = Path.Combine(dir, vssFile.Name);
            VSSItem versionItem = vssVersion.VSSItem;

            try
            {
                migrateLog.DebugFormat("Fetching VSSItem: {0}, Version: {1}", versionItem.Spec, versionItem.VersionNumber);

                if (versionItem.Type != (int)VSSItemType.VSSITEM_PROJECT)
                {
                    versionItem.Get(ref filePath,
                                    (int)
                                    (VSSFlags.VSSFLAG_USERRONO | VSSFlags.VSSFLAG_CMPFAIL | VSSFlags.VSSFLAG_GETYES |
                                     VSSFlags.VSSFLAG_REPREPLACE | VSSFlags.VSSFLAG_TIMEMOD));

                    //kill them *.scc files worth for nothing
                    string[] files = Directory.GetFiles(dir, "*.scc", SearchOption.TopDirectoryOnly);
                    foreach (string file in files)
                    {
                        File.SetAttributes(file, FileAttributes.Normal);
                        File.Delete(file);
                    }
                }

                else
                {
                    Directory.CreateDirectory(filePath);
                }


                //This seems to fail rather often on binary files and directories, so dont let us use it on them

                if (versionItem.Type != (int)VSSItemType.VSSITEM_PROJECT)
                {
                    if (!versionItem.Binary)
                    {
                        migrateLog.DebugFormat("Diffing ...");
                        if (versionItem.get_IsDifferent(filePath))
                        {
                            migrateLog.WarnFormat(
                                "Files should not be different for version {0}; possible corruption in file {1}:{0}",
                                versionItem.VersionNumber, versionItem.Spec);
                        }
                    }
                }
            }
            catch (COMException e)
            {
                if (e.ErrorCode == -2147166575)
                {
                    // VSS file's checkbox "keep only latest version" is checked therefore no file could be fetched
                    // so that calling versionItem.Get(...) results in an exception
                    migrateLog.WarnFormat(
                        "Version {0} of file {1} not stored in VSS. File has option 'Keep only latest version' (see file's properties) enabled in VSS",
                        versionItem.VersionNumber, versionItem.Spec);
                }
                else
                {
                    throw;
                }
            }

            VssBindingRemover.RemoveBindings(filePath);

            Collection <SvnStatusEventArgs> svnStatus;

            svnClient.GetStatus(filePath, out svnStatus);

            if (svnStatus.Count == 1)
            {
                SvnStatus fileStatus = svnStatus[0].LocalContentStatus;
                if (fileStatus == SvnStatus.Normal)
                {
                    migrateLog.WarnFormat("No modification detected for {0}:{1}", vssVersion.VSSItem.Spec,
                                          vssVersion.VersionNumber);
                    return;
                }
                if (fileStatus == SvnStatus.NotVersioned || fileStatus == SvnStatus.Incomplete ||
                    fileStatus == SvnStatus.Missing)
                {
                    try
                    {
                        svnClient.Add(filePath);
                    }
                    catch (SvnException e)
                    {
                        if (!e.ToString().Contains("already under version"))
                        {
                            throw;
                        }
                    }
                }
            }
            else
            {
                //Should never get here because we're always looking for the results of an individual file; only display a message
                migrateLog.WarnFormat("Invalid svn status detected for {0}:{1}", vssVersion.VSSItem.Spec,
                                      vssVersion.VersionNumber);
                migrateLog.WarnFormat("Status count was: {0}", svnStatus.Count);
                return;
            }
            //simply continue as expected
        }
Exemplo n.º 20
0
        private  void ItemDiff(IVSSItem ssItem)
        {
            Log.LogMessage(MessageImportance.Low, "Processing item " + ssItem.Name);

            bool addVersion = true;
            int labeledVersion = 0;
            foreach (IVSSVersion version in ssItem.get_Versions(0))
            {
                // VSS returns the versions in descending order, meaning the
                // most recent versions appear first.
                string action = version.Action;

                // We found our version so stop adding versions to our list
                if (action.StartsWith("Labeled '" + _label + "'", StringComparison.InvariantCultureIgnoreCase))
                {
                    labeledVersion = version.VersionNumber;
                    addVersion = false;
                    //This is a bit annoying, it would be more efficient to break
                    //out of the loop here but VSS throws an exception !%?!
                    //http://tinyurl.com/nmct
                    //break;
                }
                if (addVersion == true)
                {
                    // Only add versions that have been added,created or checked in.  Ignore label actions.
                    if ((action.StartsWith("Add")) || (action.StartsWith("Create")) || (action.StartsWith("Check")))
                    {
                        Log.LogMessage(MessageImportance.Low, "Adding: " + version.VSSItem.Name);

                        // Build our XML Element with hopefully useful information.
                        XmlElement node = _outputDoc.CreateElement("item");
                        XmlAttribute attrib = _outputDoc.CreateAttribute("name");
                        attrib.Value = version.VSSItem.Name;
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("path");
                        attrib.Value = version.VSSItem.Spec;
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("action");
                        attrib.Value = action;
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("date");
                        attrib.Value = version.Date.ToString();
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("version");
                        attrib.Value = version.VersionNumber.ToString();
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("user");
                        attrib.Value = version.Username;
                        node.Attributes.Append(attrib);

                        attrib = _outputDoc.CreateAttribute("comment");
                        attrib.Value = version.Comment;
                        node.Attributes.Append(attrib);

                        _outputDoc.ChildNodes.Item(0).AppendChild(node);
                    }
                }
            }
        }
Exemplo n.º 21
0
        private void AddFileVersionToChangeset(IVSSItem vssFile, Int32 f_count, IVSSVersion vssVersion, bool isAdd)
        {
            string    filePath;
            VSSItem   versionItem;
            string    comment;
            Changeset thisChangeset;

            // define the working copy filename
            if (!this.IsPreview)
            {
                filePath = Path.Combine(this.SvnFullRepositoryPath, this.VssRelativeFilePaths[f_count]);
            }
            else
            {
                filePath = string.Empty;
            }

            //get version item to get the version of the file
            versionItem = vssFile.get_Version(vssVersion.VersionNumber);
            comment     = versionItem.VSSVersion.Comment;

            if (Changesets.ContainsKey(vssVersion.Date))
            {
                // using an existing change set
                thisChangeset = Changesets[vssVersion.Date];

                // different comment, so create a new change set anyway
                if (thisChangeset.Comment != comment)
                {
                    bool done = false;

                    //there are two different changes at the same time
                    //I'm not sure how this happened, but it did.
                    //make the date/time of this changeset after any existing changeset
                    thisChangeset = new Changeset()
                    {
                        Comment  = comment,
                        DateTime = vssVersion.Date,
                        Username = vssVersion.Username
                    };

                    //make sure not to try and add this entry if an entry with the time already exists
                    while (!done)
                    {
                        if (Changesets.ContainsKey(thisChangeset.DateTime))
                        {
                            thisChangeset.DateTime = thisChangeset.DateTime.AddSeconds(1);
                        }
                        else
                        {
                            done = true;
                        }
                    }

                    this.Changesets.Add(thisChangeset.DateTime, thisChangeset);
                }
            }
            else
            {
                // create a new change set
                thisChangeset = new Changeset()
                {
                    Comment  = comment,
                    DateTime = vssVersion.Date,
                    Username = vssVersion.Username
                };
                this.Changesets.Add(thisChangeset.DateTime, thisChangeset);
            }

            // add the file to the change set
            thisChangeset.Files.Add(new ChangesetFileInfo()
            {
                FilePath   = filePath,
                IsAdd      = isAdd,
                VssFile    = vssFile,
                VssVersion = vssVersion
            });
        }
Exemplo n.º 22
0
        private void DiffByDate(IVSSItem ssItem)
        {
            bool startLogging = false;
            bool stopLogging = false;

            string user = User != null ? User.ToLower(CultureInfo.InvariantCulture) : null;

            foreach (IVSSVersion version in ssItem.get_Versions(VersionFlags))
            {
                // VSS returns the versions in descending order, meaning the
                // most recent versions appear first.
                if (ToDate == DateTime.MinValue || version.Date <= ToDate)
                {
                    startLogging = true;
                }
                if (FromDate != DateTime.MinValue && FromDate > version.Date)
                {
                    stopLogging = true;
                }
                if (startLogging && !stopLogging)
                {
                    // if user was specified, then skip changes that were not 
                    // performed by that user
                    if (user != null && version.Username.ToLower(CultureInfo.InvariantCulture) != user)
                    {
                        continue;
                    }

                    LogChange(version);
                }
            }
        }
Exemplo n.º 23
0
 public static bool IsProject(this IVSSItem item)
 {
     return(item.Type == (int)VSSItemType.VSSITEM_PROJECT);
 }
Exemplo n.º 24
0
        private void ItemDiff(IVSSItem ssItem)
        {
            Log.LogMessage(MessageImportance.Low, "Processing item " + ssItem.Name);

            bool addVersion     = true;
            int  labeledVersion = 0;

            foreach (IVSSVersion version in ssItem.get_Versions(0))
            {
                // VSS returns the versions in descending order, meaning the
                // most recent versions appear first.
                string action = version.Action;

                // We found our version so stop adding versions to our list
                if (action.StartsWith("Labeled '" + _label + "'"))
                {
                    labeledVersion = version.VersionNumber;
                    addVersion     = false;
                    //This is a bit annoying, it would be more efficient to break
                    //out of the loop here but VSS throws an exception !%?!
                    //http://tinyurl.com/nmct
                    //break;
                }
                if (addVersion == true)
                {
                    // Only add versions that have been added,created or checked in.  Ignore label actions.
                    if ((action.StartsWith("Add")) || (action.StartsWith("Create")) || (action.StartsWith("Check")))
                    {
                        Log.LogMessage(MessageImportance.Low, "Adding: " + version.VSSItem.Name);

                        // Build our XML Element with hopefully useful information.
                        XmlElement   node   = _outputDoc.CreateElement("item");
                        XmlAttribute attrib = _outputDoc.CreateAttribute("name");
                        attrib.Value = version.VSSItem.Name;
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("path");
                        attrib.Value = version.VSSItem.Spec;
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("action");
                        attrib.Value = action;
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("date");
                        attrib.Value = version.Date.ToString();
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("version");
                        attrib.Value = version.VersionNumber.ToString();
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("user");
                        attrib.Value = version.Username;
                        node.Attributes.Append(attrib);

                        attrib       = _outputDoc.CreateAttribute("comment");
                        attrib.Value = version.Comment;
                        node.Attributes.Append(attrib);

                        _outputDoc.ChildNodes.Item(0).AppendChild(node);
                    }
                }
            }
        }
Exemplo n.º 25
0
        //Unpin + Checkout (PrepareToPush) + Checkin + Pin or Add + Pin + + Exception handling
        public bool PushFile(string vssDir, string localDir, string localFileName, string patchName, out VSSItem item)
        {
            if (!PrepareToPushFile(vssDir, localDir, localFileName))
            {
                item = null;
                return(false);
            }

            string vssPath   = $"{vssDir}/{localFileName}";
            string localPath = Path.Combine(localDir, localFileName);

            try
            {
                item = VSSDB.get_VSSItem(vssPath, false);

                item.Checkin("", localPath);
                if (item.IsCheckedOut == 0)
                {
                    sender($"{item.Spec} checked in");
                    try
                    {
                        Pin(item, item.VersionNumber);
                        sender($"{item.Spec} pinned");
                    }
                    catch
                    {
                        sender($"Cannot pin {item.Spec}");
                    }
                }
                else
                {
                    if (MessageBox.Show($"Файл {localFileName} не зачекинился. Требуется повторить попытку или выложить патч заново", "Предупреждение", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                    {
                        return(PushFile(vssDir, localDir, localFileName, patchName, out item));
                    }

                    /*
                     * Process pr = new Process();
                     * pr.StartInfo.FileName = "cmd.exe";
                     * pr.StartInfo.UseShellExecute = false;
                     * pr.StartInfo.RedirectStandardOutput = true;
                     * pr.StartInfo.RedirectStandardInput = true;
                     * pr.StartInfo.CreateNoWindow = true;
                     * pr.Start();
                     *
                     * string drive = Path.GetPathRoot(localDir).Replace("\\", "");
                     * pr.StandardInput.WriteLine(drive);
                     * pr.StandardInput.WriteLine($"set SSDIR={basePath}");
                     * pr.StandardInput.WriteLine($"\"{SSExeFullName}\" checkin \"{item.Spec}\"");
                     * pr.StandardInput.WriteLine($"\"{SSExeFullName}\" pin \"{item.Spec}\" -V{item.VersionNumber}");
                     *
                     * sender($"{item.Spec} checked in and pinned via cmd");
                     * MessageBox.Show($"Костыль. Запинили с помощью консоли файл {item.Spec}. Требуется проверить вручную.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                     */
                }
            }
            catch (System.Runtime.InteropServices.COMException exc)
            {
                if (!IsFileNotFoundError(exc))
                {
                    throw exc;
                }
                else
                {
                    sender($"{vssPath} не найден. Добавление нового файла...");
                    IVSSItem dir = VSSDB.get_VSSItem(vssDir, false);

                    item = dir.Add(localPath);
                    sender($"{item.Spec} добавлен");

                    try
                    {
                        Pin(item, item.VersionNumber);
                        sender($"{item.Spec} pinned");
                    }
                    catch
                    {
                        sender($"Cannot pin {item.Spec}");
                    }
                }
            }

            Process p = new Process();

            p.StartInfo.FileName               = "cmd.exe";
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput  = true;
            p.StartInfo.CreateNoWindow         = true;
            p.Start();

            p.StandardInput.WriteLine($"set SSDIR={basePath}");
            p.StandardInput.WriteLine($"\"{SSExeFullName}\" Comment \"{item.Spec}\"");
            p.StandardInput.WriteLine($"Patch {patchName}");

            return(true);
        }
Exemplo n.º 26
0
 public static bool IsFileCheckedOut(this IVSSItem item)
 {
     return(item.IsCheckedOut != (int)VSSFileStatus.VSSFILE_NOTCHECKEDOUT);
 }
Exemplo n.º 27
0
		void WalkItem(IVSSItem item)
		{
			if(item.Type == 1)
			{
				_files.Add(Tuple.Create(item.Spec, item.Size));
			}
			else
			{
				WalkItems(item.Items);
			}
		}
Exemplo n.º 28
0
        private void Checkout(IVSSItem checkoutItem, FileInfo localPath, int flags, string pattern)
        {
            //TODO: timestamp stuff

            switch (checkoutItem.Type)
            {
                case (int)VSSItemType.VSSITEM_PROJECT:
                    // Item is a project.
                    if (string.IsNullOrEmpty(pattern))
                    {
                        // In the absence of a pattern, we'll checkout the entire project.
                        checkoutItem.Checkout("", localPath.FullName, flags);
                    }
                    else
                    {
                        // If a pattern is provided, we process all subitems in the project.
                        foreach (IVSSItem subItem in checkoutItem.get_Items(false))
                        {
                            switch (subItem.Type)
                            {
                                case (int)VSSItemType.VSSITEM_PROJECT:
                                    // Subitem is a project.
                                    if (Recursive)
                                    {
                                        // We'll recursively checkout matching files in this project.
                                        Checkout(subItem, new FileInfo(System.IO.Path.Combine(localPath.FullName, subItem.Name)), flags, pattern);
                                    }
                                    break;
                                case (int)VSSItemType.VSSITEM_FILE:
                                    // Subitem is a file.
                                    if (Regex.IsMatch(subItem.Name, pattern))
                                    {
                                        // We'll checkout this file since it matches the search pattern.
                                        Checkout(subItem, localPath, flags, "");
                                    }
                                    break;
                            }
                        }
                    }
                    break;
                case (int)VSSItemType.VSSITEM_FILE:
                    // Item is a file.
                    string filePath = System.IO.Path.Combine(localPath.FullName, checkoutItem.Name);
                    checkoutItem.Checkout("", filePath, flags);
                    break;
            }
        }
Exemplo n.º 29
0
 public void Add(IVSSItem i)
 {
     BaseAdd(i.Name, i);
 }