Example #1
0
        protected override async Task Because()
        {
            await addItems("master");

            await Subject.CreateBranch(new Reference { Name = "test", Pointer = "master" });

            await addItems("test");

            await addItems("master");

            await Subject.CreateBranch(new Reference { Name = "test2", Pointer = "master" });

            await addItems("test2");

            await addItems("test");

            await removeItems("master", 1, 2);

            await removeItems("test", 8, 2);

            await removeItems("test2", 13, 2);

            await addItems("test2");

            _firstMergeResult = await Subject.MergeBranch("test2", "master", Author, "This is the merge commit for branch test2");

            _commitBeforeSecondMerge = Repo.Branches["master"].Tip.Sha;

            _secondMergeResult = await Subject.MergeBranch("test", "master", Author, "This is the merge commit for branch test");

            _commitAfterSecondMerge = Repo.Branches["master"].Tip.Sha;;
        }
        public void GenerateMergeInfo_Execute_Success()
        {
            var templateName           = "Test";
            var relSourceFilePath      = @"Source.cs";
            var mergeFile              = Path.GetFullPath(@".\temp\Source_postaction.cs");
            var outputPath             = Path.GetFullPath(@".\temp\Project");
            var destinationPath        = Path.GetFullPath(@".\DestinationPath\Project");
            var expectedPostactionCode = File.ReadAllText(@".\TestData\Merge\Source_expectedmergeinfo.cs");

            Directory.CreateDirectory(outputPath);
            File.Copy(Path.Combine(Environment.CurrentDirectory, $"TestData\\Merge\\Source_postaction.cs"), mergeFile, true);

            GenContext.Current = new FakeContextProvider()
            {
                DestinationPath      = destinationPath,
                GenerationOutputPath = outputPath,
            };

            GenContext.Current.MergeFilesFromProject.Add(relSourceFilePath, new List <MergeInfo>());

            var mergePostAction = new GenerateMergeInfoPostAction(templateName, mergeFile);

            mergePostAction.Execute();

            var expected = new MergeInfo()
            {
                Format         = "CSHARP",
                PostActionCode = expectedPostactionCode,
            };

            Directory.Delete(Directory.GetParent(outputPath).FullName, true);

            Assert.Equal(expected.Format, GenContext.Current.MergeFilesFromProject[relSourceFilePath][0].Format);
            Assert.Equal(expected.PostActionCode.Replace("\r\n", string.Empty).Replace("\n", string.Empty), GenContext.Current.MergeFilesFromProject[relSourceFilePath][0].PostActionCode.Replace("\r\n", string.Empty).Replace("\n", string.Empty));
        }
Example #3
0
        public override bool Equals(object obj)
        {
            if (this == obj)
            {
                return(true);
            }
            if (obj == null)
            {
                return(false);
            }
            if (this.GetType() != obj.GetType())
            {
                return(false);
            }
            MergeInfo other = (MergeInfo)obj;

            if (EstimatedMergeBytes != other.EstimatedMergeBytes)
            {
                return(false);
            }
            if (IsExternal != other.IsExternal)
            {
                return(false);
            }
            if (MergeMaxNumSegments != other.MergeMaxNumSegments)
            {
                return(false);
            }
            if (TotalDocCount != other.TotalDocCount)
            {
                return(false);
            }
            return(true);
        }
Example #4
0
        protected override async Task Because()
        {
            await Subject.CreateBranch(new Reference { Name = "test", Pointer = "master" });

            await addItem("master");

            await addItem("test", changeValuesForKeys : true);

            _mergeResult = await Subject.MergeBranch("test", "master", Author, "This is the merge commit for branch test");
        }
