OSDN Git Service

na-get-lib,ハッシュ検証失敗後にダウンロード再試行する前に「完了」と出ないように修正した。
[applistation/AppliStation.git] / archive-inst / Program.cs
1 using System;\r
2 using System.Text;\r
3 using System.IO;\r
4 using Microsoft.Build.BuildEngine;\r
5 using NaGet.Packages;\r
6 using NaGet.Packages.Install;\r
7 \r
8 namespace ArchiveInstall\r
9 {\r
10         class Program\r
11         {\r
12                 public const string InstalledFileListName = ".applistation.installedfiles.xml";\r
13                 \r
14                 public const string InstalledPackageFileName = ".applistation.package.xml";\r
15                 \r
16                 private static void extract(string arcFile, string extractDestDir)\r
17                 {\r
18                         StringBuilder output = new StringBuilder(1024);\r
19                         int res = NaGet.InteropServices.CommonArchiverExtracter.ExtractArchive(arcFile, extractDestDir, output, IntPtr.Zero);\r
20                         if (res != 0) {\r
21                                 Environment.Exit(res);\r
22                         }\r
23                 }\r
24                 \r
25                 private static void install(string fakeTargetDir, string targetDir)\r
26                 {\r
27                         // ハッシュ比較\r
28                         if (Directory.Exists(targetDir)) {\r
29                                 InstalledFileList list = null;\r
30                                 try {\r
31                                         list = NaGet.Utils.GetDeserializedObject<InstalledFileList>(Path.Combine(targetDir, InstalledFileListName));\r
32                                 } catch {\r
33                                 }\r
34                                 if (list != null) {\r
35                                         // 変更されたファイル(設定ファイル)をキープする処理\r
36                                         foreach (InstalledFile changedFile in list.Verify(targetDir)) {\r
37                                                 string changedFilePath = Path.Combine(targetDir, changedFile.Path);\r
38                                                 string toBeChangedFilePath = Path.Combine(fakeTargetDir, changedFile.Path);\r
39                                                 \r
40                                                 // 新規のファイルは退避させる\r
41                                                 if (File.Exists(toBeChangedFilePath)) {\r
42                                                         File.Move(toBeChangedFilePath, toBeChangedFilePath + ".newfile");\r
43                                                 }\r
44                                                 \r
45                                                 // 変更済みファイルをinstallSrcの方に反映させる\r
46                                                 if (File.Exists(changedFilePath)) {\r
47                                                         if (! Directory.Exists(Path.GetDirectoryName(toBeChangedFilePath))) {\r
48                                                                 // フォルダーがない場合は作る\r
49                                                                 Directory.CreateDirectory(Path.GetDirectoryName(toBeChangedFilePath));\r
50                                                         }\r
51                                                         File.Copy(changedFilePath, toBeChangedFilePath);\r
52                                                 }\r
53                                         }\r
54                                 }\r
55                         } else {\r
56                                 Directory.CreateDirectory(targetDir);\r
57                         }\r
58                         \r
59                         // まずはフォルダーツリーを作成\r
60                         foreach (string dir in Directory.GetDirectories(fakeTargetDir, "*", SearchOption.AllDirectories)) {\r
61                                 string dirPath = NaGet.Utils.GetRelativePath(fakeTargetDir, dir);\r
62                                 string targetDirPath = Path.Combine(targetDir, dirPath);\r
63                                 if (! Directory.Exists(targetDirPath)) {\r
64                                         Directory.CreateDirectory(targetDirPath);\r
65                                 }\r
66                         }\r
67                         \r
68                         // ファイルをインストール(高速化のため移動)\r
69                         foreach (string file in Directory.GetFiles(fakeTargetDir, "*", SearchOption.AllDirectories)) {\r
70                                 string filePath = NaGet.Utils.GetRelativePath(fakeTargetDir, file);\r
71                                 string targetFilePath = Path.Combine(targetDir, filePath);\r
72                                 if (File.Exists(targetFilePath)) {\r
73                                         File.SetAttributes(targetFilePath, FileAttributes.Normal);\r
74                                         File.Delete(targetFilePath);\r
75                                 }\r
76                                 File.Move(file, targetFilePath);\r
77                         }\r
78                 }\r
79                 \r
80                 private static void postInstall(string targetDir, Package package)\r
81                 {\r
82                         // SYSTEM32へのコピーの実行\r
83                         if (!string.IsNullOrEmpty(package.System32CopyFiles)) {\r
84                                 if (! Directory.Exists(NaGet.Env.ArchiveSystem32)) {\r
85                                         Directory.CreateDirectory(NaGet.Env.ArchiveSystem32);\r
86                                 }\r
87                                 \r
88                                 string logfile = Path.Combine(NaGet.Env.ArchiveSystem32, ".applistation.install."+package.Name+".log");\r
89                                 if (File.Exists(logfile)) {\r
90                                         File.SetAttributes(logfile, FileAttributes.Normal);\r
91                                 }\r
92                                 using (FileStream fs = new FileStream(logfile, FileMode.Create))\r
93                                 using (StreamWriter sw = new StreamWriter(fs)){\r
94                                         foreach (string pathpat in package.System32CopyFiles.Split(';')) {\r
95                                                 foreach (string path in NaGet.Utils.ExtendWildcardFile(targetDir, pathpat)) {\r
96                                                         if ((File.GetAttributes(path) & FileAttributes.Directory) == 0) { // もしファイルならば\r
97                                                                 string destPath = Path.Combine(NaGet.Env.ArchiveSystem32, Path.GetFileName(path));\r
98                                                                 File.Copy(path, destPath, true);\r
99                                                                 \r
100                                                                 sw.WriteLine(Path.GetFileName(destPath));\r
101                                                         }\r
102                                                 }\r
103                                         }\r
104                                 }\r
105                                 File.SetAttributes(logfile, FileAttributes.Hidden);\r
106                         }\r
107                         \r
108                         // インストールスクリプトの実行\r
109                         if (! string.IsNullOrEmpty(package.InstallScript) ) {\r
110                                 Engine engine = MSBuild.Engine;\r
111                                 Project proj = new Project(engine);\r
112                                 try {\r
113                                         proj.LoadXml(package.InstallScript);\r
114                                 } catch (InvalidProjectFileException e) {\r
115                                         throw new ApplicationException("InstallScript is invalid", e);\r
116                                 }\r
117                                 \r
118                                 engine.BuildProject(proj, "Install");\r
119                         }\r
120                         \r
121                         // 直下のファイルで*.exeがGUIプログラムならプログラムフォルダーに登録\r
122                         foreach (string exeFile in Directory.GetFiles(targetDir, "*.exe")) {\r
123                                 if (NaGet.InteropServices.PEFileInfoUtils.GetPEFileType(exeFile) == NaGet.InteropServices.PEFileType.WinGUI) {\r
124                                         string progGrpPath = Path.Combine(NaGet.Env.ArchiveProgramGroup, package.Name);\r
125                                         if (! Directory.Exists(progGrpPath)) Directory.CreateDirectory(progGrpPath);\r
126                                         \r
127                                         using (NaGet.InteropServices.ShellLink lnk = new NaGet.InteropServices.ShellLink() ) {\r
128                                                 //string path = NaGet.Utils.GetRelativePath(progGrpPath, exeFile);// lnkファイルに相対パス指定不能\r
129                                                 string path = exeFile;\r
130                                                 \r
131                                                 lnk.Path = path;\r
132                                                 //lnk.SetIconLocation(path, 0);\r
133                                                 \r
134                                                 // .lnk ファイル名\r
135                                                 string lnkFilePath = Path.Combine(progGrpPath, lnk.GetSuitableShellLinkNameFor() + ".lnk");\r
136                                                 if (File.Exists(lnkFilePath)) { // ファイル名がかぶってしまったとき\r
137                                                         lnkFilePath = Path.Combine(progGrpPath, Path.GetFileNameWithoutExtension(exeFile) + ".lnk");\r
138                                                 }\r
139                                                 \r
140                                                 // 保存\r
141                                                 lnk.ToPersistFile().Save(lnkFilePath, true);\r
142                                         }\r
143                                 }\r
144                         }\r
145                 }\r
146                 \r
147                 private static void storeInstalledFileList(string targetDir)\r
148                 {\r
149                         string installedFileListPath = Path.Combine(targetDir, InstalledFileListName);\r
150                         if (File.Exists(installedFileListPath)) {\r
151                                 File.SetAttributes(installedFileListPath, FileAttributes.Normal);\r
152                         }\r
153                         InstalledFileList installedFileList = InstalledFileList.CreateFromFiles(targetDir);\r
154                         NaGet.Utils.PutSerializeObject(installedFileListPath, installedFileList);\r
155                         \r
156                         File.SetAttributes(installedFileListPath, FileAttributes.Hidden | FileAttributes.ReadOnly);\r
157                 }\r
158                 \r
159                 private static void storePackageXml(Package package, string destDir)\r
160                 {\r
161                         if (package == null) {\r
162                                 return;\r
163                         }\r
164                         \r
165                         InstalledPackage pkg = InstalledPackage.PackageConverter(package);\r
166                         UninstallInformation uninfo = pkg.UninstallInfo;\r
167                         uninfo.InstallLocation = destDir;\r
168                         uninfo.UninstallString = string.Format("archive-inst -x \"{0}\"", package.Name);\r
169                         uninfo.EstimatedSize = (int) (NaGet.Utils.GetFileSize(destDir) >> 10);\r
170                         uninfo.InstallDateString = DateTime.Now.ToString("yyyyMMdd");\r
171                         pkg.UninstallInfo = uninfo;\r
172                         \r
173                         string packageXmlFilePath = Path.Combine(destDir, InstalledPackageFileName);\r
174                         if (File.Exists(packageXmlFilePath)) {\r
175                                 File.SetAttributes(packageXmlFilePath, FileAttributes.Normal);\r
176                         }\r
177                         NaGet.Utils.PutSerializeObject(packageXmlFilePath, pkg);\r
178                         File.SetAttributes(packageXmlFilePath, FileAttributes.Hidden | FileAttributes.ReadOnly);\r
179                 }\r
180                 \r
181                 private static void removePackage(InstalledPackage package, string targetDir)\r
182                 {\r
183                         // アンインストールスクリプトの実行\r
184                         if (! string.IsNullOrEmpty(package.InstallScript)) {\r
185                                 Engine engine = MSBuild.Engine;\r
186                                 Project proj = new Project(engine);\r
187                                 try {\r
188                                         proj.LoadXml(package.InstallScript);\r
189                                 } catch (InvalidProjectFileException e) {\r
190                                         throw new ApplicationException("InstallScript is invalid", e);\r
191                                 }\r
192                                 \r
193                                 engine.BuildProject(proj, "Uninstall");\r
194                         }\r
195                         \r
196                         // GUIプログラムでプログラムフォルダーに登録しているのを解除\r
197                         string progGrpPath = Path.Combine(NaGet.Env.ArchiveProgramGroup, package.Name);\r
198                         if (Directory.Exists(progGrpPath)) {\r
199                                 NaGet.Utils.SetAttributeRecursive(progGrpPath, FileAttributes.Normal);\r
200                                 Directory.Delete(progGrpPath, true);\r
201                         }\r
202                         \r
203                         // SYSTEM32からの削除の実行\r
204                         if (! string.IsNullOrEmpty(package.System32CopyFiles) ) {\r
205                                 string logfile = Path.Combine(NaGet.Env.ArchiveSystem32, ".applistation.install."+package.Name+".log");\r
206                                 \r
207                                 if (File.Exists(logfile)) {\r
208                                         using (FileStream fs = new FileStream(logfile, FileMode.Open))\r
209                                         using (StreamReader sr = new StreamReader(fs)){\r
210                                                 string fileName = sr.ReadLine().Trim();\r
211                                                 string filePath = Path.Combine(NaGet.Env.ArchiveSystem32, fileName);\r
212                                                 \r
213                                                 if (File.Exists(filePath)) {\r
214                                                         File.SetAttributes(filePath, FileAttributes.Normal);\r
215                                                         File.Delete(filePath);\r
216                                                 }\r
217                                         }\r
218                                         File.SetAttributes(logfile, FileAttributes.Normal);\r
219                                         File.Delete(logfile);\r
220                                 }\r
221                         }\r
222                         \r
223                         NaGet.Utils.SetAttributeRecursive(targetDir, FileAttributes.Normal);\r
224                         Directory.Delete(targetDir, true);\r
225                 }\r
226                 \r
227                 private static void parseMainArguments(string[] args, out string arcFile, out string targetDir, out Package package)\r
228                 {\r
229                         if (args.Length < 1) {\r
230                                 throw new ArgumentException();\r
231                         }\r
232                         \r
233                         switch (args[0].ToLower()) {\r
234                                 case "-t":\r
235                                         if (args.Length != 3) {\r
236                                                 throw new ArgumentException();\r
237                                         }\r
238                                         \r
239                                         arcFile = args[1];\r
240                                         targetDir = args[2];\r
241                                         package = null;\r
242                                         break;\r
243                                 case "-i":\r
244                                         if (args.Length != 3) {\r
245                                                 throw new ArgumentException();\r
246                                         }\r
247                                         \r
248                                         arcFile = args[1];\r
249                                         PackageList<Package> pkgList = NaGet.Utils.GetDeserializedObject<PackageList<Package>>(NaGet.Env.PackageListFile);\r
250                                         package = pkgList.GetPackageForName(args[2]);\r
251                                         targetDir = Path.Combine(NaGet.Env.ArchiveProgramFiles, package.Name);\r
252                                         break;\r
253                                 case "-x":\r
254                                         if (args.Length != 2) {\r
255                                                 throw new ArgumentException();\r
256                                         }\r
257                                         \r
258                                         arcFile = null;\r
259                                         targetDir = Path.Combine(NaGet.Env.ArchiveProgramFiles, args[1]);\r
260                                         package = null;\r
261                                         \r
262                                         string filepath = Path.Combine(targetDir, InstalledPackageFileName);\r
263                                         if (File.Exists(filepath)) {\r
264                                                 package = NaGet.Utils.GetDeserializedObject<InstalledPackage>(filepath);\r
265                                         } else {\r
266                                                 Console.Error.WriteLine("Not found or already removed package : {0}", args[1]);\r
267                                                 Environment.Exit(100);\r
268                                         }\r
269                                         break;\r
270                                 default:\r
271                                         arcFile = null;\r
272                                         targetDir = null;\r
273                                         package = null;\r
274                                         Console.Error.WriteLine("Unreconized command \"{0}\".", args[0]);\r
275                                         Environment.Exit(100);\r
276                                         break;\r
277                         }\r
278                 }\r
279                 \r
280                 [STAThread]\r
281                 public static void Main(string[] args)\r
282                 {\r
283                         // アーカイブSYSTEM32をパスに足す\r
284                         NaGet.Utils.AddDirectoryToPath(NaGet.Env.ArchiveSystem32);\r
285                         \r
286                         string arcFile = null;\r
287                         string targetDir = null;\r
288                         Package package = null;\r
289                         \r
290                         // 引数パースおよびヘルプ表示\r
291                         try {\r
292                                 parseMainArguments(args, out arcFile, out targetDir, out package);\r
293                         } catch (ArgumentException) {\r
294                                 string executeFileName = System.AppDomain.CurrentDomain.FriendlyName;\r
295                                 Console.Write("Usage:");\r
296                                 Console.WriteLine("\t{0} -t archive.zip target_dir\tExtraction", executeFileName);\r
297                                 Console.WriteLine("\t{0} -i archive.zip PackageName\tInstall", executeFileName);\r
298                                 Console.WriteLine("\t{0} -x PackageName\t\tUninstall", executeFileName);\r
299                                 Console.WriteLine();\r
300                         }\r
301 \r
302                         // インストールおよび展開処理\r
303                         if (arcFile != null) {\r
304                                 string tempExtractDir = targetDir + "___temp___"; // HACK\r
305                                 Directory.CreateDirectory(tempExtractDir);\r
306                                 \r
307                                 try {\r
308                                         // STEP1. 書庫の展開\r
309                                         if (package != null && package.Type == InstallerType.ITSELF) {\r
310                                                 // 書庫でない場合展開せずにそのままコピーする\r
311                                                 string destFile = Path.Combine(tempExtractDir, Path.GetFileName(arcFile));\r
312                                                 File.Copy(arcFile, destFile);\r
313                                         } else {\r
314                                                 extract(arcFile, tempExtractDir);\r
315                                         }\r
316                                         \r
317                                         // インストールの元となるフォルダを決定する\r
318                                         string installSrc = tempExtractDir;\r
319                                         // 展開先のトップに唯一のフォルダーしかないのであれば、そのフォルダー内を基準とする\r
320                                         if (Directory.GetFiles(tempExtractDir).Length == 0 &&\r
321                                             Directory.GetDirectories(tempExtractDir).Length == 1) {\r
322                                                 installSrc = Directory.GetDirectories(tempExtractDir)[0];\r
323                                         }\r
324                                         \r
325                                         // STEP2. インストール元フォルダでインストールファイルリストの作成\r
326                                         storeInstalledFileList(installSrc);\r
327                                         \r
328                                         // STEP3. インストール\r
329                                         install(installSrc, targetDir);\r
330                                         \r
331                                         if (package != null) {\r
332                                                 // STEP4. カスタマイズ可能な後処理\r
333                                                 postInstall(targetDir, package);\r
334                                                 \r
335                                                 // STEP5. パッケージ情報をインストール先(targetDir)に置く\r
336                                                 storePackageXml(package, targetDir);\r
337                                         }\r
338                                 } catch (DllNotFoundException) {\r
339                                         Console.Error.WriteLine("E: Does not exist archive dll for {0}", arcFile); // TODO\r
340                                         Environment.Exit(10);\r
341                                 } catch (IOException e) {\r
342                                         Console.Error.WriteLine("E: File I/O Error : {0}", e.Message);\r
343                                         Environment.Exit(1);\r
344                                 } finally {\r
345                                         Directory.Delete(tempExtractDir, true);\r
346                                 }\r
347                         } else if (package is InstalledPackage) {\r
348                                 removePackage((InstalledPackage) package, targetDir);\r
349                         }\r
350                 }\r
351         }\r
352 }\r