Пример #1
0
        protected override bool GeneratePackage(string nupkg, List<DiagnosticMessage> packDiagnostics)
        {
            var compilerOptions = Project.GetCompilerOptions(
                Project.GetTargetFramework(targetFramework: null).FrameworkName, Configuration);

            if (compilerOptions.CompileInclude == null)
            {
                foreach (var path in Project.Files.SourceFiles)
                {
                    var srcFile = new PhysicalPackageFile
                    {
                        SourcePath = path,
                        TargetPath = Path.Combine("src", Common.PathUtility.GetRelativePath(Project.ProjectDirectory, path))
                    };

                    PackageBuilder.Files.Add(srcFile);
                }
            }
            else
            {
                var includeFiles = IncludeFilesResolver.GetIncludeFiles(compilerOptions.CompileInclude, "/", diagnostics: null);
                foreach (var entry in includeFiles)
                {
                    var srcFile = new PhysicalPackageFile
                    {
                        SourcePath = entry.SourcePath,
                        TargetPath = Path.Combine("src", entry.TargetPath)
                    };

                    PackageBuilder.Files.Add(srcFile);
                }
            }

            return base.GeneratePackage(nupkg, packDiagnostics);
        }
        public void FileInList_AddedToPackage()
        {
            var metaData = new PackageMetadata();
            var file = new PhysicalPackageFile();
            _files.Add(file);

            var packageBuilt = _pc.BuildPackage(_files, metaData);

            Assert.That(packageBuilt.Files[0], Is.EqualTo(file));
        }
Пример #3
0
 protected override bool GeneratePackage(string nupkg, List<DiagnosticMessage> packDiagnostics)
 {
     foreach (var path in Project.Files.SourceFiles)
     {
         var srcFile = new PhysicalPackageFile();
         srcFile.SourcePath = path;
         srcFile.TargetPath = Path.Combine("src", Common.PathUtility.GetRelativePath(Project.ProjectDirectory, path));
         PackageBuilder.Files.Add(srcFile);
     }
     return base.GeneratePackage(nupkg, packDiagnostics);
 }