Example #5
0
        /// <summary>
        /// Производит сохранение данных в БД созданной сводной ведомости
        /// </summary>
        private void SaveNew()
        {
            // создать виртуальную таблицу с пустыми записями
            _mergeInfoTable = MergeInfo.CreateTableWithRows();
            // скопировать данные из транспонированной таблицы в созданную
            MergeInfoTranspose.ConvertToMergeInfo(_svodTable, _mergeInfoTable);
            // просчитать суммы в созданной таблицйе
            MergeInfo.MathSums(_mergeInfoTable);
            // заполнение данными записи Сводной ведомости
            SetMergeData();
            // создание подключения к БД
            SQLiteConnection connection = new SQLiteConnection(_connection);
            // создание команд для вставки данных в БД
            SQLiteCommand mergeInsert    = MergiesView.InsertCommand(_mergeRow);
            SQLiteCommand tableInsert    = MergeInfo.CreateInsertCommand();
            SQLiteCommand fixdataReplace = new SQLiteCommand();
            SQLiteCommand setUnactual    =
                new SQLiteCommand(MergiesView.GetChangeActualByOrgText(_org.idVal, (int)_mergeRow[MergiesView.repYear],
                                                                       false));
            // создание Адаптера для обработки таблицы
            SQLiteDataAdapter adapter = new SQLiteDataAdapter();

            adapter.InsertCommand = tableInsert;
            // присвоение созданного подключения коммандам
            mergeInsert.Connection             =
                tableInsert.Connection         =
                    fixdataReplace.Connection  =
                        setUnactual.Connection = connection;
            // открытие соединения
            connection.Open();
            // начать транзакция
            SQLiteTransaction transaction = connection.BeginTransaction();

            // прикрепление транзакции
            mergeInsert.Transaction             =
                tableInsert.Transaction         =
                    fixdataReplace.Transaction  =
                        setUnactual.Transaction = transaction;
            // выполнить команду обнуления актуальности сводных ведомостей в выбранном году для текущей организаций
            setUnactual.ExecuteNonQuery();
            // выполнить команду вставки записи о новой сводной ведомости и назначения ее актуальной
            _mergeRow[MergiesView.id] = mergeInsert.ExecuteScalar();
            _mergeRow.EndEdit();
            // внести запись о факте создания записи сводной     ведомости
            fixdataReplace.CommandText = MergiesView.GetReplaceFixDataText(_mergeRow, FixData.FixType.New);
            fixdataReplace.ExecuteNonQuery();
            // заполнить соответствующий столбец таблицы ID сводной ведомости для их привязки к ней (сводной ведомости)
            MergeInfo.SetMergeID(_mergeInfoTable, (long)_mergeRow[MergiesView.id]);
            // ввыполнить вставку записей из таблицы программы в таблицу БД
            adapter.Update(_mergeInfoTable);
            // принять подключение
            transaction.Commit();
            // закрыть соединение
            connection.Close();
        }
Example #6
0
        protected override async Task Because()
        {
            foreach (var i in Enumerable.Range(0, 5))
            {
                await Subject.Save("master", $"Added {i} (master)", new Document { Key = $"file\\key {i}", Value = i.ToString() }, Author);
            }

            _masterCommit = Repo.Branches["master"].Tip.Sha;

            await Subject.CreateBranch(new Reference { Name = "test", Pointer = "master" });

            _mergeResult = await Subject.MergeBranch("test", "master", Author, "This is the merge commit for branch test");
        }
Example #7
0
        private void SvodVedomostEditDocumentForm_Load(object sender, EventArgs e)
        {
            _svodBS    = new BindingSource();
            _svodTable = MergeInfoTranspose.CreateTable();

            regnumBox.Text  = _org.regnumVal;
            orgnameBox.Text = _org.nameVal;

            if (_mergeRow == null)
            {
                //this.packetcountBox.Value = 0;
                //this.documentcountBox.Value = 0;
                _mergeInfoTable = null;
            }
            else
            {
                yearBox.Text           = _mergeRow[MergiesView.repYear].ToString();
                packetcountBox.Value   = (int)_mergeRow[MergiesView.listCount];
                documentcountBox.Value = (int)_mergeRow[MergiesView.docCount];

                _mergeInfoTable = MergeInfo.CreateTable();
                SQLiteDataAdapter adapter =
                    new SQLiteDataAdapter(MergeInfo.GetSelectText((long)_mergeRow[MergiesView.id]), _connection);
                adapter.Fill(_mergeInfoTable);
                MergeInfoTranspose.ConvertFromMergeInfo(_svodTable, _mergeInfoTable);

                sum1Box.Text = MergeInfo.GetSum(_mergeInfoTable, SalaryGroups.Column1).ToString("N2");
                sum2Box.Text = MergeInfo.GetSum(_mergeInfoTable, SalaryGroups.Column2).ToString("N2");
                sum3Box.Text = MergeInfo.GetSum(_mergeInfoTable, SalaryGroups.Column3).ToString("N2");
                sum4Box.Text = MergeInfo.GetSum(_mergeInfoTable, SalaryGroups.Column4).ToString("N2");
                sum5Box.Text = MergeInfo.GetSum(_mergeInfoTable, SalaryGroups.Column5).ToString("N2");

                if (!(bool)_mergeRow[MergiesView.actual])
                {
                    packetcountBox.Enabled   = false;
                    documentcountBox.Enabled = false;
                    dataView.ReadOnly        = true;
                    saveButton.Enabled       = false;
                    autofillButton.Enabled   = false;
                }
            }
            _svodBS.DataSource           = _svodTable;
            dataView.AutoGenerateColumns = false;
            dataView.DataSource          = _svodBS;

            _svodTable.ColumnChanged += new DataColumnChangeEventHandler(_svodTable_ColumnChanged);
            dataView.CellParsing     += new DataGridViewCellParsingEventHandler(dataView_CellParsing);
            dataView.DataError       += new DataGridViewDataErrorEventHandler(dataView_DataError);
        }
