root/branches/0_1_3/InstallerServiceClass.pas

Revision 136, 13.1 kB (checked in by sagrer, 1 year ago)
  • Пофиксан баг в Installer с возможным дублированием пути, вносимого в path в случае обновления с версии на версию, когда путь установки не изменялся.
  • Поправлена инфа о версии.
  • Property svnmailer:content-charset set to cp1251
Line 
1 ///////////////////////////////////////////////////////////
2 //                     GGBuildTools                      //
3 //    Набор утилит для сборки проектов Gipat Group       //
4 //             Copyright (C) 2007 Gipat Group            //
5 //              Распространяется на условиях             //
6 //    Gipat Group's opened EI-editor-utility license     //
7 //                      версии 1.0                       //
8 //                                                       //
9 //                  www.gipatgroup.org                   //
10 ///////////////////////////////////////////////////////////
11
12 //К работе над данным файлом приложили руки, ноги.... короче аффтары:
13 // 1) Sagrer (sagrer@yandex.ru)
14
15 ////////////////////////////////////////////////////////////////////////
16
17 ////////////////////////////////////////////////////////
18 //          Служебный класс для Installer             //
19 ////////////////////////////////////////////////////////
20
21 unit InstallerServiceClass;
22
23 {$mode objfpc}{$H+}
24
25 interface
26
27 uses
28   Classes, SysUtils, forms, Registry, ExtraFunctionsLcl, GGBuildToolsShared, GGConsUtilServiceClass, ExtraFileUtilsLCL;
29  
30 const
31   GGBT_InstallerAppName = 'Installer';
32  
33 type
34   TInstallerServiceClass = class (TGGConsUtilServiceClass)       //Класс с основным функционалом и данными инсталлера
35   private
36   protected
37   public
38     //Переменные
39     Registr : TRegistry;               //Объект класса для работы с виндовым реестром.
40     InstalledTools : RInstalledTools;  //Инфа про установленные тулсы
41    
42     //Конструкторы-деструкторы...
43     constructor Create; override;
44     destructor Destroy; override;
45    
46     //Другие методы...
47     procedure DoWork;        override;   //Выполнить боевую задачу %).
48     procedure InstallIt;                 //Выполнить инсталляцию.
49     procedure ShowDescription; override; //Вывести описание утилиты.
50    
51   end;
52  
53 var
54   InstServClass : TInstallerServiceClass;
55
56 implementation
57
58 /////////////////////////////////////////////
59 //         TInstallerServiceClass          //
60 /////////////////////////////////////////////
61
62 //-----------------------------------------//
63 //        Конструкторы-деструкторы...      //
64 //-----------------------------------------//
65
66 constructor TInstallerServiceClass.Create;
67 begin
68   //Проставить дефолтные значения...
69   InstalledTools.IssBuilder_installed := false;
70   InstalledTools.StarterModBuilder_installed := false;
71   InstalledTools.StarterModSynchronizator_installed := false;
72   InstalledTools.VerRevUpdater_installed := false;
73  
74   //Создать вложенные объекты классов...
75   Registr := TRegistry.Create;
76  
77   //Вбить имя приложения.
78   Self.GGConsAppName := GGBT_InstallerAppName;
79  
80   //Выполнить конструктор предка...
81   inherited;
82 end;
83
84 destructor TInstallerServiceClass.Destroy;
85 begin
86   //Выкидываем мусор
87   Registr.Free;
88
89   //Выполнить унаследованный деструктор
90   inherited;
91 end;
92
93 //------------------------------------------//
94 //             Другие методы...             //
95 //------------------------------------------//
96
97 procedure TInstallerServiceClass.DoWork;
98 //Выполнить боевую задачу %).
99 begin
100   //Выполнить нужно одну из задач - по её завершении ProcessFurther := false
101   //и дальше нифига не выполняется.
102  
103   //Выполнить унаследованную функцию
104   inherited;
105  
106   //Если ничего до сих пор не выполнилось - то выполняем боевую задачу....
107   if ProcessFurther = true then begin
108     //Блокировка других веток
109     ProcessFurther := false;
110     //Работаем....
111     InstallIt;
112   end;
113  
114 end;
115
116 procedure TInstallerServiceClass.InstallIt;
117 var
118   CurPath, CurVer, ExePath, OldPath, Answer : string;
119   NeedInstall, WasOldPath, OldVersionInstalled : boolean;
120 begin
121   //Выполнить инсталляцию.
122  
123   //Все очень просто. Проверяем ключ реестра проги, если он есть - смотрим тот ли там путь,
124   //если не тот - спрашиваем регистрировать ли путь, затем смотрим PATH, если там
125   //есть старый путь - удаляем. Затем добавляем новый путь в переменную и ключег в реестр.
126  
127   NeedInstall := false;   //По умолчанию - ниче трогать не надо %).
128   WasOldPath := false;   //И считаем что по другим путям ниче не установлено.
129   ExePath := DelLastSlash(ExtractFilePath(Application.ExeName))+'\bin';   //Сразу получим путь к GGBuildTools.
130   OldVersionInstalled := false;   //Считаем что более старой версии не установлено.
131  
132   //Выводим сначала версию...
133   ShowVersion();
134   //Отделяющая строка.
135   Writeln();
136  
137   //Пишем что собираем инфу...
138   Writeln('Gathering infirmation...');
139   Writeln('');
140  
141   //Итак, проверям ключ реестра...
142   Registr.RootKey := HKEY_CURRENT_USER;
143   if Registr.OpenKey('\Software\Gipat Group\'+AllProjectName,false) = true then begin
144   //if Registr.KeyExists('\Software\Gipat Group\'+AllProjectName,false) = true then begin    //#LCL-BUG
145     //Registr.OpenKey('\Software\Gipat Group\'+AllProjectName,false);                        //#LCL-BUG
146    
147     //Есть такой ключег... смотрим чего там внутрях %).
148     CurPath := Registr.ReadString('path');
149     CurVer := Registr.ReadString('ver');
150     Registr.CloseKey;
151    
152     //Ок. Теперь - проверяем, правильный ли там путь...
153     if UpperCase(DelLastSlash(ExtractFilePath(Application.ExeName))) <> UpperCase(DelLastSlash(CurPath)) then begin
154       //Не, не совпало.
155       WasOldPath := true;
156       OldPath := DelLastSlash(CurPath);
157     end;
158    
159     //Теперь смотрим на номер версии...
160     if IsNewVersion(CurVer,Self.AppVersion.GenerateDotsVersionString()) = true then begin
161       //Если стоит старая версия...
162       OldVersionInstalled := true;
163     end;
164    
165     //Если эта версия уже установлена, по этому же пути - то нет смысла еще раз
166     //устанавливаться, о чем и сообщаем %).
167     if (WasOldPath = false) and (OldVersionInstalled = false) then begin
168       Writeln('This version is already installed into this directory.');
169       Writeln('So, we no need to reinstall now.');
170       Writeln('Installation aborted %)');
171     end;
172    
173     //Теперь выясняем вопрос о необходимости переустановки...
174    
175     //Если был прописан другой путь.
176     If WasOldPath = true then begin
177       //Спрашиваем если нужно.
178       if DoSilent <> true then begin
179         Writeln('Another version is installed with path:');
180         Writeln(OldPath);
181         Write('Continue installing this version, deinstalling this another? (y/n) > ');
182         Readln(Answer);
183       end
184       else begin
185         Writeln('Another version is installed with path:');
186         Writeln(OldPath);
187         Writeln('I''ll deinstall this another!');
188         Answer := 'y';
189       end;
190      
191       if UpperCase(Answer) = 'Y' then begin
192         NeedInstall := true;  //Отмечаем необходимость переустановки.
193       end;
194     end;
195
196     //Если была прописана другая версия, но с путем все было ок.
197     If (WasOldPath = false) and (OldVersionInstalled = true) then begin
198       //Нужно спросить (если нужно %) ) обновлять ли на новую версию.
199       if DoSilent <> true then begin
200         Writeln('Older version ( '+CurVer+' ) is installed.');
201         Write('Update (y) or cancel (n) ? (y/n) > ');
202         Readln(Answer);
203       end
204       else begin
205         Writeln('Older version ( '+CurVer+' ) is installed.');
206         Writeln('Updating!');
207         Answer := 'y';
208       end;
209      
210       if UpperCase(Answer) = 'Y' then begin
211         NeedInstall := true;  //Отмечаем необходимость переустановки.
212       end;
213     end;
214    
215   end
216   else begin
217     //Нету нифига в реестре. Просто переустанавливаем...
218     NeedInstall := true;
219   end;
220  
221   //Запрос на собсно установку %)
222   if NeedInstall = true then begin
223     if DoSilent = false then begin
224       Write('All is ready. Really want to install? (y/n) > ');
225       Readln(Answer);
226       if UpperCase(Answer) <> 'Y' then begin
227         NeedInstall := false;  //Облом, отмена установки.
228         Writeln('Ok, canceled.');
229       end
230       else begin
231         Writeln('Ok, installing is confirmed.');
232       end;
233     end
234     else begin
235       Writeln('All is ready. Installing is confirmed automatically.');
236     end;
237   end;
238  
239   //Теперь собсно установка.
240   if NeedInstall = true then begin
241  
242     Writeln('');
243     Writeln('');
244     Writeln('');
245     Writeln('Installing started!');
246     Writeln('');
247     Writeln('');
248
249 ///////////////////////////
250
251     //Проверяем наличие тулсов...
252     Writeln('Checking tools: ');
253
254     Write('IssBuilder                              ');
255     if FileExists(DelLastSlash(ExePath)+'\IssBuilder.exe') = true then begin
256       //Экзешнег присутствует...
257       InstalledTools.IssBuilder_installed := true;
258       Writeln('[  OK  ]');
259     end
260     else begin
261       //Нету нифигга.
262       InstalledTools.IssBuilder_installed := false;
263       Writeln('[ FAIL ]');
264     end;
265    
266     Write('VerRevUpdater                           ');
267     if FileExists(DelLastSlash(ExePath)+'\VerRevUpdater.exe') = true then begin
268       //Экзешнег присутствует...
269       InstalledTools.VerRevUpdater_installed := true;
270       Writeln('[  OK  ]');
271     end
272     else begin
273       //Нету нифигга.
274       InstalledTools.VerRevUpdater_installed := false;
275       Writeln('[ FAIL ]');
276     end;
277    
278     Write('StarterModBuilder                       ');
279     if FileExists(DelLastSlash(ExePath)+'\StarterModBuilder.exe') = true then begin
280       //Экзешнег присутствует...
281       InstalledTools.StarterModBuilder_installed := true;
282       Writeln('[  OK  ]');
283     end
284     else begin
285       //Нету нифигга.
286       InstalledTools.StarterModBuilder_installed := false;
287       Writeln('[ FAIL ]');
288     end;
289    
290     Write('StarterModSynchtonizator                ');
291     if FileExists(DelLastSlash(ExePath)+'\StarterModSynchronizator.exe') = true then begin
292       //Экзешнег присутствует...
293       InstalledTools.StarterModSynchronizator_installed := true;
294       Writeln('[  OK  ]');
295     end
296     else begin
297       //Нету нифигга.
298       InstalledTools.StarterModSynchronizator_installed := false;
299       Writeln('[ FAIL ]');
300     end;
301    
302     Write('SourcePackBuilder                       ');
303     if FileExists(DelLastSlash(ExePath)+'\SourcePackBuilder.exe') = true then begin
304       //Экзешнег присутствует...
305       InstalledTools.SourcePackBuilder_installed := true;
306       Writeln('[  OK  ]');
307     end
308     else begin
309       //Нету нифигга.
310       InstalledTools.SourcePackBuilder_installed := false;
311       Writeln('[ FAIL ]');
312     end;
313    
314     Writeln('');
315    
316 /////////////////////////////
317
318     //Если что-то было зарегистрировано по старому пути...
319     if WasOldPath = true then begin
320       //Просто удаляем старый путь.
321       if EnvPathRemove(OldPath,true,true) = true then begin
322         Writeln('Deleted old path from environment.');
323       end;
324     end;
325    
326     //Теперь - если нужно - удаляем старый раздел реестра...
327     if Registr.OpenKey('\Software\Gipat Group\'+AllProjectName,false) = true then begin
328       Registr.CloseKey();
329       Registr.DeleteKey('\Software\Gipat Group\'+AllProjectName);
330       Writeln('Deleted old registry key.');
331     end;
332    
333     //Дальше - типо стандартный инсталл.
334     Writeln('');
335     Writeln('Standard installation started.');
336     Writeln('');
337     //Добавляем переменную в User path-а.
338     Write('Adding into PATH wariable: ');
339     if not ( (OldVersionInstalled = true) and (WasOldPath = false) ) then begin
340       //Новый путь нужно вбить во всех случаях, кроме как когда поменялась только версия но не путь.
341       EnvPathAdd(DelLastSlash(ExePath),EnvPathAdd_User);
342     end;
343     Writeln(DelLastSlash(ExePath));
344     Writeln('done.');
345     Writeln('');
346     //Создаем ключег в реестре.
347     Writeln('Registering in a registry...');
348     Registr.RootKey := HKEY_CURRENT_USER;
349     Registr.OpenKey('\Software\Gipat Group\'+AllProjectName, true);
350     //И вбиваем в него содержимое...
351     Registr.WriteString('path',DelLastSlash(ExtractFilePath(Application.ExeName)));
352     Registr.WriteString('ver',Self.AppVersion.GenerateDotsVersionString());
353     Registr.WriteBool('IssBuilder_installed',InstalledTools.IssBuilder_installed);
354     Registr.WriteBool('VerRevUpdater_installed',InstalledTools.VerRevUpdater_installed);
355     Registr.WriteBool('StarterModBuilder_installed',InstalledTools.StarterModBuilder_installed);
356     Registr.WriteBool('StarterModSynchronizator_installed',InstalledTools.StarterModSynchronizator_installed);
357     Registr.WriteBool('SourcePackBuilder_installed',InstalledTools.SourcePackBuilder_installed);
358     //Закрываем ключег...
359     Registr.CloseKey;
360     Writeln('done.');
361     Writeln('');
362     //Сообсчаем об успешном завершении инсталляции.
363     Writeln('Installation completed succesfully!');
364     Writeln('');
365   end;
366  
367 end;
368
369 procedure TInstallerServiceClass.ShowDescription;
370 //Вывести описание утилиты.
371 begin
372   inherited;
373   Writeln('Description:');
374   Writeln('             Installs '+AllProjectName+' to your system. No files copying, only');
375   Writeln('             registering in windows registry and environment variables.');
376 end;
377
378
379 /////////////////////////////////
380 initialization
381
382 //Инициализация %). Выделим память, создадим всякую херню... как обычно в общем %)
383 begin
384   InstServClass := TInstallerServiceClass.Create;
385 end;
386
387 finalization
388 //Мочим все лишнее...
389 begin
390   InstServClass.Free;
391 end;
392
393 end.
394
Note: See TracBrowser for help on using the browser.