3 using System.Diagnostics;
\r
5 using NaGet.SubCommands;
\r
6 using System.Xml.Serialization;
\r
8 namespace NaGet.Packages.Install
\r
12 /// ダウンロード・インストール処理をカプセル化するクラス
\r
14 public class Installation
\r
16 private Package installedPackage;
\r
21 public Package InstalledPackage {
\r
22 get { return installedPackage; }
\r
24 installedPackage = value;
\r
26 installerFile = getArchiveFilePath();
\r
27 installerIndex = GetPreferInstallerIndex(value);
\r
32 /// (保存される)インストーラのファイルのパス
\r
34 private string installerFile;
\r
37 /// インストールが完了されたか否かのフラグ
\r
39 private bool installed = false;
\r
42 /// サイレントインストールを行うか否か
\r
44 private bool silent = false;
\r
47 /// 起動するインストーラのインデックス番号
\r
49 protected int installerIndex = 0;
\r
52 /// 外部アプリのエラー出力の受信ハンドラ
\r
54 public event EventHandler<NaGet.Utils.AnyDataEventArgs<string>> ErrorDataReceived;
\r
57 /// 外部アプリの標準出力の受信ハンドラ
\r
59 public event EventHandler<NaGet.Utils.AnyDataEventArgs<string>> OutputDataReceived;
\r
64 public Installation()
\r
71 /// <param name="package">インストールするパッケージ</param>
\r
72 public Installation(Package package)
\r
74 InstalledPackage = package;
\r
80 public string InstallerFile {
\r
81 get { return installerFile; }
\r
85 #region インストーラ状態チェック関連
\r
90 public bool IsInstallablePackage()
\r
92 return installerIndex >= 0;
\r
98 public bool Downloaded {
\r
100 return File.Exists(installerFile) && ((File.GetAttributes(installerFile) & FileAttributes.Hidden) != FileAttributes.Hidden);
\r
105 /// インストール作業済みであるか否か。実際にインストールされたかどうかではありません。
\r
107 public bool Installed {
\r
108 get { return installed; }
\r
112 /// インストーラの処理が成功してインストールされたプログラムが確認できるか否か。
\r
114 public bool InstallSuccessed {
\r
116 switch (InstalledPackage.Type) {
\r
117 case InstallerType.ARCHIVE: // アーカイブインストーラはフォルダの確認
\r
118 return Directory.Exists(Path.Combine(NaGet.Env.ArchiveProgramFiles, InstalledPackage.Name));
\r
119 case InstallerType.EXEC_INSTALLER:
\r
120 case InstallerType.MSI_PACKAGE:
\r
121 return RegistriedUninstallers.GetInstalledPackageFor(InstalledPackage) != null;
\r
129 /// サイレントインストールを行うかのフラグ。
\r
131 public bool Silent {
\r
133 return (SupportsSilentOnly)? true :
\r
134 (IsSupportsSilent)? silent :
\r
137 set { silent = value; }
\r
141 /// サイレントインストールをサポートしているか否か
\r
143 public bool IsSupportsSilent {
\r
145 switch (InstalledPackage.Type) {
\r
146 case InstallerType.ARCHIVE:
\r
147 case InstallerType.MSI_PACKAGE:
\r
149 case InstallerType.EXEC_INSTALLER:
\r
150 return ! string.IsNullOrEmpty(InstalledPackage.SilentInstallArguments);
\r
158 /// サイレントインストールだけをサポートしているか否か
\r
160 public bool SupportsSilentOnly {
\r
161 get { return InstalledPackage.Type == InstallerType.ARCHIVE; }
\r
165 /// 選択されたパッケージは、AppliStationではなくPCへのインストールをするのか否かを返す。
\r
167 /// <remark>RunAsが必要か否かの判断にしようされる</remark>
\r
168 public bool TargetPC {
\r
169 get { return InstalledPackage.Type != InstallerType.ARCHIVE; }
\r
177 /// <param name="downloader">ダウンローダオブジェクト</param>
\r
178 public void Download(Downloader downloader)
\r
181 string url = InstalledPackage.Installer[installerIndex].Url.Href;
\r
182 downloader.Download(url, installerFile);
\r
184 // サーバ指定のファイル名に変更する
\r
185 if (! string.IsNullOrEmpty(downloader.DownloadedFileName)) {
\r
186 string newFile = Path.Combine(Path.GetDirectoryName(installerFile), downloader.DownloadedFileName);
\r
187 File.Move(installerFile, newFile);
\r
188 installerFile = newFile;
\r
193 string targetDir = Path.GetDirectoryName(installerFile);
\r
194 NaGet.Utils.SetAccessControlRecursive(targetDir, File.GetAccessControl(Path.GetDirectoryName(targetDir)));
\r
195 } catch (Exception) {} // 失敗時は何もしない
\r
200 /// インストーラファイルをスキャンする
\r
202 /// <remarks>ウイルスのため退避・削除されたときも例外を投げずにあたかも正常かのように動作しえます。</remarks>
\r
203 /// <exception cref="ComException">スキャンで意図せぬ動作があったとき</exception>
\r
204 /// <exception cref="FileNotFoundException">スキャン後にインストーラファイルが存在しないとき</exception>
\r
205 /// <param name="scanner">スキャナーオブジェクト</param>
\r
206 public void ScanInstallerFile(DownloadScanner scanner)
\r
208 Exception e = null;
\r
210 scanner.Scan(installerFile, InstalledPackage.Installer[installerIndex].Url.Href);
\r
211 } catch (System.Runtime.InteropServices.COMException ex) {
\r
215 if (! File.Exists(installerFile)) {
\r
216 // ファイルが消されているならばFileNotFoundExceptionを出す
\r
217 throw new FileNotFoundException(string.Empty, installerFile, e);
\r
218 } else if ( e != null ) {
\r
219 // ファイルが消されていないが例外が発生していたときは、その例外を投げる
\r
225 /// ハッシュ検証のためのハッシュの種類の数を返す
\r
227 /// <returns>ハッシュの個数</returns>
\r
228 public int GetRegisteredHashCount()
\r
230 HashValue[] hashValues = InstalledPackage.Installer[installerIndex].Hash;
\r
231 return (hashValues == null)? 0 : hashValues.Length;
\r
237 /// <returns>検証にパスしたらtrue、パスしなかったらfalse</returns>
\r
238 public bool VerifyHashValues()
\r
240 HashValue[] hashValues = InstalledPackage.Installer[installerIndex].Hash;
\r
241 if (hashValues != null) {
\r
242 foreach (HashValue hash in hashValues) {
\r
243 if (! hash.Validate(installerFile)) {
\r
252 private int invokeInstaller(string installerfile, InstallerType type)
\r
254 if (! File.Exists(installerfile)) {
\r
255 throw new FileNotFoundException(string.Format("{0} is not found, perhaps failed to download.", installerfile), installerfile);
\r
258 Process hProcess = null;
\r
261 case InstallerType.EXEC_INSTALLER:
\r
263 hProcess = Process.Start(installerfile, InstalledPackage.SilentInstallArguments);
\r
265 hProcess = Process.Start(installerfile);
\r
269 case InstallerType.MSI_PACKAGE:
\r
270 string msiexecArgs = string.Format("{0} /norestart /i \"{1}\" REBOOT=ReallySuppress",
\r
271 (Silent)? "/passive" : string.Empty,
\r
274 hProcess = Process.Start("msiexec", msiexecArgs);
\r
276 case InstallerType.ARCHIVE:
\r
277 string argument = string.Format("-i \"{0}\" \"{1}\"", installerfile, this.InstalledPackage.Name);
\r
278 hProcess = createExtractArchiveProcess(argument,
\r
279 this.OutputDataReceived,
\r
280 this.ErrorDataReceived);
\r
283 throw new NotImplementedException("Not implemented archive installation yet");
\r
285 hProcess.WaitForExit();
\r
287 return hProcess.ExitCode;
\r
289 if (hProcess != null) {
\r
296 /// インストーラ等を起動してインストール作業を行う
\r
298 /// <returns>インストーラの終了コード</returns>
\r
299 public int Install()
\r
301 string installerFile = this.installerFile;
\r
302 string tempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
\r
304 // アーカイブされているなら一旦展開
\r
305 if (InstalledPackage.ArchivedInstaller) {
\r
306 Directory.CreateDirectory(tempDir);
\r
308 string argument = string.Format("-t \"{0}\" \"{1}\"", installerFile, tempDir);
\r
309 using (Process hProcess = createExtractArchiveProcess(argument,
\r
310 this.OutputDataReceived,
\r
311 this.ErrorDataReceived)) {
\r
312 hProcess.WaitForExit();
\r
314 if (hProcess.ExitCode != 0) {
\r
315 throw new ApplicationException("Extract error " + installerFile + " to " + tempDir);
\r
319 installerFile = seekInstallerFile(tempDir, InstalledPackage.Type);
\r
320 if (installerFile == null && Directory.GetDirectories(tempDir).Length == 1) {
\r
321 installerFile = seekInstallerFile(Path.Combine(tempDir, Directory.GetDirectories(tempDir)[0]), InstalledPackage.Type);
\r
325 int exitCode = invokeInstaller(installerFile, InstalledPackage.Type);
\r
333 /// もっともふさわしいインストーラ番号を返す
\r
335 /// <returns></returns>
\r
336 public static int GetPreferInstallerIndex(Package InstalledPackage)
\r
338 if (InstalledPackage.Type == InstallerType.CANNOT_INSTALL) { // インストール不能パッケージ
\r
345 for (int i = 0; i < InstalledPackage.Installer.Length; i++) {
\r
346 Platform platform = InstalledPackage.Installer[i].Platform;
\r
349 if (platform != null) {
\r
350 pts = (platform.IsRunnable())? 10 : 0;
\r
351 pts += (platform.IsRunnableArchOnWow64() && platform.IsRunnableOS())? 1 : 0;
\r
352 } else { // if (platform == null) {
\r
353 pts = 1; // null の場合は動作プラットホーム扱い
\r
355 if (pts > bestVal) {
\r
365 /// インストーラの保存先パスを生成
\r
367 private string getArchiveFilePath()
\r
369 Package package = this.InstalledPackage;
\r
371 string folderName = string.Format("{0}({1})", package.Name, package.Version);
\r
372 string fileName = NaGet.Utils.Url2filename(package.Installer[0].Url.Href);
\r
374 string folder = Path.Combine(NaGet.Env.ArchiveFolderPath, folderName);
\r
376 if (! File.Exists(Path.Combine(folder, fileName))) {
\r
377 if (Directory.Exists(folder)) {
\r
378 if (! File.Exists(Path.Combine(folder, fileName))) {
\r
379 fileName = seekInstallerFile(folder, package.Type) ?? fileName;
\r
382 Directory.CreateDirectory(folder);
\r
386 Directory.SetAccessControl(folder, Directory.GetAccessControl(Path.GetDirectoryName(folder)));
\r
387 } catch (Exception) {} // 失敗時無視
\r
391 return Path.Combine(folder, fileName);
\r
395 /// すでにインストールされているパッケージを取得する
\r
397 /// <param name="installedPkgs">
\r
401 /// インストールされているパッケージの情報。インストールされたパッケージが見つからないならばnullを返す
\r
403 public InstalledPackage GetInstalledPackage(PackageList<InstalledPackage> installedPkgs)
\r
405 return installedPkgs.GetPackageForName(InstalledPackage.Name);
\r
411 /// <param name="basedir">探すフォルダ</param>
\r
412 /// <param name="type">インストーラの種類</param>
\r
413 /// <returns>探し出されたインストーラファイルのフルパス。存在しないならばnull</returns>
\r
414 private static string seekInstallerFile(string basedir, InstallerType type)
\r
416 if (! Directory.Exists(basedir)) {
\r
420 System.Collections.Generic.List<string> list = new System.Collections.Generic.List<string>();
\r
422 case InstallerType.MSI_PACKAGE:
\r
423 list.AddRange(Directory.GetFiles(basedir, "*.msi"));
\r
425 case InstallerType.EXEC_INSTALLER:
\r
426 list.AddRange(Directory.GetFiles(basedir, "*.exe"));
\r
428 case InstallerType.ARCHIVE:
\r
429 list.AddRange(Directory.GetFiles(basedir, "*.zip"));
\r
430 list.AddRange(Directory.GetFiles(basedir, "*.lzh"));
\r
431 list.AddRange(Directory.GetFiles(basedir, "*.cab"));
\r
432 list.AddRange(Directory.GetFiles(basedir, "*.7z"));
\r
433 list.AddRange(Directory.GetFiles(basedir, "*.tar*"));
\r
441 delegate(string file) {
\r
442 return ! File.Exists(file);
\r
446 // "setup"の語が入ったファイルはインストーラとみなし、優先選択
\r
447 foreach (string path in list) {
\r
448 if (Path.GetFileName(path).ToLower().IndexOf("setup") >= 0) {
\r
454 return (list.Count > 0)? list[0] : null;
\r
459 /// アーカイブファイルの展開・インストールを行う
\r
461 /// <param name="archiveInstArgs">"archive-inst.exe"への引数</param>
\r
462 /// <param name="outputReceived">標準出力用リスナ(null可)</param>
\r
463 /// <param name="errorReceived">エラー出力用リスナ(null可)</param>
\r
464 /// <returns>実行プロセス</returns>
\r
465 private Process createExtractArchiveProcess(string archiveInstArgs,
\r
466 EventHandler<NaGet.Utils.AnyDataEventArgs<string>> outputReceived,
\r
467 EventHandler<NaGet.Utils.AnyDataEventArgs<string>> errorReceived)
\r
469 string archiveInstExe = Path.GetFullPath("archive-inst.exe");
\r
470 if (! File.Exists(archiveInstExe)) {
\r
471 string errMsg = string.Format("\"{0}\" does not found!");
\r
472 throw new ApplicationException(errMsg,
\r
473 new FileNotFoundException(errMsg, archiveInstExe));
\r
478 ProcessStartInfo procInfo = new ProcessStartInfo(archiveInstExe, archiveInstArgs);
\r
479 procInfo.UseShellExecute = false;
\r
480 procInfo.CreateNoWindow = true;
\r
481 procInfo.WorkingDirectory = Environment.CurrentDirectory;
\r
483 return NaGet.Utils.ProcessStartWithOutputCapture(procInfo, outputReceived, errorReceived);
\r
487 /// ダウンロードしたインストーラファイルを削除する
\r
489 public virtual void RemoveDownloadedFile()
\r
491 if (Downloaded && File.Exists(installerFile)) {
\r
492 File.Delete(installerFile);
\r
496 public override string ToString()
\r
498 return string.Format("{0}({1})", InstalledPackage.Name, InstalledPackage.Version);
\r
501 public static string ToString(Installation[] installations)
\r
503 string[] strs = new string[installations.Length];
\r
504 for (int i = 0; i < installations.Length; i++) {
\r
505 strs[i] = installations[i].ToString();
\r
507 return string.Join(" ", strs);
\r
511 /// パッケージ配列をインストール処理配列に変換する便利メソッド
\r
513 /// <param name="pkgs">パッケージ配列</param>
\r
514 /// <returns>変換されたインストール処理配列</returns>
\r
515 public static Installation[] ConvertInstallations(Package[] pkgs)
\r
517 Installation[] insts = new Installation[pkgs.Length];
\r
518 for (int i = 0; i < pkgs.Length; i++) {
\r
519 insts[i] = new Installation(pkgs[i]);
\r