Example #8
0
        /// <summary>
        /// 获取单元格合并的额外信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        private MergeInfo GetMergeInfo(string data)
        {
            MergeInfo mergeInfo = null;
            Match     info      = Regex.Match(data, @"\(\?!(?<mergeType>\w+)\s*=\s*[""']?(?<mergeSpan>\d+)[""']?\)");
            string    mergeType = string.Empty;
            int       mergeSpan;

            if (info.Success)
            {
                mergeType = info.Groups["mergeType"].Value.ToString();
                mergeSpan = Convert.ToInt32(info.Groups["mergeSpan"].Value);
                mergeInfo = new MergeInfo()
                {
                    MergeType = mergeType, MergeSpan = mergeSpan
                };
            }
            return(mergeInfo);
        }
Example #9
0
        /// <summary>
        /// Производит сохранение данных в БД измененной сводной ведомости
        /// </summary>
        private void SaveEdited()
        {
            // скопировать данные с транспонированной таблицы в таблицу, соответствующую по структуре с таблицей БД
            MergeInfoTranspose.ConvertToMergeInfo(_svodTable, _mergeInfoTable);
            // просчитать суммы в созданной таблицйе
            MergeInfo.MathSums(_mergeInfoTable);
            // заполнение данными записи Сводной ведомости
            SetMergeData();
            // создание подключения к БД
            SQLiteConnection connection = new SQLiteConnection(_connection);
            // создание команд для вставки данных в БД
            SQLiteCommand mergeInsert    = MergiesView.UpdateCommand(_mergeRow);
            SQLiteCommand tableInsert    = MergeInfo.CreateUpdateCommand();
            SQLiteCommand fixdataReplace = new SQLiteCommand();
            // создание Адаптера для обработки таблицы
            SQLiteDataAdapter adapter = new SQLiteDataAdapter();

            adapter.UpdateCommand = tableInsert;
            // присвоение созданного подключения коммандам
            mergeInsert.Connection            =
                tableInsert.Connection        =
                    fixdataReplace.Connection = connection;
            // открытие соединения
            connection.Open();
            // начать транзакция
            SQLiteTransaction transaction = connection.BeginTransaction();

            // прикрепление транзакции
            mergeInsert.Transaction            =
                tableInsert.Transaction        =
                    fixdataReplace.Transaction = transaction;
            // выполнить обновление данных о сводной ведомости
            mergeInsert.ExecuteNonQuery();
            // выполнить вставку(обновление) данных о факте изменения сводной ведомости
            fixdataReplace.CommandText = MergiesView.GetReplaceFixDataText(_mergeRow, FixData.FixType.Edit);
            fixdataReplace.ExecuteNonQuery();
            // выполнить обносление данных по значениям выплат
            adapter.Update(_mergeInfoTable);
            // принять подключение
            transaction.Commit();
            // закрыть соединение
            connection.Close();
        }