Пример #4
0
        private void EnsurePackageFiles()
        {
            if (_files != null && _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary <string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            using (Stream stream = GetStream())
            {
                Package package = Package.Open(stream);

                _expandedFolderPath = GetExpandedFolderPath();

                // unzip files inside package
                var files = from part in package.GetParts()
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (PackagePart file in files)
                {
                    string path     = UriUtility.GetPath(file.Uri);
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    using (Stream partStream = file.GetStream())
                    {
                        // only copy the package part to disk if there doesn't exist
                        // a file with the same name.
                        if (!_expandedFileSystem.FileExists(filePath))
                        {
                            using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                            {
                                partStream.CopyTo(targetStream);
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
Пример #5
0
        internal static IEnumerable <PhysicalPackageFile> ResolveSearchPattern(string basePath, string searchPath, string targetPath, bool includeEmptyDirectories)
        {
            string normalizedBasePath;

            return(Enumerable.Select <SearchPathResult, PhysicalPackageFile>(PerformWildcardSearchInternal(basePath, searchPath, includeEmptyDirectories, out normalizedBasePath), delegate(SearchPathResult result) {
                if (!result.IsFile)
                {
                    EmptyFrameworkFolderFile file1 = new EmptyFrameworkFolderFile(ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath));
                    file1.SourcePath = result.Path;
                    return file1;
                }
                PhysicalPackageFile file2 = new PhysicalPackageFile();
                file2.SourcePath = result.Path;
                file2.TargetPath = ResolvePackagePath(normalizedBasePath, searchPath, result.Path, targetPath);
                return file2;
            }));
        }
Пример #6
0
        private void EnsurePackageFiles()
        {
            if (_files != null)
            {
                return;
            }

            _files = new Dictionary <string, PhysicalPackageFile>();
            foreach (var filePath in _fileSystem.GetFiles("", "*.*", true))
            {
                _files[filePath] = new PhysicalPackageFile
                {
                    SourcePath = _fileSystem.GetFullPath(filePath),
                    TargetPath = filePath
                };
            }
        }
Пример #7
0
        private void AddPackage(IPackageManager manager, string id, string version, string payloadAssemblyFilePath)
        {
            PackageBuilder builder = new PackageBuilder();
            builder.Id = id;
            builder.Version = new SemanticVersion(version);
            builder.Description = "dummy description";
            builder.Authors.Add("dummy author");

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = payloadAssemblyFilePath;
            file.TargetPath = "analyzers/" + Path.GetFileName(payloadAssemblyFilePath);
            builder.Files.Add(file);

            using (MemoryStream stream = new MemoryStream())
            {
                builder.Save(stream);
                stream.Position = 0;

                ZipPackage pkg = new ZipPackage(stream);
                manager.InstallPackage(pkg, true, true);
            }
        }
Пример #8
0
 public PhysicalPackageFile(PhysicalPackageFile file)
 {
     SourcePath = file.SourcePath;
     TargetPath = file.TargetPath;
 }
Пример #9
0
        private void EnsurePackageFiles()
        {
            if (_files != null &&
                _expandedFolderPath != null &&
                _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary <string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            var packageName = new PackageName(Id, Version);

            // Only use the cache for expanded folders under %temp%, or set from unit tests
            if (_expandedFileSystem == _tempFileSystem || _forceUseCache)
            {
                Tuple <string, DateTimeOffset> cacheValue;
                DateTimeOffset lastModifiedTime = _fileSystem.GetLastModified(_packagePath);

                // if the cache doesn't exist, or it exists but points to a stale package,
                // then we invalidate the cache and store the new entry.
                if (!_cachedExpandedFolder.TryGetValue(packageName, out cacheValue) ||
                    cacheValue.Item2 < lastModifiedTime)
                {
                    cacheValue = Tuple.Create(GetExpandedFolderPath(), lastModifiedTime);
                    _cachedExpandedFolder[packageName] = cacheValue;
                }

                _expandedFolderPath = cacheValue.Item1;
            }
            else
            {
                _expandedFolderPath = GetExpandedFolderPath();
            }

            using (Stream stream = GetStream())
            {
                var package = new ZipArchive(stream);
                // unzip files inside package
                var files = from part in package.Entries
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (ZipArchiveEntry file in files)
                {
                    string path     = file.FullName.Replace('/', '\\').Replace("%2B", "+");
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    bool copyFile = true;

                    if (copyFile)
                    {
                        using (Stream partStream = file.Open())
                        {
                            try
                            {
                                using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                                {
                                    partStream.CopyTo(targetStream);
                                }
                            }
                            catch (Exception)
                            {
                                // if the file is read-only or has an access denied issue, we just ignore it
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
Пример #10
0
        private void EnsurePackageFiles()
        {
            if (_files != null)
            {
                return;
            }

            _files = new Dictionary<string, PhysicalPackageFile>();
            foreach (var filePath in _fileSystem.GetFiles("", "*.*", true))
            {
                _files[filePath] = new PhysicalPackageFile
                {
                    SourcePath = _fileSystem.GetFullPath(filePath),
                    TargetPath = filePath
                };
            }
        }
Пример #11
0
        private static void BuildPackages()
        {
            var directory = new DirectoryInfo(BuildDirectory);
            XmlSerializer serializer = new XmlSerializer(typeof(game));
            var fs = File.Open(directory.GetFiles().First().FullName, FileMode.Open);
            var game = (game)serializer.Deserialize(fs);
            fs.Close();
            var builder = new NuGet.PackageBuilder()
                              {
                                  Id = game.id,
                                  Description = game.description,
                                  ProjectUrl = new Uri(game.gameurl),
                                  Version = new SemanticVersion(game.version),
                                  Title = game.name,
                                  IconUrl = new Uri(game.iconurl),
                              };
            foreach (var author in game.authors.Split(',')) builder.Authors.Add(author);
            foreach (var tag in game.tags.Split(' ')) builder.Tags.Add(tag);
            // files and maybe release notes
            var allFiles = directory
                .GetFiles("*.*", SearchOption.AllDirectories)
                .Where(x=>x.Extension.ToLower() != ".nupkg" && x.Extension.ToLower() != ".o8g");
            foreach (var file in allFiles)
            {
                var path = file.FullName;
                var relPath = path.Replace(directory.FullName, "\\def");
                var pf = new PhysicalPackageFile() { SourcePath = path, TargetPath = relPath };

                builder.Files.Add(pf);
            }
            var feedPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".nupkg");
            var olPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".o8g");
            var filestream = File.Open(feedPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
            filestream = File.Open(olPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
        }
        public PhysicalPackageAssemblyReference(PhysicalPackageFile file)
            : base(file)
        {

        }
Пример #13
0
        private void EnsurePackageFiles()
        {
            if (_files != null &&
                _expandedFolderPath != null &&
                _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary<string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            var packageName = new PackageName(Id, Version);

            // Only use the cache for expanded folders under %temp%, or set from unit tests
            if (_expandedFileSystem == _tempFileSystem || _forceUseCache)
            {
                Tuple<string, DateTimeOffset> cacheValue;
                DateTimeOffset lastModifiedTime = _fileSystem.GetLastModified(_packagePath);

                // if the cache doesn't exist, or it exists but points to a stale package,
                // then we invalidate the cache and store the new entry.
                if (!_cachedExpandedFolder.TryGetValue(packageName, out cacheValue) ||
                    cacheValue.Item2 < lastModifiedTime)
                {
                    cacheValue = Tuple.Create(GetExpandedFolderPath(), lastModifiedTime);
                    _cachedExpandedFolder[packageName] = cacheValue;
                }

                _expandedFolderPath = cacheValue.Item1;
            }
            else
            {
                _expandedFolderPath = GetExpandedFolderPath();
            }

            using (Stream stream = GetStream())
            {
                var package = new ZipArchive(stream);
                // unzip files inside package
                var files = from part in package.Entries
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (ZipArchiveEntry file in files)
                {
                    string path = file.FullName.Replace('/', '\\').Replace("%2B", "+");
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    bool copyFile = true;

                    if (copyFile)
                    {
                        using (Stream partStream = file.Open())
                        {
                            try
                            {
                                using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                                {
                                    partStream.CopyTo(targetStream);
                                }
                            }
                            catch (Exception)
                            {
                                // if the file is read-only or has an access denied issue, we just ignore it
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
Пример #14
0
        private static void BuildPackages()
        {
            var directory = new DirectoryInfo(BuildDirectory);
            XmlSerializer serializer = new XmlSerializer(typeof(game));
            var fs = File.Open(directory.GetFiles().First(x=>x.Name == "definition.xml").FullName, FileMode.Open);
            var game = (game)serializer.Deserialize(fs);
            fs.Close();
            var builder = new NuGet.PackageBuilder()
                              {
                                  Id = game.id,
                                  Description = game.description,
                                  ProjectUrl = new Uri(game.gameurl),
                                  Version = new SemanticVersion(game.version),
                                  Title = game.name,
                                  IconUrl = new Uri(game.iconurl),
                              };
            foreach (var author in game.authors.Split(',')) builder.Authors.Add(author);
            foreach (var tag in game.tags.Split(' ')) builder.Tags.Add(tag);
            // files and maybe release notes

            var baseRefPath = "\\def";

            foreach (var dir in directory.GetDirectories())
            {
                if (dir.Name == "Sets")
                {
                    var refpath = baseRefPath + "\\" + "Sets" + "\\";
                    foreach (var setdir in dir.GetDirectories())
                    {
                        var doc = XDocument.Load(Path.Combine(setdir.FullName, "set.xml"));
                        var gameId = doc.Root.Attribute("id").Value;
                        var setRefPath = refpath + gameId;
                        foreach (var f in setdir.GetFiles("*", SearchOption.AllDirectories))
                        {
                            var relPath = f.FullName.Replace(setdir.FullName, setRefPath);
                            var pf = new PhysicalPackageFile() { SourcePath = f.FullName, TargetPath = relPath };
                            builder.Files.Add(pf);
                        }
                    }
                }
                else
                {
                    var refpath = baseRefPath + "\\" + dir.Name;
                    var files = dir.GetFiles("*", SearchOption.AllDirectories);
                    foreach (var f in files)
                    {
                        var relPath = f.FullName.Replace(dir.FullName, refpath);
                        var pf = new PhysicalPackageFile() { SourcePath = f.FullName, TargetPath = relPath };
                        builder.Files.Add(pf);
                    }
                }
            }
            var defFile = new FileInfo(Path.Combine(directory.FullName, "definition.xml"));
            var defFilePack = new PhysicalPackageFile()
                                  {
                                      SourcePath = defFile.FullName,
                                      TargetPath =
                                          defFile.FullName.Replace(defFile.Directory.FullName, baseRefPath)
                                  };
            builder.Files.Add(defFilePack);

            //var allFiles = directory
            //    .GetFiles("*.*", SearchOption.AllDirectories)
            //    .Where(x=>x.Extension.ToLower() != ".nupkg" && x.Extension.ToLower() != ".o8g");
            //foreach (var file in allFiles)
            //{
            //    //Sets\0abccf03-2825-4b6e-ba59-698408a2005c
            //    var path = file.FullName;
            //    var relPath = path.Replace(directory.FullName, "\\def");
            //    var pf = new PhysicalPackageFile() { SourcePath = path, TargetPath = relPath };

            //    builder.Files.Add(pf);
            //}
            var feedPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".nupkg");
            var olPath = Path.Combine(directory.FullName, game.name + '-' + game.version + ".o8g");
            O8gPath = olPath;
            NupkgPath = feedPath;
            Console.WriteLine("Feed Path: " + feedPath);
            Console.WriteLine("Manual Path: " + olPath);
            var filestream = File.Open(feedPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
            filestream = File.Open(olPath, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            builder.Save(filestream);
            filestream.Flush(true);
            filestream.Close();
        }
Пример #15
0
        protected virtual bool GeneratePackage(string nupkg, List<DiagnosticMessage> packDiagnostics)
        {
            foreach (var sharedFile in Project.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = Path.Combine("shared", Path.GetFileName(sharedFile));
                PackageBuilder.Files.Add(file);
            }

            if (Project.PackOptions.PackInclude != null)
            {
                var files = IncludeFilesResolver.GetIncludeFiles(Project.PackOptions.PackInclude, "/", diagnostics: packDiagnostics);
                PackageBuilder.Files.AddRange(GetPackageFiles(files, packDiagnostics));
            }
            else if (Project.Files.PackInclude != null && Project.Files.PackInclude.Any())
            {
                AddPackageFiles(Project.Files.PackInclude, packDiagnostics);
            }

            // Write the packages as long as we're still in a success state.
            if (!packDiagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                Reporter.Verbose.WriteLine($"Adding package files");
                foreach (var file in PackageBuilder.Files.OfType<PhysicalPackageFile>())
                {
                    if (file.SourcePath != null && File.Exists(file.SourcePath))
                    {
                        Reporter.Verbose.WriteLine($"Adding {file.Path.Yellow()}");
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(nupkg));

                using (var fs = File.Create(nupkg))
                {
                    PackageBuilder.Save(fs);
                    Reporter.Output.WriteLine($"{Project.Name} -> {Path.GetFullPath(nupkg)}");
                }

                return true;
            }

            return false;
        }
        private void AddDummyFile(PackageBuilder builder, string targetPath)
        {
            string dummyContentFilesDir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "dummyContent");
            string fileName = "dummy" + System.Guid.NewGuid().ToString() + ".txt";

            string fullFilePath = TestUtils.CreateTextFile(dummyContentFilesDir, fileName, "dummy content");

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = fullFilePath;
            file.TargetPath = targetPath;
            builder.Files.Add(file);
        }
Пример #17
0
        private void EnsurePackageFiles()
        {
            if ((this._files == null) || ((this._expandedFolderPath == null) || !this._expandedFileSystem.DirectoryExists(this._expandedFolderPath)))
            {
                this._files = new Dictionary <string, PhysicalPackageFile>();
                this._supportedFrameworks = null;
                PackageName key = new PackageName(base.Id, base.Version);
                if (!ReferenceEquals(this._expandedFileSystem, _tempFileSystem) && !this._forceUseCache)
                {
                    this._expandedFolderPath = this.GetExpandedFolderPath();
                }
                else
                {
                    Tuple <string, DateTimeOffset> tuple;
                    DateTimeOffset lastModified = this._fileSystem.GetLastModified(this._packagePath);
                    if (!_cachedExpandedFolder.TryGetValue(key, out tuple) || (tuple.Item2 < lastModified))
                    {
                        tuple = Tuple.Create <string, DateTimeOffset>(this.GetExpandedFolderPath(), lastModified);
                        _cachedExpandedFolder[key] = tuple;
                    }
                    this._expandedFolderPath = tuple.Item1;
                }
                using (Stream stream = this.GetStream())
                {
                    using (IEnumerator <PackagePart> enumerator = (from part in Package.Open(stream).GetParts()
                                                                   where ZipPackage.IsPackageFile(part)
                                                                   select part).GetEnumerator())
                    {
                        string path;
                        string str2;
                        goto TR_0023;
TR_000E:
                        PhysicalPackageFile file1 = new PhysicalPackageFile();
                        file1.SourcePath          = this._expandedFileSystem.GetFullPath(str2);
                        file1.TargetPath          = path;
                        this._files[path]         = file1;
TR_0023:
                        while (true)
                        {
                            if (enumerator.MoveNext())
                            {
                                PackagePart current = enumerator.Current;
                                path = UriUtility.GetPath(current.Uri);
                                str2 = Path.Combine(this._expandedFolderPath, path);
                                bool flag = true;
                                if (this._expandedFileSystem.FileExists(str2))
                                {
                                    using (Stream stream2 = current.GetStream())
                                    {
                                        using (Stream stream3 = this._expandedFileSystem.OpenFile(str2))
                                        {
                                            flag = stream2.Length != stream3.Length;
                                        }
                                    }
                                }
                                if (flag)
                                {
                                    Stream stream4 = current.GetStream();
                                    try
                                    {
                                        using (Stream stream5 = this._expandedFileSystem.CreateFile(str2))
                                        {
                                            stream4.CopyTo(stream5);
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                    finally
                                    {
                                        if (stream4 != null)
                                        {
                                            stream4.Dispose();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                return;
                            }
                            break;
                        }
                        goto TR_000E;
                    }
                }
            }
        }
Пример #18
0
        private void BuildPackage(Project project, string assemblyPath, PackageBuilder builder, FrameworkName targetFramework)
        {
            var framework = targetFramework;
            var dependencies = new List<PackageDependency>();

            var frameworkReferences = new HashSet<string>(_resolver.GetFrameworkReferences(framework), StringComparer.OrdinalIgnoreCase);
            var frameworkAssemblies = new List<string>();

            if (project.Dependencies.Count > 0)
            {
                foreach (var dependency in project.Dependencies)
                {
                    if (frameworkReferences.Contains(dependency.Name))
                    {
                        frameworkAssemblies.Add(dependency.Name);
                    }
                    else
                    {
                        var dependencyVersion = new VersionSpec()
                        {
                            IsMinInclusive = true,
                            MinVersion = dependency.Version
                        };
                        if (dependencyVersion.MinVersion == null || dependencyVersion.MinVersion.IsSnapshot)
                        {
                            var actual = _packages
                                .Where(pkg => string.Equals(pkg.Identity.Name, project.Name, StringComparison.OrdinalIgnoreCase))
                                .SelectMany(pkg => pkg.Dependencies)
                                .SingleOrDefault(dep => string.Equals(dep.Name, dependency.Name, StringComparison.OrdinalIgnoreCase));
                            if (actual != null)
                            {
                                dependencyVersion.MinVersion = actual.Version;
                            }
                        }

                        dependencies.Add(new PackageDependency(dependency.Name, dependencyVersion));
                    }
                }

                if (dependencies.Count > 0)
                {
                    builder.DependencySets.Add(new PackageDependencySet(framework, dependencies));
                }
            }

            // Only do this on full desktop
            if (targetFramework.Identifier == VersionUtility.DefaultTargetFramework.Identifier)
            {
                foreach (var a in frameworkAssemblies)
                {
                    builder.FrameworkReferences.Add(new FrameworkAssemblyReference(a));
                }
            }

            var file = new PhysicalPackageFile();
            file.SourcePath = assemblyPath;
            var folder = VersionUtility.GetShortFrameworkName(framework);
            file.TargetPath = String.Format(@"lib\{0}\{1}.dll", folder, project.Name);
            builder.Files.Add(file);
        }
Пример #19
0
        public override bool Equals(object obj)
        {
            PhysicalPackageFile file = obj as PhysicalPackageFile;

            return((file != null) && (string.Equals(this.SourcePath, file.SourcePath, StringComparison.OrdinalIgnoreCase) && string.Equals(this.TargetPath, file.TargetPath, StringComparison.OrdinalIgnoreCase)));
        }
Пример #20
0
		public void AddFile (string fileName)
		{
			var file = new PhysicalPackageFile ();
			file.TargetPath = fileName.ToNativePath ();
			FilesList.Add (file);
		}
        private void WatchPhysicalFile(PhysicalPackageFile physicalFile)
        {
            string folderPath = System.IO.Path.GetDirectoryName(physicalFile.OriginalPath);
            string fileName = System.IO.Path.GetFileName(physicalFile.OriginalPath);

            _watcher = new FileSystemWatcher(folderPath, fileName)
                       {
                           IncludeSubdirectories = false,
                           EnableRaisingEvents = true
                       };

            _watcher.Changed += OnFileChanged;
            _watcher.Deleted += OnFileDeleted;
            _watcher.Renamed += OnFileDeleted;
        }
        public void AddFile(PackageFile file, bool makeCopy = false)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            if (Contains(file))
            {
                return;
            }

            PackagePart newFile;

            if (makeCopy)
            {
                string fileCopyPath;
                using (Stream originalFileStream = file.GetStream())
                {
                    fileCopyPath = FileHelper.CreateTempFile(file.Name, originalFileStream);
                }

                string newTargetPath = this.Path + "\\" + file.Name;
                var physicalFile = new PhysicalPackageFile(isTempFile: true, originalPath: fileCopyPath, targetPath: newTargetPath);

                newFile = new PackageFile(physicalFile, file.Name, this);
            }
            else
            {
                // detach from current parent
                if (file.Parent != null)
                {
                    file.Parent.Detach(file);
                }

                newFile = file;
            }

            Attach(newFile);
            newFile.IsSelected = true;
            IsExpanded = true;
            PackageViewModel.NotifyChanges();
        }
        private void InnerCreatePackage(KeyValuePair<Tuple<SemanticVersion, string>, DllReference> mainAssembly, bool logToSlack)
        {
            try
            {
                var metadata = new ManifestMetadata()
                {
                    Authors = _author,
                    Version = mainAssembly.Key.Item1.ToString(),
                    Id = mainAssembly.Key.Item2,
                    Description = "automatically created package using nuget-converter for " + mainAssembly.Key.Item2,
                    Owners = _owner,
                    RequireLicenseAcceptance = false
                };

                var builder = new PackageBuilder();
                var dependencies = new List<PackageDependency>();

                //Common Dependancies
                var asmReferencies = mainAssembly.Value;
                Trace.TraceInformation($"Resolving Cached Dependencies for {asmReferencies.Id.Item2}-{asmReferencies.Id.Item1}...");
                foreach (var dependency in asmReferencies.AssemblyReferences)
                {
                    Trace.TraceInformation($"Resolving Dependency {dependency.Item2}-{dependency.Item1}...");
                    //CIRCULAR REFERENCE STEP 1 : This dependency reference the current package, let's avoid referencing it.
                    if (IsDependencyCircular(mainAssembly, dependency))
                        continue;
                    
                    var packageId = _dependenciesResolverService.GetDependencyFromCacheOrResolve(mainAssembly.Value, dependency);
                    if (packageId == null)
                        throw new VersionNotFoundException($"{dependency.Item2}-{dependency.Item1} was not found on official repository/assemblies directory and none of nugetconverter.ini files on assemblies directory provide custom mapping to help me.");

                    //Package is already added or it reference it self we can ignore it 
                    if (!dependencies.Any(_ => _.Id.Equals(packageId.Item2))
                            // Package already referenced We can ignore it
                             && (packageId.Item2 != mainAssembly.Key.Item2 || packageId.Item1 != mainAssembly.Key.Item1))
                    {
                        var semanticVersion = new VersionSpec {MinVersion = packageId.Item1, IsMinInclusive = true};
                        dependencies.Add(new PackageDependency(packageId.Item2, semanticVersion));

                        //CIRCULAR REFERENCE STEP 2 :
                        //We removed the circular dependency previously
                        //to be sure everything is still working we add it again at an upper level.
                        // LibA
                        //   |_jaxen
                        //     |_jdom
                        //       |_jaxen
                        //         |_jdom
                        //         ...
                        //Into
                        //// LibA
                        //   |_jaxen
                        //   |_jdom
                        //     |_jaxen
                        var circularDependency = _configurationService.Get().CircularMapping.FirstOrDefault(__ => packageId.Item2 == __.Item1 && dependencies.All(_ => _.Id != __.Item2.Item1));
                        if(circularDependency!=null)
                                dependencies.Add(new PackageDependency(circularDependency.Item2.Item1, new VersionSpec(circularDependency.Item2.Item2)));
                    }
                }

                var manifestFileDll = new PhysicalPackageFile();
                manifestFileDll.SourcePath = asmReferencies.Path;
                manifestFileDll.TargetPath = @"lib\" + asmReferencies.FrameworkVersion + @"\" + Path.GetFileName(asmReferencies.Path);
                builder.Files.Add(manifestFileDll);

                var pdb = asmReferencies.Path.Replace(".dll", ".pdb");
                if (File.Exists(pdb))
                {
                    var manifestFilePdb = new PhysicalPackageFile();
                    manifestFilePdb.SourcePath = pdb;
                    manifestFilePdb.TargetPath = @"lib\" + asmReferencies.FrameworkVersion + @"\" + Path.GetFileNameWithoutExtension(asmReferencies.Path) + ".pdb";
                    builder.Files.Add(manifestFilePdb);
                }

                var xml = asmReferencies.Path.Replace(".dll", ".xml");
                if (File.Exists(xml))
                {
                    var manifestFileXml = new PhysicalPackageFile();
                    manifestFileXml.SourcePath = xml;
                    manifestFileXml.TargetPath = @"lib\" + asmReferencies.FrameworkVersion + @"\" + Path.GetFileNameWithoutExtension(asmReferencies.Path) + ".xml";
                    builder.Files.Add(manifestFileXml);
                }

                builder.DependencySets.Add(new PackageDependencySet(VersionUtility.ParseFrameworkName(asmReferencies.FrameworkVersion), dependencies));

                WritePackage(builder, metadata);

                // We absolutly need to generate extra package and keep the original
                // one in order to check cyclic dependancies
                var configuration = _configurationService.Get();
                foreach (var packageMapping in configuration.PackageMapping)
                {
                    var packageMappingMatching = packageMapping.Item2.Match(mainAssembly.Key.Item2);
                    if (packageMappingMatching.Success)
                    {
                        var group = packageMappingMatching.Groups[packageMapping.Item1];
                        if (group.Success)
                        {
                            metadata.Id = mainAssembly.Key.Item2.Replace(group.Value, packageMapping.Item1);
                            Trace.TraceWarning($"nugetconverter.ini asked to generate an extra {metadata.Id} package");
                            WritePackage(builder, metadata);
                        }
                    }

                }
            }
            catch (Exception exception)
            {
                var package = NugetRepository + mainAssembly.Key.Item2 + NugetSeparator + mainAssembly.Key.Item1 + ".nupkg";
                SendError(logToSlack, package, exception.Message);

                if (File.Exists(package))
                    File.Delete(package);
            }
        }
Пример #24
0
        public bool Build()
        {
            var projectDiagnostics = new List<ICompilationMessage>();
            Runtime.Project project;
            if (!Runtime.Project.TryGetProject(_buildOptions.ProjectDir, out project, projectDiagnostics))
            {
                LogError(string.Format("Unable to locate {0}.", Runtime.Project.ProjectFileName));
                return false;
            }

            var sw = Stopwatch.StartNew();

            var baseOutputPath = GetBuildOutputDir(_buildOptions);
            var configurations = _buildOptions.Configurations.DefaultIfEmpty("Debug");

            string frameworkSelectionError;
            var frameworks = FrameworkSelectionHelper.SelectFrameworks(project,
                                                                       _buildOptions.TargetFrameworks,
                                                                       _applicationEnvironment.RuntimeFramework,
                                                                       out frameworkSelectionError);

            if (frameworks == null)
            {
                LogError(frameworkSelectionError);
                return false;
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(project, "prepack", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return false;
            }

            if (!ScriptExecutor.Execute(project, "prebuild", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return false;
            }

            var success = true;

            var allDiagnostics = new List<ICompilationMessage>();
            var cacheContextAccessor = new CacheContextAccessor();
            var cache = new Cache(cacheContextAccessor);

            PackageBuilder packageBuilder = null;
            PackageBuilder symbolPackageBuilder = null;
            InstallBuilder installBuilder = null;

            // Build all specified configurations
            foreach (var configuration in configurations)
            {
                if (_buildOptions.GeneratePackages)
                {
                    // Create a new builder per configuration
                    packageBuilder = new PackageBuilder();
                    symbolPackageBuilder = new PackageBuilder();
                    InitializeBuilder(project, packageBuilder);
                    InitializeBuilder(project, symbolPackageBuilder);

                    installBuilder = new InstallBuilder(project, packageBuilder, _buildOptions.Reports);
                }

                var configurationSuccess = true;

                baseOutputPath = Path.Combine(baseOutputPath, configuration);

                // Build all target frameworks a project supports
                foreach (var targetFramework in frameworks)
                {
                    _buildOptions.Reports.Information.WriteLine();
                    _buildOptions.Reports.Information.WriteLine("Building {0} for {1}",
                        project.Name, targetFramework.ToString().Yellow().Bold());

                    var diagnostics = new List<ICompilationMessage>();

                    var context = new BuildContext(_hostServices,
                                                   _applicationEnvironment,
                                                   cache,
                                                   cacheContextAccessor,
                                                   project,
                                                   targetFramework,
                                                   configuration,
                                                   baseOutputPath);

                    context.Initialize(_buildOptions.Reports.Quiet);

                    if (context.Build(diagnostics))
                    {
                        if (_buildOptions.GeneratePackages)
                        {
                            context.PopulateDependencies(packageBuilder);
                            context.AddLibs(packageBuilder, "*.dll");
                            context.AddLibs(packageBuilder, "*.xml");
                            context.AddLibs(symbolPackageBuilder, "*.*");
                        }
                    }
                    else
                    {
                        configurationSuccess = false;
                    }

                    allDiagnostics.AddRange(diagnostics);

                    WriteDiagnostics(diagnostics);
                }

                success = success && configurationSuccess;

                if (_buildOptions.GeneratePackages)
                {
                    // Create a package per configuration
                    string nupkg = GetPackagePath(project, baseOutputPath);
                    string symbolsNupkg = GetPackagePath(project, baseOutputPath, symbols: true);

                    if (configurationSuccess)
                    {
                        // Generates the application package only if this is an application packages
                        configurationSuccess = installBuilder.Build(baseOutputPath);
                        success = success && configurationSuccess;
                    }

                    if (configurationSuccess)
                    {
                        foreach (var sharedFile in project.Files.SharedFiles)
                        {
                            var file = new PhysicalPackageFile();
                            file.SourcePath = sharedFile;
                            file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile));
                            packageBuilder.Files.Add(file);
                        }

                        var root = project.ProjectDirectory;

                        foreach (var path in project.Files.SourceFiles)
                        {
                            var srcFile = new PhysicalPackageFile();
                            srcFile.SourcePath = path;
                            srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path));
                            symbolPackageBuilder.Files.Add(srcFile);
                        }

                        using (var fs = File.Create(nupkg))
                        {
                            packageBuilder.Save(fs);
                            _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", project.Name, nupkg);
                        }

                        if (symbolPackageBuilder.Files.Any())
                        {
                            using (var fs = File.Create(symbolsNupkg))
                            {
                                symbolPackageBuilder.Save(fs);
                            }

                            _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", project.Name, symbolsNupkg);
                        }
                    }
                }
            }

            if (!ScriptExecutor.Execute(project, "postbuild", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return false;
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(project, "postpack", GetScriptVariable))
            {
                LogError(ScriptExecutor.ErrorMessage);
                return false;
            }

            sw.Stop();

            if (projectDiagnostics.Any())
            {
                // Add a new line to separate the project diagnostics information from compilation diagnostics
                _buildOptions.Reports.Information.WriteLine();

                projectDiagnostics.ForEach(d => LogWarning(d.FormattedMessage));
            }

            allDiagnostics.AddRange(projectDiagnostics);
            WriteSummary(allDiagnostics);

            _buildOptions.Reports.Information.WriteLine("Time elapsed {0}", sw.Elapsed);
            return success;
        }
Пример #25
0
        private static bool GeneratePackage(Project project, PackageBuilder packageBuilder, string nupkg, List<DiagnosticMessage> packDiagnostics)
        {
            foreach (var sharedFile in project.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = Path.Combine("shared", Path.GetFileName(sharedFile));
                packageBuilder.Files.Add(file);
            }

            var root = project.ProjectDirectory;

            if (project.Files.PackInclude != null && project.Files.PackInclude.Any())
            {
                AddPackageFiles(project, project.Files.PackInclude, packageBuilder, packDiagnostics);
            }

            // Write the packages as long as we're still in a success state.
            if (!packDiagnostics.Any(d => d.Severity == DiagnosticMessageSeverity.Error))
            {
                Reporter.Verbose.WriteLine($"Adding package files");
                foreach (var file in packageBuilder.Files.OfType<PhysicalPackageFile>())
                {
                    if (file.SourcePath != null && File.Exists(file.SourcePath))
                    {
                        Reporter.Verbose.WriteLine($"Adding {file.Path.Yellow()}");
                    }
                }

                Directory.CreateDirectory(Path.GetDirectoryName(nupkg));

                using (var fs = File.Create(nupkg))
                {
                    packageBuilder.Save(fs);
                    Reporter.Output.WriteLine($"{project.Name} -> {Path.GetFullPath(nupkg)}");
                }

                return true;
            }

            return false;
        }
        private Stream BuildPackageToStream(ManifestMetadata metadata, Stream outputStream)
        {
            string testDir = TestUtils.EnsureTestDirectoryExists(this.TestContext, "source");
            string dummyTextFile = TestUtils.CreateTextFile(Guid.NewGuid().ToString(), testDir, "content");

            PackageBuilder packageBuilder = new PackageBuilder();

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = dummyTextFile;
            file.TargetPath = "dummy.txt";
            packageBuilder.Files.Add(file);

            packageBuilder.Populate(metadata);
            packageBuilder.Save(outputStream);

            // Assert correct function of the above code when versions are specifically "Release" or "Prerelease"            
            if (String.Equals(metadata.Version, ReleaseVersion, StringComparison.CurrentCulture))
            {
                Assert.IsTrue(packageBuilder.IsReleaseVersion());
            }
            else if (String.Equals(metadata.Version, PreReleaseVersion, StringComparison.CurrentCulture))
            {
                Assert.IsFalse(packageBuilder.IsReleaseVersion());
            }

            return outputStream;
        }
        public PackageFile AddFile(string filePath, bool isTempFile)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentException("File does not exist.", "filePath");
            }

            string newFileName = System.IO.Path.GetFileName(filePath);
            if (ContainsFolder(newFileName))
            {
                PackageViewModel.UIServices.Show(Resources.FileNameConflictWithExistingDirectory, MessageLevel.Error);
                return null;
            }

            bool showingRemovedFile = false;
            if (ContainsFile(newFileName))
            {
                bool confirmed = PackageViewModel.UIServices.Confirm(
                    Resources.ConfirmToReplaceExsitingFile_Title,
                    String.Format(CultureInfo.CurrentCulture, Resources.ConfirmToReplaceExsitingFile, newFileName),
                    isWarning: true);

                if (confirmed)
                {
                    var part = this[newFileName] as PackageFile;
                    showingRemovedFile = PackageViewModel.IsShowingFileContent(part);

                    // remove the existing file before adding the new one
                    RemoveChildByName(newFileName);
                }
                else
                {
                    return null;
                }
            }

            string newTargetPath = this.Path + "\\" + newFileName;
            var physicalFile = new PhysicalPackageFile(isTempFile, filePath, newTargetPath);
            var newFile = new PackageFile(physicalFile, newFileName, this);

            Children.Add(newFile);
            newFile.IsSelected = true;
            IsExpanded = true;
            PackageViewModel.NotifyChanges();

            if (showingRemovedFile)
            {
                PackageViewModel.ShowFileContent(newFile);
            }

            return newFile;
        }
Пример #28
0
 public PhysicalPackageAssemblyReference(PhysicalPackageFile file) : base(file)
 {
 }
        private IPackage AddPackage(IPackageManager manager, string id, string version, string payloadAssemblyFilePath, params IPackage[] dependencies)
        {
            PackageBuilder builder = new PackageBuilder();

            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "dummy author 1,dummy author 2",
                Owners = "dummy owner 1,dummy owner 2",
                Title = "dummy title",
                Version = new SemanticVersion(version).ToString(),
                Id = id,
                Description = "dummy description",
                LicenseUrl = "http://my.license/readme.txt",
                ProjectUrl = "http://dummyurl/"
            };

            List<ManifestDependency> dependencyList = new List<ManifestDependency>();
            foreach (IPackage dependencyNode in dependencies)
            {
                dependencyList.Add(new ManifestDependency()
                {
                    Id = dependencyNode.Id,
                    Version = dependencyNode.Version.ToString(),
                });
            }

            List<ManifestDependencySet> dependencySetList = new List<ManifestDependencySet>()
            {
                new ManifestDependencySet()
                {
                    Dependencies = dependencyList
                }
            };
            metadata.DependencySets = dependencySetList;

            builder.Populate(metadata);

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = payloadAssemblyFilePath;
            file.TargetPath = "analyzers/" + Path.GetFileName(payloadAssemblyFilePath);
            builder.Files.Add(file);

            using (MemoryStream stream = new MemoryStream())
            {
                builder.Save(stream);
                stream.Position = 0;

                ZipPackage pkg = new ZipPackage(stream);
                manager.InstallPackage(pkg, true, true);

                return pkg;
            }
        }
Пример #30
0
        private IPackage AddPackage(IPackageManager manager, string id, string version, string payloadAssemblyFilePath)
        {
            PackageBuilder builder = new PackageBuilder();
            builder.Id = id;
            builder.Title = "dummy title";
            builder.Version = new SemanticVersion(version);
            builder.Description = "dummy description";

            builder.Authors.Add("dummy author 1");
            builder.Authors.Add("dummy author 2");

            builder.Owners.Add("dummy owner 1");
            builder.Owners.Add("dummy owner 2");

            builder.ProjectUrl = new System.Uri("http://dummyurl/");
            builder.LicenseUrl = new Uri("http://my.license/readme.txt");


            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = payloadAssemblyFilePath;
            file.TargetPath = "analyzers/" + Path.GetFileName(payloadAssemblyFilePath);
            builder.Files.Add(file);

            using (MemoryStream stream = new MemoryStream())
            {
                builder.Save(stream);
                stream.Position = 0;

                ZipPackage pkg = new ZipPackage(stream);
                manager.InstallPackage(pkg, true, true);

                return pkg;
            }
        }
Пример #31
0
        private void EnsurePackageFiles()
        {
            if (_files != null && _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary<string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            using (Stream stream = GetStream())
            {
                Package package = Package.Open(stream);

                _expandedFolderPath = GetExpandedFolderPath();

                // unzip files inside package
                var files = from part in package.GetParts()
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (PackagePart file in files)
                {
                    string path = UriUtility.GetPath(file.Uri);
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    using (Stream partStream = file.GetStream())
                    {
                        // only copy the package part to disk if there doesn't exist
                        // a file with the same name.
                        if (!_expandedFileSystem.FileExists(filePath))
                        {
                            using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                            {
                                partStream.CopyTo(targetStream);
                            }
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }
        public IPackage CreatePackage(
            string packageId,
            string packageVersion,
            string contentFilePath,
            License requiresLicenseAccept,
            params IPackage[] dependencies)
        {
            PackageBuilder builder = new PackageBuilder();
            ManifestMetadata metadata = new ManifestMetadata()
            {
                Authors = "dummy author",
                Version = new SemanticVersion(packageVersion).ToString(),
                Id = packageId,
                Description = "dummy description",
                LicenseUrl = "http://choosealicense.com/",
                RequireLicenseAcceptance = (requiresLicenseAccept == License.Required)
            };

            List<ManifestDependency> dependencyList = new List<ManifestDependency>();
            foreach (IPackage dependencyNode in dependencies)
            {
                dependencyList.Add(new ManifestDependency()
                {
                    Id = dependencyNode.Id,
                    Version = dependencyNode.Version.ToString(),
                });
            }

            List<ManifestDependencySet> dependencySetList = new List<ManifestDependencySet>()
            {
                new ManifestDependencySet()
                {
                    Dependencies = dependencyList
                }
            };
            metadata.DependencySets = dependencySetList;

            builder.Populate(metadata);

            PhysicalPackageFile file = new PhysicalPackageFile();
            file.SourcePath = contentFilePath;
            file.TargetPath = Path.GetFileName(contentFilePath);
            builder.Files.Add(file);

            string fileName = packageId + "." + metadata.Version + ".nupkg";
            string destinationName = Path.Combine(this.manager.LocalRepository.Source, fileName);

            using (Stream fileStream = File.Open(destinationName, FileMode.OpenOrCreate))
            {
                builder.Save(fileStream);
            }

            // Retrieve and return the newly-created package
            IPackage package = this.fakeRemoteRepo.FindPackage(packageId, new SemanticVersion(packageVersion));
            Assert.IsNotNull(package, "Test setup error: failed to create and retrieve a test package");

            return package;
        }
Пример #33
0
        private bool GeneratePackage(bool success, List<DiagnosticMessage> allDiagnostics, PackageBuilder packageBuilder, PackageBuilder symbolPackageBuilder, string nupkg, string symbolsNupkg)
        {
            var packDiagnostics = new List<DiagnosticMessage>();
            foreach (var sharedFile in _currentProject.Files.SharedFiles)
            {
                var file = new PhysicalPackageFile();
                file.SourcePath = sharedFile;
                file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile));
                packageBuilder.Files.Add(file);
            }

            var root = _currentProject.ProjectDirectory;

            if (_currentProject.Files.PackInclude != null && _currentProject.Files.PackInclude.Any())
            {
                AddPackageFiles(_currentProject.ProjectDirectory, _currentProject.Files.PackInclude, packageBuilder, packDiagnostics);
            }
            success &= !packDiagnostics.HasErrors();
            allDiagnostics.AddRange(packDiagnostics);

            foreach (var path in _currentProject.Files.SourceFiles)
            {
                var srcFile = new PhysicalPackageFile();
                srcFile.SourcePath = path;
                srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path));
                symbolPackageBuilder.Files.Add(srcFile);
            }

            // Write the packages as long as we're still in a success state.
            if (success)
            {
                using (var fs = File.Create(nupkg))
                {
                    packageBuilder.Save(fs);
                    _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(nupkg));
                }

                if (symbolPackageBuilder.Files.Any())
                {
                    using (var fs = File.Create(symbolsNupkg))
                    {
                        symbolPackageBuilder.Save(fs);
                        _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", _currentProject.Name, Path.GetFullPath(symbolsNupkg));
                    }
                }
            }

            WriteDiagnostics(packDiagnostics);
            return success;
        }
Пример #34
0
 public PhysicalPackageFile(PhysicalPackageFile file)
 {
     SourcePath = file.SourcePath;
     TargetPath = file.TargetPath;
 }
Пример #35
0
        public bool Build()
        {
            Runtime.Project project;
            if (!Runtime.Project.TryGetProject(_buildOptions.ProjectDir, out project))
            {
                WriteError(string.Format("Unable to locate {0}.'", Runtime.Project.ProjectFileName));
                return false;
            }

            var sw = Stopwatch.StartNew();

            var baseOutputPath = GetBuildOutputDir(_buildOptions);
            var configurations = _buildOptions.Configurations.DefaultIfEmpty("Debug");

            var specifiedFrameworks = _buildOptions.TargetFrameworks
                .ToDictionary(f => f, Runtime.Project.ParseFrameworkName);

            var projectFrameworks = new HashSet<FrameworkName>(
                project.GetTargetFrameworks()
                       .Select(c => c.FrameworkName));

            IEnumerable<FrameworkName> frameworks = null;

            if (projectFrameworks.Count > 0)
            {
                // Specified target frameworks have to be a subset of
                // the project frameworks
                if (!ValidateFrameworks(projectFrameworks, specifiedFrameworks))
                {
                    return false;
                }

                frameworks = specifiedFrameworks.Count > 0 ? specifiedFrameworks.Values : (IEnumerable<FrameworkName>)projectFrameworks;
            }
            else
            {
                frameworks = new[] { _applicationEnvironment.RuntimeFramework };
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(project, "prepack", GetScriptVariable))
            {
                WriteError(ScriptExecutor.ErrorMessage);
                return false;
            }

            if (!ScriptExecutor.Execute(project, "prebuild", GetScriptVariable))
            {
                WriteError(ScriptExecutor.ErrorMessage);
                return false;
            }

            var success = true;

            var allErrors = new List<string>();
            var allWarnings = new List<string>();

            var cacheContextAccessor = new CacheContextAccessor();
            var cache = new Cache(cacheContextAccessor);

            PackageBuilder packageBuilder = null;
            PackageBuilder symbolPackageBuilder = null;

            // Build all specified configurations
            foreach (var configuration in configurations)
            {
                if (_buildOptions.GeneratePackages)
                {
                    // Create a new builder per configuration
                    packageBuilder = new PackageBuilder();
                    symbolPackageBuilder = new PackageBuilder();
                    InitializeBuilder(project, packageBuilder);
                    InitializeBuilder(project, symbolPackageBuilder);
                }

                var configurationSuccess = true;

                baseOutputPath = Path.Combine(baseOutputPath, configuration);

                // Build all target frameworks a project supports
                foreach (var targetFramework in frameworks)
                {
                    _buildOptions.Reports.Information.WriteLine();
                    _buildOptions.Reports.Information.WriteLine("Building {0} for {1}",
                        project.Name, targetFramework.ToString().Yellow().Bold());

                    var errors = new List<string>();
                    var warnings = new List<string>();

                    var context = new BuildContext(_hostServices,
                                                   _applicationEnvironment,
                                                   cache,
                                                   cacheContextAccessor,
                                                   project,
                                                   targetFramework,
                                                   configuration,
                                                   baseOutputPath);

                    context.Initialize(_buildOptions.Reports.Quiet);

                    if (context.Build(warnings, errors))
                    {
                        if (_buildOptions.GeneratePackages)
                        {
                            context.PopulateDependencies(packageBuilder);
                            context.AddLibs(packageBuilder, "*.dll");
                            context.AddLibs(packageBuilder, "*.xml");
                            context.AddLibs(symbolPackageBuilder, "*.*");
                        }
                    }
                    else
                    {
                        configurationSuccess = false;
                    }

                    allErrors.AddRange(errors);
                    allWarnings.AddRange(warnings);

                    WriteDiagnostics(warnings, errors);
                }

                success = success && configurationSuccess;

                if (_buildOptions.GeneratePackages)
                {
                    // Create a package per configuration
                    string nupkg = GetPackagePath(project, baseOutputPath);
                    string symbolsNupkg = GetPackagePath(project, baseOutputPath, symbols: true);

                    if (configurationSuccess)
                    {
                        foreach (var sharedFile in project.SharedFiles)
                        {
                            var file = new PhysicalPackageFile();
                            file.SourcePath = sharedFile;
                            file.TargetPath = String.Format(@"shared\{0}", Path.GetFileName(sharedFile));
                            packageBuilder.Files.Add(file);
                        }

                        var root = project.ProjectDirectory;

                        foreach (var path in project.SourceFiles)
                        {
                            var srcFile = new PhysicalPackageFile();
                            srcFile.SourcePath = path;
                            srcFile.TargetPath = Path.Combine("src", PathUtility.GetRelativePath(root, path));
                            symbolPackageBuilder.Files.Add(srcFile);
                        }

                        using (var fs = File.Create(nupkg))
                        {
                            packageBuilder.Save(fs);
                            _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", project.Name, nupkg);
                        }

                        if (symbolPackageBuilder.Files.Any())
                        {
                            using (var fs = File.Create(symbolsNupkg))
                            {
                                symbolPackageBuilder.Save(fs);
                            }

                            _buildOptions.Reports.Quiet.WriteLine("{0} -> {1}", project.Name, symbolsNupkg);
                        }
                    }
                }
            }

            if (!ScriptExecutor.Execute(project, "postbuild", GetScriptVariable))
            {
                WriteError(ScriptExecutor.ErrorMessage);
                return false;
            }

            if (_buildOptions.GeneratePackages &&
                !ScriptExecutor.Execute(project, "postpack", GetScriptVariable))
            {
                WriteError(ScriptExecutor.ErrorMessage);
                return false;
            }

            sw.Stop();

            WriteSummary(allWarnings, allErrors);

            _buildOptions.Reports.Information.WriteLine("Time elapsed {0}", sw.Elapsed);
            return success;
        }
Пример #36
0
        private void EnsurePackageFiles()
        {
            if (_files != null &&
                _expandedFolderPath != null &&
                _expandedFileSystem.DirectoryExists(_expandedFolderPath))
            {
                return;
            }

            _files = new Dictionary<string, PhysicalPackageFile>();
            _supportedFrameworks = null;

            var packageName = new PackageName(Id, Version);

            // Only use the cache for expanded folders under %temp%.
            if (_expandedFileSystem == _tempFileSystem)
            {
                _expandedFolderPath = _cachedExpandedFolder.GetOrAdd(packageName, _ => GetExpandedFolderPath());
            }
            else
            {
                _expandedFolderPath = GetExpandedFolderPath();
            }

            using (Stream stream = GetStream())
            {
                Package package = Package.Open(stream);
                // unzip files inside package
                var files = from part in package.GetParts()
                            where ZipPackage.IsPackageFile(part)
                            select part;

                // now copy all package's files to disk
                foreach (PackagePart file in files)
                {
                    string path = UriUtility.GetPath(file.Uri);
                    string filePath = Path.Combine(_expandedFolderPath, path);

                    using (Stream partStream = file.GetStream())
                    {
                        using (Stream targetStream = _expandedFileSystem.CreateFile(filePath))
                        {
                            partStream.CopyTo(targetStream);
                        }
                    }

                    var packageFile = new PhysicalPackageFile
                    {
                        SourcePath = _expandedFileSystem.GetFullPath(filePath),
                        TargetPath = path
                    };

                    _files[path] = packageFile;
                }
            }
        }