OSDN Git Service

na-get-lib,1.2.xまでサポートしていたテキストファイル形式の旧式レポジトリリストファイル(provider.list.txt)の対応コードを削除
[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                                         try {\r
74                                                 File.SetAttributes(targetFilePath, FileAttributes.Normal);\r
75                                                 File.Delete(targetFilePath);\r
76                                         } catch (UnauthorizedAccessException e) {\r
77                                                 throw new IOException(string.Format("Access denied '{0}'", targetFilePath), e);\r
78                                         }\r
79                                 }\r
80                                 File.Move(file, targetFilePath);\r
81                         }\r
82                 }\r
83                 \r
84                 private static void postInstall(string targetDir, Package package)\r
85                 {\r
86                         // SYSTEM32へのコピーの実行\r
87                         if (!string.IsNullOrEmpty(package.System32CopyFiles)) {\r
88                                 if (! Directory.Exists(NaGet.Env.ArchiveSystem32)) {\r
89                                         Directory.CreateDirectory(NaGet.Env.ArchiveSystem32);\r
90                                 }\r
91                                 \r
92                                 string logfile = Path.Combine(NaGet.Env.ArchiveSystem32, ".applistation.install."+package.Name+".log");\r
93                                 if (File.Exists(logfile)) {\r
94                                         File.SetAttributes(logfile, FileAttributes.Normal);\r
95                                 }\r
96                                 using (FileStream fs = new FileStream(logfile, FileMode.Create))\r
97                                 using (StreamWriter sw = new StreamWriter(fs)){\r
98                                         foreach (string pathpat in package.System32CopyFiles.Split(';')) {\r
99                                                 foreach (string path in NaGet.Utils.ExtendWildcardFile(targetDir, pathpat)) {\r
100                                                         if ((File.GetAttributes(path) & FileAttributes.Directory) == 0) { // もしファイルならば\r
101                                                                 string destPath = Path.Combine(NaGet.Env.ArchiveSystem32, Path.GetFileName(path));\r
102                                                                 File.Copy(path, destPath, true);\r
103                                                                 \r
104                                                                 sw.WriteLine(Path.GetFileName(destPath));\r
105                                                         }\r
106                                                 }\r
107                                         }\r
108                                 }\r
109                                 File.SetAttributes(logfile, FileAttributes.Hidden);\r
110                         }\r
111                         \r
112                         // インストールスクリプトの実行\r
113                         if (! string.IsNullOrEmpty(package.InstallScript) ) {\r
114                                 Engine engine = MSBuild.Engine;\r
115                                 Project proj = new Project(engine);\r
116                                 try {\r
117                                         proj.LoadXml(package.InstallScript);\r
118                                 } catch (InvalidProjectFileException e) {\r
119                                         throw new ApplicationException("InstallScript is invalid", e);\r
120                                 }\r
121                                 \r
122                                 engine.BuildProject(proj, "Install");\r
123                         }\r
124                         \r
125                         // 直下のファイルで*.exeがGUIプログラムならプログラムフォルダーに登録\r
126                         foreach (string exeFile in Directory.GetFiles(targetDir, "*.exe")) {\r
127                                 if (NaGet.InteropServices.PEFileInfoUtils.GetPEFileType(exeFile) == NaGet.InteropServices.PEFileType.WinGUI) {\r
128                                         string progGrpPath = Path.Combine(NaGet.Env.ArchiveProgramGroup, package.Name);\r
129                                         if (! Directory.Exists(progGrpPath)) Directory.CreateDirectory(progGrpPath);\r
130                                         \r
131                                         using (NaGet.InteropServices.ShellLink lnk = new NaGet.InteropServices.ShellLink() ) {\r
132                                                 //string path = NaGet.Utils.GetRelativePath(progGrpPath, exeFile);// lnkファイルに相対パス指定不能\r
133                                                 string path = exeFile;\r
134                                                 \r
135                                                 lnk.Path = path;\r
136                                                 //lnk.SetIconLocation(path, 0);\r
137                                                 \r
138                                                 // .lnk ファイル名\r
139                                                 string lnkFilePath = Path.Combine(progGrpPath, lnk.GetSuitableShellLinkNameFor() + ".lnk");\r
140                                                 if (File.Exists(lnkFilePath)) { // ファイル名がかぶってしまったとき\r
141                                                         lnkFilePath = Path.Combine(progGrpPath, Path.GetFileNameWithoutExtension(exeFile) + ".lnk");\r
142                                                 }\r
143                                                 \r
144                                                 // 保存\r
145                                                 lnk.ToPersistFile().Save(lnkFilePath, true);\r
146                                         }\r
147                                 }\r
148                         }\r
149                 }\r
150                 \r
151                 private static void storeInstalledFileList(string targetDir)\r
152                 {\r
153                         string installedFileListPath = Path.Combine(targetDir, InstalledFileListName);\r
154                         if (File.Exists(installedFileListPath)) {\r
155                                 File.SetAttributes(installedFileListPath, FileAttributes.Normal);\r
156                         }\r
157                         InstalledFileList installedFileList = InstalledFileList.CreateFromFiles(targetDir);\r
158                         NaGet.Utils.PutSerializeObject(installedFileListPath, installedFileList);\r
159                         \r
160                         File.SetAttributes(installedFileListPath, FileAttributes.Hidden | FileAttributes.ReadOnly);\r
161                 }\r
162                 \r
163                 private static void storePackageXml(Package package, string destDir)\r
164                 {\r
165                         if (package == null) {\r
166                                 return;\r
167                         }\r
168                         \r
169                         InstalledPackage pkg = InstalledPackage.PackageConverter(package);\r
170                         UninstallInformation uninfo = pkg.UninstallInfo;\r
171                         uninfo.InstallLocation = destDir;\r
172                         uninfo.UninstallString = string.Format("archive-inst -x \"{0}\"", package.Name);\r
173                         uninfo.EstimatedSize = (int) (NaGet.Utils.GetFileSize(destDir) >> 10);\r
174                         uninfo.InstallDateString = DateTime.Now.ToString("yyyyMMdd");\r
175                         pkg.UninstallInfo = uninfo;\r
176                         \r
177                         string packageXmlFilePath = Path.Combine(destDir, InstalledPackageFileName);\r
178                         if (File.Exists(packageXmlFilePath)) {\r
179                                 File.SetAttributes(packageXmlFilePath, FileAttributes.Normal);\r
180                         }\r
181                         NaGet.Utils.PutSerializeObject(packageXmlFilePath, pkg);\r
182                         File.SetAttributes(packageXmlFilePath, FileAttributes.Hidden | FileAttributes.ReadOnly);\r
183                 }\r
184                 \r
185                 private static void removePackage(InstalledPackage package, string targetDir)\r
186                 {\r
187                         // アンインストールスクリプトの実行\r
188                         if (! string.IsNullOrEmpty(package.InstallScript)) {\r
189                                 Engine engine = MSBuild.Engine;\r
190                                 Project proj = new Project(engine);\r
191                                 try {\r
192                                         proj.LoadXml(package.InstallScript);\r
193                                 } catch (InvalidProjectFileException e) {\r
194                                         throw new ApplicationException("InstallScript is invalid", e);\r
195                                 }\r
196                                 \r
197                                 engine.BuildProject(proj, "Uninstall");\r
198                         }\r
199                         \r
200                         // GUIプログラムでプログラムフォルダーに登録しているのを解除\r
201                         string progGrpPath = Path.Combine(NaGet.Env.ArchiveProgramGroup, package.Name);\r
202                         if (Directory.Exists(progGrpPath)) {\r
203                                 NaGet.Utils.SetAttributeRecursive(progGrpPath, FileAttributes.Normal);\r
204                                 Directory.Delete(progGrpPath, true);\r
205                         }\r
206                         \r
207                         // SYSTEM32からの削除の実行\r
208                         if (! string.IsNullOrEmpty(package.System32CopyFiles) ) {\r
209                                 string logfile = Path.Combine(NaGet.Env.ArchiveSystem32, ".applistation.install."+package.Name+".log");\r
210                                 \r
211                                 if (File.Exists(logfile)) {\r
212                                         using (FileStream fs = new FileStream(logfile, FileMode.Open))\r
213                                         using (StreamReader sr = new StreamReader(fs)){\r
214                                                 string fileName = sr.ReadLine().Trim();\r
215                                                 string filePath = Path.Combine(NaGet.Env.ArchiveSystem32, fileName);\r
216                                                 \r
217                                                 if (File.Exists(filePath)) {\r
218                                                         File.SetAttributes(filePath, FileAttributes.Normal);\r
219                                                         File.Delete(filePath);\r
220                                                 }\r
221                                         }\r
222                                         File.SetAttributes(logfile, FileAttributes.Normal);\r
223                                         File.Delete(logfile);\r
224                                 }\r
225                         }\r
226                         \r
227                         try {\r
228                                 NaGet.Utils.SetAttributeRecursive(targetDir, FileAttributes.Normal);\r
229                                 Directory.Delete(targetDir, true);\r
230                         } catch (UnauthorizedAccessException) {\r
231                                 Console.Error.WriteLine("W: could not complete to delete '{0}': Permission denied", targetDir);\r
232                                 Environment.Exit(1);\r
233                         }\r
234                 }\r
235                 \r
236                 private static void parseMainArguments(string[] args, out string arcFile, out string targetDir, out Package package)\r
237                 {\r
238                         if (args.Length < 1) {\r
239                                 throw new ArgumentException();\r
240                         }\r
241                         \r
242                         switch (args[0].ToLower()) {\r
243                                 case "-t":\r
244                                         if (args.Length != 3) {\r
245                                                 throw new ArgumentException();\r
246                                         }\r
247                                         \r
248                                         arcFile = args[1];\r
249                                         targetDir = args[2];\r
250                                         package = null;\r
251                                         break;\r
252                                 case "-i":\r
253                                         if (args.Length != 3) {\r
254                                                 throw new ArgumentException();\r
255                                         }\r
256                                         \r
257                                         arcFile = args[1];\r
258                                         PackageList<Package> pkgList = NaGet.Utils.GetDeserializedObject<PackageList<Package>>(NaGet.Env.PackageListFile);\r
259                                         package = pkgList.GetPackageForName(args[2]);\r
260                                         targetDir = Path.Combine(NaGet.Env.ArchiveProgramFiles, package.Name);\r
261                                         break;\r
262                                 case "-x":\r
263                                         if (args.Length != 2) {\r
264                                                 throw new ArgumentException();\r
265                                         }\r
266                                         \r
267                                         arcFile = null;\r
268                                         targetDir = Path.Combine(NaGet.Env.ArchiveProgramFiles, args[1]);\r
269                                         package = null;\r
270                                         \r
271                                         string filepath = Path.Combine(targetDir, InstalledPackageFileName);\r
272                                         if (File.Exists(filepath)) {\r
273                                                 package = NaGet.Utils.GetDeserializedObject<InstalledPackage>(filepath);\r
274                                         } else {\r
275                                                 Console.Error.WriteLine("Not found or already removed package : {0}", args[1]);\r
276                                                 Environment.Exit(100);\r
277                                         }\r
278                                         break;\r
279                                 default:\r
280                                         arcFile = null;\r
281                                         targetDir = null;\r
282                                         package = null;\r
283                                         Console.Error.WriteLine("Unreconized command \"{0}\".", args[0]);\r
284                                         Environment.Exit(100);\r
285                                         break;\r
286                         }\r
287                 }\r
288                 \r
289                 [STAThread]\r
290                 public static void Main(string[] args)\r
291                 {\r
292                         // アーカイブSYSTEM32をパスに足す\r
293                         NaGet.Utils.AddDirectoryToPath(NaGet.Env.ArchiveSystem32);\r
294                         \r
295                         string arcFile = null;\r
296                         string targetDir = null;\r
297                         Package package = null;\r
298                         \r
299                         // 引数パースおよびヘルプ表示\r
300                         try {\r
301                                 parseMainArguments(args, out arcFile, out targetDir, out package);\r
302                         } catch (ArgumentException) {\r
303                                 string executeFileName = System.AppDomain.CurrentDomain.FriendlyName;\r
304                                 Console.Write("Usage:");\r
305                                 Console.WriteLine("\t{0} -t archive.zip target_dir\tExtraction", executeFileName);\r
306                                 Console.WriteLine("\t{0} -i archive.zip PackageName\tInstall", executeFileName);\r
307                                 Console.WriteLine("\t{0} -x PackageName\t\tUninstall", executeFileName);\r
308                                 Console.WriteLine();\r
309                         }\r
310 \r
311                         // インストールおよび展開処理\r
312                         if (arcFile != null) {\r
313                                 string tempExtractDir = targetDir + "___temp___"; // HACK\r
314                                 Directory.CreateDirectory(tempExtractDir);\r
315                                 \r
316                                 try {\r
317                                         // STEP1. 書庫の展開\r
318                                         if (package != null && package.Type == InstallerType.ITSELF) {\r
319                                                 // 書庫でない場合展開せずにそのままコピーする\r
320                                                 string destFile = Path.Combine(tempExtractDir, Path.GetFileName(arcFile));\r
321                                                 File.Copy(arcFile, destFile);\r
322                                         } else {\r
323                                                 extract(arcFile, tempExtractDir);\r
324                                         }\r
325                                         \r
326                                         // インストールの元となるフォルダを決定する\r
327                                         string installSrc = tempExtractDir;\r
328                                         // 展開先のトップに唯一のフォルダーしかないのであれば、そのフォルダー内を基準とする\r
329                                         if (Directory.GetFiles(tempExtractDir).Length == 0 &&\r
330                                             Directory.GetDirectories(tempExtractDir).Length == 1) {\r
331                                                 installSrc = Directory.GetDirectories(tempExtractDir)[0];\r
332                                         }\r
333                                         \r
334                                         // STEP2. インストール元フォルダでインストールファイルリストの作成\r
335                                         storeInstalledFileList(installSrc);\r
336                                         \r
337                                         // STEP3. インストール\r
338                                         install(installSrc, targetDir);\r
339                                         \r
340                                         if (package != null) {\r
341                                                 // STEP4. カスタマイズ可能な後処理\r
342                                                 postInstall(targetDir, package);\r
343                                                 \r
344                                                 // STEP5. パッケージ情報をインストール先(targetDir)に置く\r
345                                                 storePackageXml(package, targetDir);\r
346                                         }\r
347                                 } catch (DllNotFoundException) {\r
348                                         Console.Error.WriteLine("E: Does not exist archive dll for {0}", arcFile); // TODO\r
349                                         Environment.Exit(10);\r
350                                 } catch (IOException e) {\r
351                                         Console.Error.WriteLine("E: File I/O Error : {0}", e.Message);\r
352                                         Environment.Exit(1);\r
353                                 } finally {\r
354                                         Directory.Delete(tempExtractDir, true);\r
355                                 }\r
356                         } else if (package is InstalledPackage) {\r
357                                 removePackage((InstalledPackage) package, targetDir);\r
358                         }\r
359                 }\r
360         }\r
361 }\r