Example #10
0
 /// <summary>
 /// 添加单元格数据
 /// </summary>
 /// <param name="data">数据值</param>
 /// <param name="mergeInfo">单元格合并信息</param>
 private void AddCellData(string data)
 {
     if (WithinMergeArea(rowIndex, colIndex))
     {
         colIndex++;
         AddCellData(data);
     }
     else
     {
         MergeInfo mergeInfo = GetMergeInfo(data);
         SetCellStyleByCellData(data);
         data = Regex.Replace(data, @"\(\?!.+?\)", "");
         double dataDou;
         if (double.TryParse(data, out dataDou))
         {
             Cell cell = worksheet.Cells.Add(rowIndex, colIndex, dataDou, cellStyle);
         }
         else
         {
             worksheet.Cells.Add(rowIndex, colIndex, data, cellStyle);
         }
         if (mergeInfo != null)
         {
             MergeArea mergeArea;
             if (string.Equals(mergeInfo.MergeType, "colspan", StringComparison.InvariantCultureIgnoreCase))
             {
                 mergeArea = new MergeArea()
                 {
                     RowMin = (ushort)rowIndex, RowMax = (ushort)rowIndex, ColMin = (ushort)colIndex, ColMax = (ushort)(colIndex + mergeInfo.MergeSpan - 1)
                 };
             }
             else
             {
                 mergeArea = new MergeArea()
                 {
                     RowMin = (ushort)rowIndex, RowMax = (ushort)(rowIndex + mergeInfo.MergeSpan - 1), ColMin = (ushort)colIndex, ColMax = (ushort)colIndex
                 };
             }
             worksheet.AddMergeArea(mergeArea);
             mergeAreaList.Add(mergeArea);
         }
     }
 }
Example #11
0
        public void FrameMerge(MergeInfo cMergeInfo, List <byte[]> aLayers, bool bEnqueueFirst)
        {
            _cMREDone.Reset();  // для многоразового юзания
            _nMaxTasksIndx = cMergeInfo.nBackgroundHight;
            _nTaskNumber   = 0;
            _cInfo         = cMergeInfo;
            _aLayers       = aLayers.ToArray();
            lock (_aqQueue.oSyncRoot)              // что б вклинить таск из байтилуса - только он не конкурирует с пре-рендерами роллов и т.п.
            {
                if (bEnqueueFirst)
                {
                    _aqQueue.EnqueueFirst(this);
                }
                else
                {
                    _aqQueue.Enqueue(this);
                }
            }
            //(new Logger()).WriteDebug3("begin one [" + DateTime.Now.ToString("yyyy-MM-dd h:mm:ss.ms") + "]");

            _cMREDone.WaitOne();
        }
Example #12
0
        public void FrameMerge(MergeInfo cMergeInfo, List<byte[]> aLayers)
        {
			_aqTasks.Add(this, 0);
			_nMaxTasksIndx = cMergeInfo.nBackgroundHight;
            aCropTopLineInBG = new int[cMergeInfo.aLayerInfos.Length];
			aCropBottomLineInBG = new int[cMergeInfo.aLayerInfos.Length];
			for (int nI = 0; nI < aCropTopLineInBG.Length; nI++)
			{
				aCropTopLineInBG[nI] = cMergeInfo.aLayerInfos[nI].nBackgroundStart / cMergeInfo.nBackgroundWidth;
				aCropBottomLineInBG[nI] = aCropTopLineInBG[nI] + cMergeInfo.aLayerInfos[nI].nCropHeight - 1;
            }

			_cInfo = cMergeInfo;
            _aLayers = aLayers.ToArray();
            _aqQueue.Enqueue(this);
			//(new Logger()).WriteDebug3("begin one [" + DateTime.Now.ToString("yyyy-MM-dd h:mm:ss.ms") + "]");
			_cMREDone.WaitOne();

			_aqTasks.Remove(this);
        }
Example #13
0
        public override string GetMergerSql(MergeInfo info)
        {
            bool needinsert = info.InsertPram != null && info.InsertPram.Count != 0;
            bool needupdate = info.UpdatePram != null && info.UpdatePram.Count != 0;

            if (!needinsert && !needupdate)
            {
                throw new DataBaseException("Merger方法的insert和update参数不能同时为空");
            }
            string        mainsql  = @"  merge into {0} a
                            using (select {1} from dual) b
                            on (1 = 1 {2})";
            string        sql0     = info.TableName;
            List <string> sql1list = new List <string>();

            foreach (KeyValuePair <string, MergePramInfo> item in info.Pk)
            {
                sql1list.Add(SetValueToStr(item.Value) + " " + item.Key);
            }
            List <string> sql2list = new List <string>();

            foreach (KeyValuePair <string, MergePramInfo> item in info.Pk)
            {
                sql2list.Add(" and a." + item.Key + "=b." + item.Key);
            }
            List <string> sql3list = new List <string>();

            mainsql = string.Format(mainsql,
                                    sql0,
                                    string.Join(",", sql1list),
                                    string.Join(" ", sql2list)
                                    );
            //更新字段
            if (needupdate)
            {
                foreach (KeyValuePair <string, MergePramInfo> item in info.UpdatePram)
                {
                    if (!info.Pk.ContainsKey(item.Key))
                    {
                        sql3list.Add(" a." + item.Key + "=" + SetValueToStr(item.Value) + " ");
                    }
                }
                string updatesql = @"when matched then
                                     update set " + string.Join(",", sql3list);
                mainsql += updatesql;
                if (sql3list.Count == 0)
                {
                    throw new DataBaseException("更新字段必须有主键之外的项");
                }
            }
            List <string> sql4list = new List <string>();
            List <string> sql5list = new List <string>();

            //插入字段
            if (needinsert)
            {
                //插入主键字段
                foreach (KeyValuePair <string, MergePramInfo> item in info.Pk)
                {
                    sql4list.Add(item.Key);
                    sql5list.Add(SetValueToStr(item.Value));
                }
                //插入其他字段
                foreach (KeyValuePair <string, MergePramInfo> item in info.InsertPram)
                {
                    if (!info.Pk.ContainsKey(item.Key))
                    {
                        sql4list.Add(item.Key);
                        sql5list.Add(SetValueToStr(item.Value));
                    }
                }
                string insertsql = @"when not matched then
                                      insert
                                        ({0})
                                      values
                                        ({1})";
                insertsql = string.Format(insertsql,
                                          string.Join(",", sql4list),
                                          string.Join(",", sql5list)
                                          );
                mainsql += insertsql;
            }
            return(mainsql);
        }
Example #14
0
 private void OnMerged(MergeInfo mergeInfo)
 {
     Score += Bubble.GetNumber(mergeInfo.power);
 }
Example #15
0
 public void SecondMergeShouldSuccedWithValidInfo() =>
 _secondMergeResult.ShouldBeEquivalentTo(MergeInfo.Succeeded("test", "master", _commitAfterSecondMerge));
Example #16
0
        public override string GetMergerSql(MergeInfo info)
        {
            string sql = "INSERT OR REPLACE INTO " + info.TableName + " ({0}) VALUES({1})";

            return(string.Format(sql, Getpram(info.UpdatePram), GetpramValue(info.UpdatePram)));
        }
Example #17
0
 /// <summary>
 /// 获取读写sql
 /// </summary>
 /// <param name="info"></param>
 /// <returns></returns>
 public abstract string GetMergerSql(MergeInfo info);
Example #18
0
 public void MergeShouldSuccedWithValidInfo() =>
 _mergeResult.ShouldBeEquivalentTo(MergeInfo.Succeeded("test", "master", string.Empty));
Example #19
0
 public override string GetMergerSql(MergeInfo info)
 {
     throw new NotImplementedException();
 }
Example #20
0
        private Collection ConvertCollection(Collection collection, ConvertConfig config)
        {
            Collection result = new Collection();
            result.name = collection.name;

            List<Product> products = new List<Product>();
            foreach (Product product in collection.products)
                products.Add((Product)product.Clone());

            products.Sort(CompareProductsByCode);

            Dictionary<Product, MergeInfo> mergesByProduct = new Dictionary<Product, MergeInfo>();
            Dictionary<string, MergeInfo> mergesByIndex = new Dictionary<string, MergeInfo>();

            // Определяем группы товаров
            for (int productIndex = 0; productIndex < products.Count; ++productIndex)
            {
                Product product = products[productIndex];

                // Проверяем выполнение регулярных выражений
                for (int groupIndex = 0; groupIndex < config.groups.Length; ++groupIndex)
                {
                    ConvertConfig.GroupConfig groupConfig = config.groups[groupIndex];
                    Dictionary<string, string> values = groupConfig.inputExpression.Parse(product.name);

                    if (null != values)
                    {
                        if (null != groupConfig.merge)
                        {
                            if (null != groupConfig.textExpression)
                                product.name = groupConfig.textExpression.Format(values).Trim();

                            string mid = product.name + ":" + product.cost.ToString();
                            if (!mergesByIndex.ContainsKey(mid))
                            {
                                MergeInfo mergeInfo = new MergeInfo(product);
                                mergesByIndex.Add(mid, mergeInfo);
                                mergesByProduct.Add(product, mergeInfo);
                            }
                            else
                            {
                                mergesByProduct.Add(product, null);
                            }

                            mergesByIndex[mid].codes.Add(product.code);
                        }
                        else if (null != groupConfig.groupExpression)
                        {
                            product.groupName = groupConfig.groupExpression.Format(values).Trim();
                            product.shortName = groupConfig.textExpression.Format(values).Trim();
                        }
                        else
                        {
                            product.name = groupConfig.textExpression.Format(values).Trim();
                        }

                        break;
                    }
                }
            }

            // Группируем товары
            for (int productIndex = 0; productIndex < products.Count; ++productIndex)
            {
                Product product = products[productIndex];
                if (null == product)
                    continue;

                if (mergesByProduct.ContainsKey(product))
                {
                    MergeInfo mergeInfo = mergesByProduct[product];
                    if (null == mergeInfo)
                        continue;

                    product.code = 0;

                    StringBuilder name = new StringBuilder();
                    name.Append(product.name);
                    name.Append(" (");

                    mergeInfo.codes.Sort();

                    int codeStartIndex = 0;
                    for (int codeIndex = 1; codeIndex <= mergeInfo.codes.Count; ++codeIndex)
                    {
                        if (codeIndex < mergeInfo.codes.Count &&
                            mergeInfo.codes[codeIndex] == mergeInfo.codes[codeStartIndex] + codeIndex - codeStartIndex)
                            continue;

                        if (codeStartIndex != 0)
                            name.Append(", ");

                        name.Append(mergeInfo.codes[codeStartIndex]);
                        if (codeIndex - codeStartIndex > 1)
                        {
                            name.Append("-");
                            name.Append(mergeInfo.codes[codeIndex - 1]);
                        }

                        codeStartIndex = codeIndex;
                    }

                    name.Append(")");

                    product.name = name.ToString();

                    result.products.Add(product);
                }
                else if (null != product.shortName && null != product.groupName)
                {
                    // Создаем группу товаров
                    for (int i = productIndex; i < products.Count; ++i)
                    {
                        Product inputProduct = products[i];
                        if (null == inputProduct)
                            continue;

                        if (inputProduct.groupName == product.groupName)
                        {
                            result.products.Add(inputProduct);
                            products[i] = null;
                        }
                    }
                }
                else
                {
                    // Помещаем товар в список
                    result.products.Add(product);
                }
            }

            // Прогоняем подгруппы
            foreach (Collection subCollection in collection.collections)
                result.collections.Add(ConvertCollection(subCollection, config));

            return result;
        }
Example #21
0
        static private void WorkerMain()
        {
            try
            {
                _nJobIndx = 0;
                int nCounter = 0;
                (new Logger()).WriteNotice("main worker started");
                //Logger.Timings cTimings = new helpers.Logger.Timings("discom:WorkerMain:profiling");
                while (true)
                {
                    _cDisComProcessing = _aqQueue.Dequeue(); //DNF
                    if (_cDisComProcessing._cInfo is MergeInfo)
                    {
                        _cMergeInfo = (MergeInfo)_cDisComProcessing._cInfo;
#if !CUDATEST
                        if (_cMergeInfo.bLayer1CopyToBackground)
                        {
                            Array.Copy(_cDisComProcessing._aLayers[1], _cDisComProcessing._aLayers[0], _cDisComProcessing._aLayers[0].Length);
                        }
                        else
                        {
                            Array.Clear(_cDisComProcessing._aLayers[0], 0, _cDisComProcessing._aLayers[0].Length);
                        }
#endif
                    }
                    else
                    {
                        _cMergeInfo = null;
                    }

                    if (100 < nCounter++)
                    {
                        //cTimings.TotalRenew(); //profiling
                        nCounter  = 0;
                        _nJobIndx = 1;
                        //(new Logger()).WriteNotice("profiling begin [id:" + _cDisComProcessing.GetHashCode() + "][max_indx:" + _cDisComProcessing._nMaxTasksIndx + "][total_threads:" + _aMREDone.Length + "]");
                    }
                    else
                    {
                        _nJobIndx = 0;
                    }



                    //_cDisComProcessing._cMREDone.Reset();
                    foreach (ManualResetEvent cMRE in _aMREDone)
                    {
                        cMRE.Reset();
                    }

                    //if (_nJobIndx == 1) //profiling
                    //    cTimings.Restart("done reset");

                    foreach (ManualResetEvent cMRE in _aMREStart)
                    {
                        cMRE.Set();
                    }

                    //if (_nJobIndx == 1) //profiling
                    //    cTimings.Restart("start set");

                    for (int nIndx = 0; nIndx < _aMREDone.Length; nIndx += 64)
                    {
                        ManualResetEvent.WaitAll(_aMREDone.Skip(nIndx).Take(64).ToArray());
                    }


                    _cDisComProcessing._cMREDone.Set();


                    //if (_nJobIndx == 1) //profiling
                    //{
                    //    (new Logger()).WriteNotice("profiling end [id:" + _cDisComProcessing.GetHashCode() + "][max_indx:" + _cDisComProcessing._nMaxTasksIndx + "][total_jobs_done = " + _cDisComProcessing._nJobsDone + "]");
                    //    cTimings.Stop("merge done");
                    //}
                }
            }
            catch (ThreadInterruptedException)
            {
            }
            catch (Exception ex)
            {
                (new Logger()).WriteError(ex);
            }
        }
Example #22
0
 public void FirstMergesShouldSuccedWithValidInfo() =>
 _firstMergeResult.ShouldBeEquivalentTo(MergeInfo.Succeeded("test2", "master", _commitBeforeSecondMerge));
Example #23
0
        public Task <MergeInfo> MergeBranch(string source, string target, Author author, string message)
        {
            var signature    = getSignature(author);
            var targetBranch = _repo.Branches[target];
            var sourceBranch = _repo.Branches[source];

            if (isTransactionInProgress(target))
            {
                var exceptionMessage = $"There is a transaction in progress for branch {target}. Complete the transaction first.";
                _logger.Warn(exceptionMessage);
                throw new ArgumentException(exceptionMessage);
            }

            lock (getLock(target))
            {
                var mergeRes = _repo.ObjectDatabase.MergeCommits(sourceBranch.Tip, targetBranch.Tip, new MergeTreeOptions());
                if (mergeRes.Status != MergeTreeStatus.Succeeded)
                {
                    var logMessage = $"Could not merge {source} into {target} because of conflicts. Please merge manually";
                    _logger.Trace(logMessage);

                    return(Task.FromResult(new MergeInfo
                    {
                        Message = logMessage,
                        SourceBranch = source,
                        TargetBranch = target,
                        Status = MergeResult.Conflicts,
                        Conflicts = mergeRes.Conflicts.Select(c => new ConflictInfo
                        {
                            SourceSha = c.Ours?.Id.Sha,
                            TargetSha = c.Theirs?.Id.Sha,
                            Path = c.Ours?.Path ?? c.Theirs.Path,
                            Type = object.ReferenceEquals(c.Ours, null) || object.ReferenceEquals(c.Theirs, null) ? ConflictType.Remove : ConflictType.Change
                        }).ToList()
                    }));
                }

                _repo.Branches.Remove(sourceBranch);

                var previousCommit = targetBranch.Tip;
                var tree           = mergeRes.Tree;

                if (previousCommit != null && previousCommit.Tree.Id == tree.Id)
                {
                    return(Task.FromResult(MergeInfo.Succeeded(source, target, string.Empty)));
                }

                var ancestors = previousCommit != null ? new List <Commit> {
                    previousCommit
                } : new List <Commit>();
                var commit = _repo.ObjectDatabase.CreateCommit(signature, signature, message, tree, ancestors, false);

                _repo.Refs.UpdateTarget(_repo.Refs[targetBranch.CanonicalName], commit.Id);

                _logger.Trace($"Squashed and merged {source} into {target} and removed {source} with message {message}");

                push(target);

                return(Task.FromResult(MergeInfo.Succeeded(source, target, commit.Sha)));
            }
        }
 private void OnMerge(MergeInfo mergInfo)
 {
     PlaySound(SOUND_MERGE);
 }